<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>
            <el-button style="margin-left: 10px"
                       type="primary"
                       size="mini"
                       @click="handleShowPersonList">居民信息中选择</el-button>

          </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 class="avatar-uploader"
                       ref="uploadPic"
                       :action="uploadUlr"
                       list-type="picture-card"
                       :on-exceed="exceedPic"
                       :on-remove="removePic"
                       :file-list="replayImgList"
                       :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="address"
                        label-width="150px"
                        style="display: block">

            <el-input class="cell-width-1"
                      v-model="formData.address">
            </el-input>

          </el-form-item>
          <el-form-item label="位置坐标"
                        prop="longitude"
                        label-width="150px"
                        style="display: block">
            <div style="width:500px">

              <div class="div_map">
                <div id="app">

                </div>
                <div class="div_searchmap">
                  <el-input class="cell-width-map"
                            maxlength="50"
                            size="mini"
                            placeholder="请输入关键字"
                            v-model="keyWords">
                  </el-input>
                  <el-button style="margin-left: 10px"
                             type="primary"
                             size="mini"
                             @click="handleSearchMap">查询</el-button>
                </div>
              </div>

              <div style="margin-top: 10px">
                <span>经度</span>
                <el-input class="item_width_3"
                          maxlength="50"
                          placeholder="请输入经度"
                          v-model="formData.longitude">
                </el-input>
                <span style="margin-left: 20px">纬度</span>
                <el-input class="item_width_3"
                          maxlength="50"
                          placeholder="请输入纬度"
                          v-model="formData.latitude">
                </el-input>
              </div>
            </div>
          </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="请选择"
                       @change="handleChangeGrid"
                       clearable>
              <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="居民"
                        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 { 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详情

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

      qudaoArray: [

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

      formData: iniFmData(),
      formDataTemp: {
        address: "山东省青岛市市南区徐州路21号戊",
        // categoryList: ["1015", "1016"],
        eventContent: "asdfasdfasdfasdf",
        gridId: "63d5ff92ea981b1c58e4914ac894c610",
        happenTime: "2022-05-05 12:00:00",
        idCard: "211103190909090909",
        imageList: ["https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/internal/20220518/0818246db4cc4ac7bcd84bea69a8b38c.png"],
        latitude: 36.07120507831775,
        longitude: 120.38806572319174,
        mobile: "15111111111",
        name: "张三",
        reportUserId: "",
        sourceType: "1",
      },


      //地图相关
      keyWords: '',

      //图片相关  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: []
    };
  },
  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)
    },
  },

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

    this.initMap()
    this.formData = {
      ...this.formDataTemp
    }
  },

  methods: {
    handleShowPersonList () {
      this.personTableShow = true;
    },
    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
        console.log(selPerson)

        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
      }

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

      if (code === 0) {
        this.gridList = data

      } else {
        this.$message.error(msg)
      }

    },
    async getCategoryList () {
      const url = "/gov/issue/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)

    },
    exceedPic () {
      this.$message.warning("最多上传3张预览图片")

    },
    handleSuccess (response, file, fileList) {
      this.replayImgList.push(file)
      this.formData.imageList.push(response.data.url)

    },

    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap () {
      // 定义地图中心点坐标
      var center = new window.TMap.LatLng(36.0722275, 120.38945519)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      map = new window.TMap.Map(document.getElementById('app'), {
        center: center, // 设置地图中心点坐标
        zoom: 17.2, // 设置地图缩放级别
        pitch: 43.5, // 设置俯仰角
        rotation: 45 // 设置地图旋转角度
      })

      search = new window.TMap.service.Search({ pageSize: 10 })
      // 新建一个地点搜索类
      markers = new TMap.MultiMarker({
        map: map,
        geometries: []
      })
      infoWindowList = Array(10)

      geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类

      // 监听地图平移结束
      map.on('panend', () => {
        this.handleMoveCenter()
      })
      this.handleMoveCenter()
      this.convert()
    },

    setMarker (lat, lng) {
      markers.setGeometries([])
      markers.add([
        {
          id: '4',
          styleId: 'marker',
          position: new TMap.LatLng(lat, lng),
          properties: {
            title: 'marker4'
          }
        }
      ])
    },

    handleSearchMap () {
      infoWindowList.forEach((infoWindow) => {
        infoWindow.close()
      })
      infoWindowList.length = 0
      markers.setGeometries([])
      // 在地图显示范围内以给定的关键字搜索地点
      search
        .searchRectangle({
          keyword: this.keyWords,
          bounds: map.getBounds()
        })
        .then((result) => {
          let { data } = result
          if (Array.isArray(data) && data.length > 0) {
            const {
              location: { lat, lng }
            } = data[0]


            map.setCenter(new TMap.LatLng(lat, lng))
            this.setMarker(lat, lng)
            this.formData.latitude = lat
            this.formData.longitude = lng
            this.convert()
          } else {
            this.$message.error('未检索到相关位置坐标')
          }
        })
    },

    handleMoveCenter () {
      //修改地图中心点
      const center = map.getCenter()
      const lat = center.getLat()
      const lng = center.getLng()
      this.formData.latitude = lat
      this.formData.longitude = lng
      this.setMarker(lat, lng)
      this.convert(lat, lng)
    },

    convert (lat, lng) {
      markers.setGeometries([]);
      // var input = document.getElementById('location').value.split(',');
      let location
      if (lat && lng) {
        location = new TMap.LatLng(lat, lng);
      } else {
        location = new TMap.LatLng(this.formData.latitude, this.formData.longitude);
      }

      // map.setCenter(location);
      markers.updateGeometries([
        {
          id: 'main', // 点标注数据数组
          position: location,
        },
      ]);
      geocoder
        .getAddress({ location: location }) // 将给定的坐标位置转换为地址
        .then((result) => {
          this.formData.address = result.result.address
          // 显示搜索到的地址
        });
    },


    resetData () {

      this.formData = iniFmData();
      this.replayImgList = []
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: "正在加载……", // 加载中需要显示的文字
        background: "rgba(0,0,0,.7)", // 背景颜色
      });
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close();
      }
    },
  },
};
</script>
<style
  lang="scss"
  src="@/assets/scss/modules/shequzhili/event-info.scss"
  scoped
></style>





<style>
.el-dialog__body {
  padding: 0 10px 20px !important;
}
</style>
