<template>
  <div class="">
    <el-form ref="ref_form"
             :inline="false"
             :model="formData"
             :rules="dataRule"
             label-width="100px">
      <el-form-item label="事件分类"
                    label-width="150px"
                    prop="categoryId">
        <el-cascader class="cell-width-2"
                     ref="myCascader"
                     v-model="selCategoryArray"
                     :key="iscascaderShow"
                     :options="casOptions"
                     :props="optionProps"
                     :show-all-levels="false"
                     @change="handleChangeCate"></el-cascader>
      </el-form-item>
      <el-form-item label="服务内容"
                    label-width="150px"
                    prop="content">
        <el-input v-model="formData.content"
                  :autosize="{ minRows: 2, maxRows: 10 }"
                  type="textarea"
                  clearable
                  class="cell-width-area"
                  placeholder="请输入内容"></el-input>
      </el-form-item>

      <el-form-item label="服务类型"
                    label-width="150px"
                    prop="categoryCode">

        <el-cascader v-model="formData.categoryCode"
                     :options="demandOptions"
                     clearable
                     class="cell-width-1"
                     @change="handleCateSlect"></el-cascader>

      </el-form-item>

      <el-form-item label="服务时间"
                    label-width="150px"
                    prop="wantServiceTime">
        <el-date-picker v-model="formData.wantServiceTime"
                        type="datetime"
                        class="cell-width-1"
                        clearable
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="服务人"
                    label-width="150px"
                    prop="demandUserName">
        <el-input v-model="formData.demandUserName"
                  class="cell-width-1"></el-input>

      </el-form-item>
      <el-form-item label="联系电话"
                    label-width="150px"
                    prop="demandUserMobile">
        <el-input v-model="formData.demandUserMobile"
                  class="cell-width-1"></el-input>

      </el-form-item>
      <el-form-item label="服务地点"
                    prop="serviceLocation"
                    label-width="150px"
                    style="display: block">

        <el-input class="cell-width-1"
                  v-model="formData.serviceLocation">
        </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_map">

            </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-item label="门牌号"
                    label-width="150px"
                    prop="locationDetail">
        <el-input v-model="formData.locationDetail"
                  class="cell-width-1"></el-input>

      </el-form-item>

      <el-form-item label="服务方"
                    label-width="150px"
                    prop="serverId">

        <template>
          <el-select v-model="formData.serviceType"
                     class="cell-width-1"
                     placeholder="请选择"
                     clearable
                     @change="handleServiceChange('add', $event)">
            <el-option v-for="item in serviceOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
          -
          <el-select v-model="formData.serverId"
                     class="cell-width-1"
                     filterable
                     placeholder="请选择"
                     clearable>
            <el-option v-for="item in serviceOptiondList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-form-item>

    </el-form>

  </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 {
    operationType: '2',//处理方式[0:已回复 1:已转项目  2:已转服务]	
    icEventId: '',//事件Id	
    gridId: '',//	
    categoryCode: '',//	二级服务分类编码	
    parentCode: '',//	父级服务分类编码	
    content: '',//		服务内容1000字	
    reportType: 'self_help',//	社区帮办：community；楼长帮办：building_caption;党员帮办：party;自身上报：self_help	
    reportUserName: '',//	上报人姓名	
    reportUserMobile: '',//	自身上报时存储注册居民的手机号	
    reportTime: '',//	上报时间	
    demandUserId: '',//	服务人：user.id或者ic_resi_user.id	
    demandUserName: '',//	服务人姓名	
    demandUserMobile: '',//服务人联系电话	
    wantServiceTime: '',//	希望服务时间
    serviceType: '',
    serverId: '',
    locationDetail: '',
    serviceLocation: '',//事件地址	
    latitude: '',//	经度	
    longitude: '',//维度	
    categoryId: ''
  };
}
export default {
  data () {
    return {
      btnDisable: false,
      customerId: localStorage.getItem("customerId"),
      demandOptions: [],
      serviceOptions: [
        {
          label: "志愿者",
          value: "volunteer",
        },
        //  {
        //   label: '社会组织',
        //   value: 'social_org'
        // },
        {
          label: "社区自组织",
          value: "community_org",
        },
        {
          label: "区域党建单位",
          value: "party_unit",
        },
      ],
      serviceOptiondList: [],

      casOptions: [],
      iscascaderShow: 0,
      selCategoryArray: [],
      selCateObj: {},
      optionProps: {
        multiple: false,
        value: 'id',
        label: 'name',
        children: 'subCategory',
      },

      formData: iniFmData(),
      formDataTemp: {
        icEventId: "",
        serviceLocation: "34534534",
        categoryCode: "10030002",
        content: "341231",
        demandUserId: "",
        demandUserMobile: "15111111111",
        demandUserName: "123123",
        gridId: "",

        operationType: "2",
        parentCode: "1003",
        reportTime: "",
        reportType: "self_help",
        reportUserMobile: "",
        reportUserName: "",
        serverId: "cebe59b05d02715141762211bf57734f",
        serviceType: "volunteer",
        wantServiceTime: "2022-05-17 00:00:00",
        latitude: 36.069920462445104,
        locationDetail: "345345",
        longitude: 120.38677261825706,
        serviceLocation: "山东省青岛市市南区闽江路82号"
      },

      okflag: false,
      //地图相关
      keyWords: '',

      eventDetailCopy: {}
    };
  },
  components: {},
  computed: {
    dataRule () {

      return {
        categoryId: [
          { required: true, message: "请填写事件分类", trigger: "blur" },
        ],
        content: [
          { required: true, message: "服务内容不能为空", trigger: "blur" },
        ],
        categoryCode: [
          { required: true, message: "服务类型不能为空", trigger: "blur" },
        ],
        wantServiceTime: [
          { required: true, message: "服务时间不能为空", trigger: "blur" },
        ],
        demandUserName: [
          { required: true, message: "服务人不能为空", trigger: "blur" },
        ],
        demandUserMobile: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        serviceLocation: [
          { required: true, message: "服务地点不能为空", trigger: "blur" },
        ],
        serverId: [
          { required: true, message: "服务方不能为空", trigger: "blur" },
        ],

      };
    },


  },
  props: {

    demandUserId: {
      type: String,
      default: "",
    },
    demandUserName: {
      type: String,
      default: "",
    },
    demandUserMobile: {
      type: String,
      default: "",
    },
    eventId: {
      type: String,
      default: "",
    },

    eventDetailData: {
      type: Object,
      default () {
        return {}
      }
    },

  },
  watch: {
    demandUserName: function (val) {

      this.formData.reportUserName = val
      this.formData.demandUserName = val
    },
    demandUserMobile: function (val) {

      this.formData.reportUserMobile = val
      this.formData.demandUserMobile = val
    },
    demandUserId: function (val) {

      this.formData.demandUserId = val
    },
  },

  async mounted () {
    const { user } = this.$store.state
    this.agencyId = user.agencyId
    this.getCategoryList();
    this.getDemandOptions();
    // this.formData = { ...this.formDataTemp }
    this.initMap()

    if (this.eventId) {
      this.eventDetailCopy = JSON.parse(JSON.stringify(this.eventDetailData));
      this.formData.reportUserMobile = this.eventDetailCopy.mobile
      this.formData.reportUserName = this.eventDetailCopy.name
      this.formData.reportTime = this.eventDetailCopy.happenTime
      this.formData.gridId = this.eventDetailCopy.gridId


    } else {
      this.formData.demandUserName = this.demandUserName
      this.formData.demandUserMobile = this.demandUserMobile
      this.formData.demandUserId = this.demandUserId
    }

  },

  methods: {

    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.iscascaderShow
        this.casOptions = []


        this.casOptions = treeDataNew

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

    },

    handleChangeCate () {
      console.log(this.$refs["myCascader"].getCheckedNodes()[0].data)
      this.selCateObj = this.$refs["myCascader"].getCheckedNodes()[0].data
      this.formData.categoryId = this.selCateObj.id
    },

    //重构树，去除网格
    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
    },

    async getDemandOptions () {
      const url = "/heart/icresidemanddict/demandoption"
      let params = {}

      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.demandOptions = this.getFlagData(
          this.getTreeData(data),
          "usableFlag"
        );

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

    },

    getTreeData (data) {
      if (!Array.isArray(data)) return [];
      let arr = data.map((item) => {
        let _item = {};
        if (item.children) {
          if (item.children.length === 0)
            _item = { ...item, children: undefined };
          else _item = { ...item, children: this.getTreeData(item.children) };
        } else {
          _item = { ...item };
        }
        return _item;
      });
      return arr;
    },
    getFlagData (data, flag) {
      if (!Array.isArray(data)) return [];
      let arr1 = data.filter((item) => item[flag]);
      let arr2 = arr1.map((item) => {
        if (item.children)
          return { ...item, children: this.getFlagData(item.children, flag) };
        else return item;
      });
      // console.log('arrr-oppp', arr2)
      return arr2;
    },

    handleCateSlect (val) {
      console.log("val", val);
      if (val.length === 1) {
        this.demandOptions.forEach((item) => {
          if (item.value == val[0]) this.formData.parentCode = item.pvalue;
        });
        this.formData.categoryCode = val[0];
      } else {
        this.formData.parentCode = val[0];
        this.formData.categoryCode = val[1];
      }
    },

    handleServiceChange (type, val) {
      if (val === "social_org") {
        if (type === "add") this.getServiceuserList(val, "add_demand");
        else this.getServiceuserList(val, "query_demand");
      } else this.getServiceuserList(val, "");
    },

    async getServiceuserList (serviceType, query) {

      if (!serviceType) return false;
      const { demandUserId } = this.formData;
      const params = {
        serviceName: "",
        serviceType: serviceType,
        queryPurpose: query,
      };


      const url = "/heart/userdemand/servicelist"


      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.serviceOptiondList = data.filter(
          (item) => item.value != demandUserId
        );
      } else {
        this.$message.error(msg)
      }


    },

    async getDemandInfo () {
      this.okflag = false
      this.$refs["ref_form"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);

        } else {


          this.okflag = true
        }
      });
    },


    resetData () {

    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap () {
      // 定义地图中心点坐标
      var center = new window.TMap.LatLng(36.0722275, 120.38945519)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      map = new window.TMap.Map(document.getElementById('app_map'), {
        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.serviceLocation = result.result.address
          // 显示搜索到的地址
        });
    },



    // 开启加载动画
    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>
