<template>
  <div style="max-height: 82vh; overflow: auto; padding: 20px"
       class="form-class">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="150px">
      <!--<el-form-item label="所属组织名称" prop="orgName">-->
      <!--<el-select v-model="dataForm.orgName" placeholder="所属组织名称">-->
      <!--<el-option-->
      <!--v-for="item in organizationList"-->
      <!--:key="item.value"-->
      <!--:label="item.label"-->
      <!--:value="item.value"-->
      <!--&gt;-->
      <!--</el-option>-->
      <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item label="疫苗接种点名称"
                    prop="name">
        <el-input v-model="dataForm.name"
                  placeholder="疫苗接种点名称"
                  :disabled="dialogTitle == '查看'"></el-input>
      </el-form-item>
      <el-form-item label="接种时间"
                    :class="dataForm.noAvailableVaccines != '2' ? '' : 'time-class'">
        <div class="data-block">
          <div style="width: 30%">
            <el-date-picker v-model="dataForm.inoculationDate"
                            value-format="yyyy-MM-dd"
                            type="date"
                            :clearable="false"
                            placeholder="选择日期"
                            :disabled="dialogTitle == '查看'">
            </el-date-picker>
          </div>
          <div class="time-block">
            <div>
              <span>上午</span>
              <el-time-picker is-range
                              v-model="morningTime"
                              format="HH:mm"
                              value-format="HH:mm"
                              range-separator="至"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                              placeholder="选择时间范围"
                              @change="startTimeChange"
                              :disabled="dialogTitle == '查看'"
                              :clearable="false"
                              :editable="false"
                              style="width: 56%">
              </el-time-picker>
            </div>
            <div>
              <span>下午</span>
              <el-time-picker is-range
                              v-model="afterTime"
                              format="HH:mm"
                              value-format="HH:mm"
                              range-separator="至"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                              placeholder="选择时间范围"
                              @change="endTimeChange"
                              :disabled="dialogTitle == '查看'"
                              :clearable="false"
                              :editable="false"
                              style="width: 56%">
              </el-time-picker>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label=""
                    prop="noAvailableVaccines">
        <el-checkbox v-model="dataForm.noAvailableVaccines"
                     true-label="1"
                     false-label="2"
                     :disabled="dialogTitle == '查看'">暂无疫苗</el-checkbox>
      </el-form-item>
      <el-form-item label="咨询电话"
                    prop="mobile">
        <el-input v-model="dataForm.mobile"
                  :disabled="dialogTitle == '查看'"
                  placeholder="咨询电话"></el-input>
      </el-form-item>

      <el-form-item label="地图位置"
                    prop="longitude"
                    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_ymjzd"
               class="div_map"></div>
        </div>
      </el-form-item>

      <el-form-item label="接种点地址"
                    prop="address">
        <el-input v-model="dataForm.address"
                  placeholder="例:青岛市时代国际广场"
                  style="width: 65%"></el-input>

      </el-form-item>
    </el-form>
    <div class="submit">
      <el-button @click="closeSubmit">{{ $t("cancel") }}</el-button>
      <el-button v-if="dialogTitle != '查看'"
                 type="primary"
                 @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </div>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
import daiMap from "@/utils/dai-map";
import { requestPost, requestGet } from "@/js/dai/request";
var map;
var search;
var markers;
var geocoder;
var infoWindowList;
export default {
  data () {
    return {
      searchOptions: [],
      searchValue: '',
      resultList: [],
      loading: false,
      visible: false,
      dataForm: {
        id: "",
        customerId: "",
        orgId: "",
        orgName: "",
        pid: "",
        pids: "",
        name: "",
        inoculationDate: "",
        moStartTime: "",
        moEndTime: "",
        afStartTime: "",
        afEndTime: "",
        noAvailableVaccines: "1",
        mobile: "",
        address: "",
        longitude: "",
        latitude: "",
      },
      keyWords: null,
      // organizationList: [],
      morningTime: null,
      afterTime: null,
    };
  },
  computed: {
    dataRule () {
      return {
        customerId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        noAvailableVaccines: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        longitude: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        latitude: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  props: {
    dialogTitle: {
      type: String,
      default: "",
    },
  },
  methods: {
    startTimeChange () {
      if (Array.isArray(this.morningTime) && this.morningTime.length > 0) {
        let hour_0 = Number(this.morningTime[0].substring(0, 2));
        let hour_1 = Number(this.morningTime[1].substring(0, 2));
        let minute_0 = Number(this.morningTime[0].substring(3, 5));
        let minute_1 = Number(this.morningTime[1].substring(3, 5));
        let second_0 = Number(this.morningTime[0].substring(6, 8));
        let second_1 = Number(this.morningTime[1].substring(6, 8));
        if (hour_0 > 12 || hour_1 > 12) {
          this.$message.error("请选择00:00-12:00时间段的时间");
          this.morningTime = null;
          return false;
        }
        if (hour_0 == 12) {
          if (minute_0 > 0 || second_0 > 0) {
            this.$message.error("请选择00:00-12:00时间段的时间");
            this.morningTime = null;
            return false;
          }
        }
        if (hour_1 == 12) {
          if (minute_1 > 0 || second_1 > 0) {
            this.$message.error("请选择00:00-12:00时间段的时间");
            this.morningTime = null;
            return false;
          }
        }
        this.dataForm.moStartTime = this.morningTime[0];
        this.dataForm.moEndTime = this.morningTime[1];
      }
    },
    endTimeChange () {
      if (Array.isArray(this.afterTime) && this.afterTime.length > 0) {
        let hour_0 = Number(this.afterTime[0].substring(0, 2));
        let hour_1 = Number(this.afterTime[1].substring(0, 2));
        let minute_0 = Number(this.afterTime[0].substring(3, 5));
        let minute_1 = Number(this.afterTime[1].substring(3, 5));
        let second_0 = Number(this.afterTime[0].substring(6, 8));
        let second_1 = Number(this.afterTime[1].substring(6, 8));
        if (hour_0 < 12 || hour_1 < 12) {
          this.$message.error("请选择12:01-23:59时间段的时间");
          this.afterTime = null;
          return false;
        }
        // if (hour_0 == 12) {
        //   if (minute_0 == 0 && second_0 == 0) {
        //     this.$message.error("请选择12:01-23:59时间段的时间");
        //     this.afterTime = null;
        //     return false;
        //   }
        // }
        // if (hour_1 == 12) {
        //   if (minute_1 == 0 && second_1 == 0) {
        //     this.$message.error("请选择12:01-23:59时间段的时间");
        //     this.afterTime = null;
        //     return false;
        //   }
        // }
        this.dataForm.afStartTime = this.afterTime[0];
        this.dataForm.afEndTime = this.afterTime[1];
      }
    },
    closeSubmit () {
      this.resetData()
      this.$emit("closeDialog");
    },
    resetData () {
      this.searchValue = ''
      this.searchOptions = []
      this.resultList = []
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap (latitude, longitude) {

      map = new daiMap(
        document.getElementById("app_ymjzd"),
        { 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
    },
    // 获取所属组织列表
    // getFormInfo() {
    //   this.$http
    //     .post(`/gov/org/agency/community-list`)
    //     .then(({ data: res }) => {
    //       if (res.code !== 0) {
    //         return this.$message.error(res.msg);
    //       }
    //       this.organizationList = res.data;
    //     })
    //     .catch(() => {});
    // },
    async init () {
      this.visible = true;
      let { latitude, longitude } = this.$store.state.user;

      this.$refs["dataForm"].resetFields();
      if (this.dataForm.id) {
        await this.getInfo();
      } 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 getInfo () {

      let url = `/epmetuser/icPointVaccinesInoculation/${this.dataForm.id}`
      const { data, code, msg } = await requestGet(url)
      if (code === 0) {
        this.dataForm = {
          ...this.dataForm,
          ...data,
        };
        if (data.moStartTime !== "") {
          this.morningTime = [data.moStartTime, data.moEndTime];
        }
        if (data.afStartTime !== "") {
          this.afterTime = [data.afStartTime, data.afEndTime];
        }
      } else {
        this.$message.error(msg)
      }

      // this.$http
      //   .get(`/epmetuser/icPointVaccinesInoculation/${this.dataForm.id}`)
      //   .then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg);
      //     }
      //     this.dataForm = {
      //       ...this.dataForm,
      //       ...res.data,
      //     };
      //     if (res.data.moStartTime !== "") {
      //       this.morningTime = [res.data.moStartTime, res.data.moEndTime];
      //     }
      //     if (res.data.afStartTime !== "") {
      //       this.afterTime = [res.data.afStartTime, res.data.afEndTime];
      //     }

      //   })
      //   .catch(() => { });
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          if (
            !this.dataForm.inoculationDate &&
            this.dataForm.noAvailableVaccines === "2"
          ) {
            this.$message.error("请选择接种日期");
            return false;
          }
          if (
            this.morningTime === null &&
            this.dataForm.noAvailableVaccines === "2"
          ) {
            this.$message.error("请填写上午接种时间");
            return false;
          }
          if (
            this.afterTime === null &&
            this.dataForm.noAvailableVaccines === "2"
          ) {
            this.$message.error("请填写下午接种时间");
            return false;
          }
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/epmetuser/icPointVaccinesInoculation/",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(
                  res.internalMsg ? res.internalMsg : res.msg
                );
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.resetData()
                  this.visible = false;
                  this.$emit("refreshDataList");
                  this.closeSubmit();
                },
              });
            })
            .catch(() => { });
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
<style scoped>
.data-block {
  display: flex;
}
.time-block > div {
  margin-bottom: 10px;
}
.time-block span {
  padding: 10px;
}
.position_label >>> .el-form-item__label::before {
  color: #fff !important;
}
.submit {
  text-align: center;
  margin: auto;
}
.form-class .el-input {
  width: 75%;
}
.form-class .el-textarea {
  width: 75% !important;
}
.time-class {
  position: relative;
}
.time-class::before {
  content: "*";
  color: #f56c6c;
  position: absolute;
  left: 42px;
  top: 10px;
}
.div_map {
  position: relative;
  margin-top: 5px;
}
</style>
