<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
               :inline="true"
               :model="dataForm"
               :rules="dataRule"
               :disabled="formType === 'detail'"
               class="form">
        <el-form-item label="中心名称	"
                      prop="centerName"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入中心名称	"
                    v-model="dataForm.centerName">
          </el-input>
        </el-form-item>

        <el-form-item label="办公电话"
                      prop="workPhone"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入办公电话"
                    v-model="dataForm.workPhone">
          </el-input>
        </el-form-item>

        <el-form-item label="办公时间"
                      prop="amStartTime"
                      label-width="150px"
                      style="display: block">
          <div class="row">
            <span>上午</span>
            <el-time-select style="margin-left: 10px"
                            v-model="dataForm.amStartTime"
                            :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '12:00',
              }"
                            placeholder="开始时间">
            </el-time-select>
            <span style="margin: 0 5px">至</span>
            <el-time-select v-model="dataForm.amEndTime"
                            :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '12:00',
                minTime: dataForm.amStartTime,
              }"
                            placeholder="结束时间">
            </el-time-select>
          </div>

          <div class="row"
               style="margin-top: 5px">
            <span>下午</span>
            <el-time-select style="margin-left: 10px"
                            v-model="dataForm.pmStartTime"
                            :picker-options="{
                start: '12:00',
                step: '00:30',
                end: '24:00',
              }"
                            placeholder="开始时间">
            </el-time-select>
            <span style="margin: 0 5px">至</span>
            <el-time-select v-model="dataForm.pmEndTime"
                            :picker-options="{
                start: '12:00',
                step: '00:30',
                end: '24:00',
                minTime: dataForm.pmStartTime,
              }"
                            placeholder="结束时间">
            </el-time-select>
          </div>
        </el-form-item>

        <el-form-item label="地图位置"
                      prop="longitude"
                      label-width="150px"
                      style="display: block">
          <div style="width: 500px">
            <el-select v-model="searchValue"
                       filterable
                       style="width: 500px"
                       remote
                       :reserve-keyword="true"
                       placeholder="请输入关键词"
                       :remote-method="remoteMethod"
                       :loading="loading">
              <el-option v-for="(item,index) in searchOptions"
                         @click.native="handleClickKey(index)"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
            <div id="app_dqfwzx"
                 class="div_map"></div>
          </div>
        </el-form-item>
        <el-form-item label="社区地址"
                      prop="address"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入社区地址	"
                    v-model="dataForm.address">
          </el-input>
        </el-form-item>

        <el-form-item label="可预约事项"
                      prop="matterList"
                      label-width="150px"
                      style="display: block">
          <div class="m-staffs">
            <div class="item"
                 :key="'staff' + index"
                 v-for="(item, index) in dataForm.matterList">
              <div class="item-info">
                <el-input class="item_width_1"
                          style="width: 150px"
                          maxlength="50"
                          show-word-limit
                          placeholder="事项名"
                          v-model="item.matterName"
                          :disabled="item.matterId != undefined" />
                <el-upload :headers="$getElUploadHeaders()"
                           :disabled="item.matterId != undefined"
                           class="avatar-uploader"
                           :action="uploadUlr"
                           :data="{ customerId: customerId }"
                           :show-file-list="false"
                           :on-success="
                    (response, file, fileList) =>
                      handleImgSuccess(index, response, file, fileList)
                  "
                           :before-upload="beforeImgUpload">
                  <img v-if="item.matterImg"
                       :src="item.matterImg"
                       style="width: 36px; height: 36px"
                       class="function-icon" />
                  <i v-else
                     class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>

                <div class="hint">（事项封面，图片小于1M）</div>
              </div>

              <div class="item-pic">
                <el-select style="width: 150px; margin-left: 0"
                           v-model="item.appointmentType"
                           filterable
                           placeholder="预约类型"
                           :disabled="item.matterId != undefined">
                  <el-option v-for="item in appointmentTypeOptions"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
                <el-select v-if="item.appointmentType==='custom'"
                           style="width: 300px; margin-left: 10px"
                           v-model="item.customList"
                           filterable
                           multiple
                           placeholder="请选择"
                           :disabled="item.matterId != undefined">
                  <el-option v-for="item in customOption"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="item-pic"
                   style="margin-top:20px;">
                <el-time-select style="width: 150px; "
                                v-model="item.startTime"
                                :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '24:00',
                  }"
                                placeholder="开始时间"
                                :disabled="item.matterId != undefined">
                </el-time-select>
                <span style="margin: 0 5px">至</span>
                <el-time-select style="width: 150px"
                                v-model="item.endTime"
                                :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '24:00',
                    minTime: item.startTime,
                  }"
                                placeholder="结束时间"
                                :disabled="item.matterId != undefined">
                </el-time-select>
                <el-button style="margin-left: 20px"
                           size="small"
                           @click="handleDelStaff(index)">删除</el-button>
              </div>

            </div>

            <div class="item-add">
              <el-button size="small"
                         type="warning"
                         @click="handleAddStaff">添加</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 v-if="formType != 'detail'"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Loading } from "element-ui"; // 引入Loading服务
import { requestPost } from "@/js/dai/request";
import daiMap from "@/utils/dai-map";

var map;
var search;
var markers;
var infoWindowList;
let loading; // 加载动画
var geocoder; // 新建一个正逆地址解析类

export default {
  data () {
    return {
      uploadUlr: window.SITE_CONFIG["apiURL"] + "/oss/file/uploadqrcodeV2",
      customerId: "",

      formType: "add", //表单操作类型 add新增，edit编辑，detail详情
      searchOptions: [],
      searchValue: '',
      resultList: [],
      loading: false,

      btnDisable: false,

      partyServiceCenterId: "",

      appointmentTypeOptions: [
        {
          label: "每天",
          value: "everyDay",
        },
        {
          label: "工作日",
          value: "workDay",
        },
        {
          label: "周末",
          value: "weekend",
        },
        {
          label: "自定义",
          value: "custom",
        },
      ],
      customOption: [
        {
          label: "周日",
          value: "1",
        },
        {
          label: "周一",
          value: "2",
        },
        {
          label: "周二",
          value: "3",
        },
        {
          label: "周三",
          value: "4",
        },
        {
          label: "周四",
          value: "5",
        },
        {
          label: "周五",
          value: "6",
        },
        {
          label: "周六",
          value: "7",
        },

      ],

      dataForm: {
        centerName: "",
        address: "",
        workPhone: "",
        amStartTime: "",
        amEndTime: "",
        pmStartTime: "",
        pmEndTime: "",
        longitude: "",
        latitude: "",
        matterList: [],
        delMatterList: [],
        locationAddress: "",
      },
    };
  },
  components: {},
  computed: {
    dataRule () {
      return {
        centerName: [
          { required: true, message: "中心名称	不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "中心名称	长度在 1 到 50个字符",
            trigger: "blur",
          },
        ],
        address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
        amStartTime: [
          { required: true, message: "办公时间不能为空", trigger: "blur" },
        ],
        amEndTime: [
          { required: true, message: "办公时间不能为空", trigger: "blur" },
        ],
        pmStartTime: [
          { required: true, message: "办公时间不能为空", trigger: "blur" },
        ],
        pmEndTime: [
          { required: true, message: "办公时间不能为空", trigger: "blur" },
        ],
        workPhone: [
          { required: true, message: "办公电话不能为空", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "位置坐标不能为空", trigger: "blur" },
        ],
      };
    },
  },
  props: {},
  watch: {},

  async mounted () {
    this.customerId = localStorage.getItem("customerId");

  },

  methods: {
    handleImgSuccess (index, res, file) {
      if (res.code === 0 && res.msg === "success") {
        console.log("res.data.url", res.data.url);
        this.dataForm.matterList[index].matterImg = res.data.url;
      } else {
        this.$message.error(res.msg);
      }
    },

    beforeImgUpload (file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isLt1M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      return isLt1M;
    },

    handleAddStaff () {
      this.dataForm.matterList = [
        ...this.dataForm.matterList,
        {
          matterName: "",
          appointmentType: "",
          matterImg: "",
          startTime: "",
          endTime: "",
          customDay: "",
          customList: []
        },
      ];
    },
    async handleDelStaff (index) {
      const { matterList } = this.dataForm;
      let list = [...matterList];
      let delItem = list.splice(index, 1);
      console.log(delItem);
      if (delItem[0].matterId) {
        if (!confirm("删除后无法恢复，确认删除？"))
          return console.log("不删了");
        if (!(await this.delStaff(delItem[0].matterId))) return;
        this.dataForm.delMatterList = [
          ...this.dataForm.delMatterList,
          delItem[0].matterId,
        ];
      }

      this.dataForm.matterList = list;
    },
    async delStaff (matterId) {
      const { data, code, msg } = await requestPost(
        "/gov/org/icpartyservicecenter/delmatter",
        {
          matterId,
        }
      );
      return code === 0;
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap (latitude, longitude) {

      map = new daiMap(
        document.getElementById("app_dqfwzx"),
        { latitude, longitude },
        {
          zoom: 16.2, // 设置地图缩放级别
          pitch: 43.5, // 设置俯仰角
          rotation: 45, // 设置地图旋转角度
        }
      );

      // 监听地图平移结束
      map.on("dragend", (e) => {
        this.handleMoveCenter(e);
      });

      map.setCenter(latitude, longitude);
      map.setMarker(latitude, longitude);

    },


    async handleMoveCenter () {
      //修改地图中心点
      const { lat, lng } = map.getCenter();
      this.dataForm.latitude = lat;
      this.dataForm.longitude = lng;
      map.setMarker(lat, lng);

      let { msg, data } = await map.getAddress(lat, lng);
      if (msg == "success") {
        this.dataForm.address = data.address
        this.searchValue = data.address
        this.searchOptions = []

      }
    },

    async remoteMethod (query) {

      if (query !== '') {
        this.loading = true;

        const { msg, data } = await map.searchNearby(query);
        this.loading = false;
        this.resultList = []

        if (msg == "success" && data.resultList && data.resultList.length > 0) {

          if (data.resultList && data.resultList.length > 0) {
            this.resultList = data.resultList
            this.searchOptions = this.resultList.map(item => {
              return { value: `${item.hotPointID}`, label: `${item.address + item.name}` };

            });
          }
        } else {
          this.searchOptions = [
            {
              value: '0',
              label: '未检索到结果'
            }
          ]
        }
      } else {
        this.searchOptions = [];
      }
    },

    handleClickKey (index) {
      let selPosition = this.resultList[index]
      let lonlat = selPosition.lonlat.split(" ")
      map.setCenter(lonlat[1], lonlat[0]);
      map.setMarker(lonlat[1], lonlat[0]);
      this.dataForm.latitude = lonlat[1];
      this.dataForm.longitude = lonlat[0];
      this.dataForm.address = selPosition.address + selPosition.name
    },


    async initForm (type, row) {
      this.$refs.ref_form.resetFields();
      let { latitude, longitude } = this.$store.state.user;
      this.formType = type;
      console.log(row);
      if (row) {
        this.dataForm = { ...this.dataForm, ...row };
        this.partyServiceCenterId = this.dataForm.partyServiceCenterId;

        this.dataForm.matterList.forEach(element => {
          if (element.customDay) {
            element.customList = element.customDay.split(',')
          } else {
            element.customList = []
          }

        });

      } else {
        this.dataForm.latitude = latitude
        this.dataForm.longitude = longitude
      }

      this.$nextTick(() => {
        if (!map) {
          this.initMap(this.dataForm.latitude, this.dataForm.longitude)
        } else {
          map.setCenter(this.dataForm.latitude, this.dataForm.longitude);
          map.setMarker(this.dataForm.latitude, this.dataForm.longitude);

        }

      })
    },

    async handleComfirm () {
      this.btnDisable = true;
      setTimeout(() => {
        this.btnDisable = false;
      }, 5000);
      this.$refs["ref_form"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);
          this.btnDisable = false;
        } else {
          this.submit();
        }
      });
    },

    async submit () {
      let url = "";
      if (this.formType === "add") {
        url = "/gov/org/icpartyservicecenter/addpartyservicecenter";
        // url = "http://yapi.elinkservice.cn/mock/245/gov/org/neighborhood/neighborhoodadd"
      } else {
        url = "/gov/org/icpartyservicecenter/editpartyservicecenter";

        this.dataForm.partyServiceCenterId = this.partyServiceCenterId;
      }

      const matterList = this.dataForm.matterList.filter(
        (item) => !item.matterId
      );

      if (

        matterList.some(
          (item) =>

            !item.matterImg ||
            !item.matterName ||
            !item.appointmentType ||
            !item.startTime ||
            !item.endTime || (item.appointmentType === 'custom' && item.customList.length === 0)
        )
      ) {
        return this.$message({
          type: "warning",
          message: "请补充完整可预约事项信息",
        });
      }

      matterList.forEach(element => {
        element.customDay = element.customList.join(',')
      });



      const { data, code, msg } = await requestPost(url, {
        ...this.dataForm,
        matterList,
      });

      if (code === 0) {
        this.$message({
          type: "success",
          message: "操作成功",
        });
        this.resetData();
        this.$emit("dialogOk");
        this.btnDisable = false;
      } else {
        this.btnDisable = false;
        this.$message.error(msg);
      }
    },

    handleCancle () {
      this.resetData();
      this.$emit("dialogCancle");
    },
    resetData () {
      this.searchValue = ''
      this.searchOptions = []
      this.resultList = []

      this.partyServiceCenterId = "";
      this.dataForm = {
        centerName: "",
        address: "",
        workPhone: "",
        amStartTime: "",
        amEndTime: "",
        pmStartTime: "",
        pmEndTime: "",
        longitude: "",
        latitude: "",
        matterList: [],
        delMatterList: [],
        locationAddress: "",
      };
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: "正在加载……", // 加载中需要显示的文字
        background: "rgba(0,0,0,.7)", // 背景颜色
      });
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>

<style lang="scss" scoped>
.m-staffs {
  margin-left: auto;
  width: 520px;

  .item {
    // display: flex;
    // align-items: flex-start;
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 4px dashed #f7f8f9;

    .item-info {
      display: flex;
      align-items: flex-start;
      margin: 0 0;
      // margin-bottom: 7px;

      .avatar-uploader {
        margin: 0 0 0 20px;

        ::v-deep .el-upload {
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }
        img {
          object-fit: cover;
        }
        .el-upload:hover {
          border-color: #409eff;
        }
        .avatar {
          width: 36px;
          height: 36px;
          display: block;
        }
        .avatar-uploader-icon {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          font-size: 28px;
          color: #8c939d;
          width: 36px;
          height: 36px;
          line-height: 36px;
          text-align: center;
        }
      }
      .hint {
        // width: 75%;
        font-size: 14px;
        color: #999999;
        margin-left: 0;
      }
    }
    .item-pic {
      display: flex;
      align-items: center;
      // justify-content: space-around;
    }
  }
}
</style>
