<template>
  <div class="g-add">
    <div class="g-add-page">
      <div class="g-left">
        <el-form ref="ref_form1"
                 :inline="true"
                 :model="formData"
                 :rules="dataRule"
                 class="form">
          <el-form-item label="所属网格	"
                        prop="gridId"
                        label-width="150px"
                        style="display: block">
            <el-select v-model.trim="formData.gridId"
                       placeholder="请选择"
                       clearable
                       class="cell-width-1">
              <el-option v-for="item in gridList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="报事人"
                        prop="name"
                        label-width="150px"
                        style="display: block">
            <el-input class="cell-width-1"
                      maxlength="10"
                      placeholder="请输入报事人姓名"
                      v-model="formData.name">
            </el-input>
            <div>
              <el-button style="margin-top: 10px"
                         type="primary"
                         size="mini"
                         @click="handleShowPersonList">居民信息中选择</el-button>
            </div>
          </el-form-item>
          <el-form-item label="手机号"
                        prop="mobile"
                        label-width="150px"
                        style="display: block">
            <el-input class="cell-width-1"
                      maxlength="30"
                      placeholder="请输入手机号	"
                      v-model="formData.mobile">
            </el-input>
          </el-form-item>

          <el-form-item label="证件号"
                        prop="idCard"
                        label-width="150px"
                        style="display: block">
            <el-input class="cell-width-1"
                      maxlength="30"
                      placeholder="请输入证件号"
                      v-model="formData.idCard"></el-input>
          </el-form-item>

          <el-form-item label="反应渠道"
                        label-width="150px"
                        prop="sourceType">
            <el-select v-model="formData.sourceType"
                       placeholder="请选择"
                       size="small"
                       clearable
                       class="cell-width-1">
              <el-option v-for="item in qudaoArray"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="发生时间"
                        prop="happenTime"
                        label-width="150px"
                        style="display: block">
            <el-date-picker v-model="formData.happenTime"
                            class="cell-width-1"
                            type="datetime"
                            placeholder="发生时间"
                            value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="事件内容"
                        prop="eventContent"
                        label-width="150px"
                        style="display: block">
            <el-input class="cell-width-2"
                      type="textarea"
                      maxlength="500"
                      show-word-limit
                      :rows="5"
                      placeholder="请输入事件内容，不超过500字"
                      v-model="formData.eventContent"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="g-right">
        <el-form ref="ref_form2"
                 :inline="true"
                 :model="formData"
                 :rules="dataRule"
                 class="form">
          <el-form-item label="图片"
                        label-width="150px"
                        style="display: block">
            <el-upload :headers="$getElUploadHeaders()"
                       :class="['avatar-uploader', { hide: hideUploadBtn }]"
                       ref="uploadPic"
                       :action="uploadUlr"
                       list-type="picture-card"
                       :on-exceed="exceedPic"
                       :on-remove="removePic"
                       :file-list="replayImgList"
                       :on-change="handleEditChange"
                       :on-success="handleSuccess"
                       :limit="3">
              <span class="font-14">选择图片</span>
              <div slot="tip"
                   class="upload_tip">
                最多上传3张图片，图片支持jpg、jpeg、bmp、git或png格式
              </div>
            </el-upload>
          </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_event"
                   class="div_map"></div>
            </div>
          </el-form-item>

          <el-form-item label="详细地址"
                        prop="address"
                        label-width="150px"
                        style="display: block">
            <el-input class="cell-width-1"
                      v-model="formData.address">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 新增弹出框 -->
    <el-dialog :visible.sync="personTableShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :destroy-on-close="true"
               title="选择居民"
               width="550px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <div style="padding: 10px 30px">
        <el-form :inline="false"
                 ref="ref_formSearch"
                 :label-width="'90px'">
          <el-form-item label="所属网格"
                        label-width="150px">
            <el-select class="cell-width-1"
                       v-model.trim="selGridId"
                       placeholder="请选择"
                       clearable>
              <el-option v-for="item in gridList"
                         @click.native="handleChangeGrid"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="居民"
                        label-width="150px"
                        prop="selPersonIndex">
            <el-select v-model="selPersonIndex"
                       class="cell-width-1"
                       filterable
                       placeholder="请选择"
                       clearable>
              <el-option v-for="(item, index) in demandUserList"
                         :key="item.demandUserId"
                         :label="item.label"
                         :value="index">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="div-btn">
          <el-button style="margin-left: 20px"
                     type="primary"
                     size="small"
                     @click="handleComfirmSelPerson">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

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

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

function iniFmData () {
  return {

    gridId: "", //所属网格
    reportUserId: "", //	报事人ID
    name: "", //	报事人姓名
    mobile: "", //	手机号
    idCard: "", //	证件号
    sourceType: "", //	反映渠道
    happenTime: "", //发生时间
    eventContent: "", //	事件内容
    imageList: [], //	图片集合
    // categoryList: [],//	二类分类Id
    address: "", //事件地址
    latitude: "", //	经度
    longitude: "", //维度
    // operationType: '',//	处理方式
    // content: '',//回复内容
    // status: '',//	处理中：processing；已办结：closed_case
  };
}

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

      btnDisable: false,
      gridList: [], //所属网格list--场所区域

      qudaoArray: [
        {
          value: "1",
          label: "多媒体反应",
        },
        {
          value: "2",
          label: "社区电话",
        },
        {
          value: "3",
          label: "12345",
        },
        {
          value: "4",
          label: "网络员手持终端",
        },
      ],

      formData: iniFmData(),

      //地图相关
      keyWords: "",
      isFirst: true, //地图是否首次加载，首次加载不给地址赋值

      //图片相关  oss/file/uploadvariedfile
      dialogImageUrl: "oss/file/uploadvariedfile",
      uploadUlr: window.SITE_CONFIG["apiURL"] + "/oss/file/uploadvariedfile",
      //  upload_url: '', // 上传URL
      upload_name: "", // 图片或视频名称
      replayImgList: [],

      okflag: false,

      formDataSearch: {
        gridId: "",
        name: "",
      },
      personTableShow: false,
      selGridId: "",
      selPersonIndex: "",
      selPerson: {},
      demandUserList: [],

      hideUploadBtn: false,
    };
  },
  components: {},
  computed: {
    dataRule () {
      let checkIdCard = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入证件号"));
        } else {
          if (!isCard(value)) {
            callback(new Error("证件号格式不正确"));
          }
          callback();
        }
      };

      return {
        gridId: [
          { required: true, message: "所属网格不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "报事人不能为空", trigger: "blur" }],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
        ],
        // idCard: [
        //   { required: true, message: "证件号不能为空", trigger: "blur" },
        //   { required: true, validator: checkIdCard, trigger: "blur" },
        // ],
        sourceType: [
          { required: true, message: "反映渠道不能为空", trigger: "blur" },
        ],
        eventContent: [
          { required: true, message: "事件内容不能为空", trigger: "blur" },
        ],
        happenTime: [
          { required: true, message: "发生时间不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "事件地址不能为空", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "坐标位置不能为空", trigger: "blur" },
        ],
      };
    },
  },
  props: {},
  watch: {
    "formData.name": function (val) {
      this.$emit("changeName", val);
    },
    "formData.mobile": function (val) {
      this.$emit("changeMobile", val);
    },
    "formData.reportUserId": function (val) {
      this.$emit("changeUserId", val);
    },
    "formData.gridId": function (val) {
      this.selGridId = val;
      this.$emit("changeGridId", val);
    },
  },

  async mounted () {
    const { user } = this.$store.state;
    this.agencyId = user.agencyId;

    let { latitude, longitude } = this.$store.state.user;
    if (!latitude || latitude == "" || latitude == "0") {
      latitude = 39.9088810666821;
      longitude = 116.39743841556731;
    }

    this.formData.latitude = latitude;
    this.formData.longitude = longitude;


    this.initMap(this.formData.latitude, this.formData.longitude);


    this.loadGrid();
    this.getCategoryList();
  },

  methods: {
    async handleShowPersonList () {
      if (this.formData.gridId) {
        await this.handleChangeGrid();
        this.personTableShow = true;
      } else {
        this.$message.info("请先选择网格");
      }
    },
    diaClose () {
      this.personTableShow = false;
    },
    handleComfirmSelPerson () {
      if (this.selPersonIndex === 0 || this.selPersonIndex) {
        let selPerson = this.demandUserList[this.selPersonIndex];
        this.formData.name = selPerson.demandUserName;
        this.formData.mobile = selPerson.demandUserMobile;
        this.formData.reportUserId = selPerson.demandUserId;
        this.formData.idCard = selPerson.idCard;

        this.personTableShow = false;
      } else {
        this.$message.info("请选择人员");
      }
    },

    async handleChangeGrid () {
      const url = "/epmetuser/icresiuser/demandusers";
      // const url = "http://yapi.elinkservice.cn/mock/245/epmetuser/epidemicPrevention/page"
      let params = {
        agencyId: "",
        gridId: this.selGridId,
        name: "",
      };

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.demandUserList = data;
      } else {
        this.$message.error(msg);
      }
      this.tableLoading = false;
    },

    async loadGrid () {
      const url = "/gov/org/customergrid/gridoption";

      let params = {
        agencyId: this.agencyId,
        purpose: "addorupdate",
      };

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.gridList = data;
      } else {
        this.$message.error(msg);
      }
    },
    async getCategoryList () {
      const url = "/governance/issueprojectcategorydict/list";

      let params = {};

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        let treeDataNew = this.filterTree(data);
        // this.categrayList = data
        //组织级联数据
        ++this.iscascaderShow;
        this.casOptions = [];
        this.selCategoryArray = [];

        this.casOptions = treeDataNew;
      } else {
        this.$message.error(msg);
      }
    },

    //重构树，去除网格
    filterTree (arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].subCategory) {
          if (childs[i].subCategory.length) {
            this.filterTree(childs[i].subCategory);
          } else {
            delete childs[i].subCategory;
          }
        }
      }
      return arr;
    },

    handleChangeAgency (value) {
      // this.agencyName = this.$refs["myCascader"].getCheckedNodes()[0].label
      // this.orgId = this.selCategoryArray.length > 0 ? this.selCategoryArray[this.selCategoryArray.length - 1] : ''
    },

    async getEventInfo () {
      this.okflag = false;
      this.$refs["ref_form1"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);
          return false;
        } else {
          this.$refs["ref_form2"].validate((valid, messageObj) => {
            if (!valid) {
              app.util.validateRule(messageObj);
              return false;
            } else {
              if (!formVltHelper.userOrMobile(this.formData.mobile)) {
                this.$message({
                  type: "error",
                  message: "手机号格式有误",
                });
                return false;
              }

              const regCard = /(^\d{15}$)|(^\d{17}(\d|X)$)/; //证件号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
              if (
                this.formData.idCard &&
                regCard.test(this.formData.idCard) === false
              ) {
                this.$message({
                  type: "warning",
                  message: "请输入正确的证件号码",
                });
                return false;
              }
              this.okflag = true;
            }
          });
        }
      });
    },

    removePic (file, fileList) {
      this.formData.imageList.splice(
        this.formData.imageList.findIndex((item) => item === file.url),
        1
      );
      this.replayImgList.splice(
        this.replayImgList.findIndex((item) => item.uid === file.uid),
        1
      );
      this.hideUploadBtn = fileList.length >= 3;
    },
    // 最多上传3张图，超过时隐藏上传按钮
    handleEditChange (file, fileList) {
      this.hideUploadBtn = fileList.length >= 3;
    },
    exceedPic () {
      this.$message.warning("最多上传3张预览图片");
    },
    handleSuccess (response, file, fileList) {
      this.replayImgList.push(file);
      this.formData.imageList.push(response.data.url);
    },

    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap (latitude, longitude) {

      map = new daiMap(
        document.getElementById("app_event"),
        { 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.formData.latitude = lat;
      this.formData.longitude = lng;
      map.setMarker(lat, lng);

      let { msg, data } = await map.getAddress(lat, lng);
      if (msg == "success") {
        this.formData.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.formData.latitude = lonlat[1];
      this.formData.longitude = lonlat[0];
      this.formData.address = selPosition.address + selPosition.name
    },

    resetData () {
      this.formData = iniFmData();
      this.replayImgList = [];
      this.searchValue = ''
      this.searchOptions = []
      this.resultList = []
    },
    // 开启加载动画
    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/shequzhili/event-info.scss";

.item_width_4 {
  width: 350px;
}

.div_map {
  margin-top: 10px;
}
</style>

<style lang="scss">
.el-dialog__body {
  padding: 0 10px 20px !important;
}

.hide {
  .el-upload--picture-card {
    display: none !important;
  }
}
</style>
