<template>
  <el-row class="tansfer">
    <el-form ref="ref_form_demand" :inline="false" :model="formData" :rules="dataRule">
      <el-form-item label="" label-width="0" prop="content">
        <div class="items">
          <div class="label required">服务内容：</div>
          <div class="value">
            <el-input
                v-model="formData.content"
                :autosize="{ minRows: 2, maxRows: 10 }"
                class="cell-width-area"
                clearable
                placeholder="请输入内容"
                type="textarea"
            />
          </div>
        </div>
      </el-form-item>
      <el-col :span="12">
        <el-form-item label="" prop="categoryCode">
          <div class="items">
            <div class="label required">服务类型：</div>
            <div class="value">
              <el-cascader
                  v-model="formData.categoryCode"
                  :options="demandOptions"
                  class="cell-width-1"
                  clearable
                  @change="handleCateSlect"
              />
            </div>
          </div>

        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="" prop="wantServiceTime">
          <div class="items">
            <div class="label required">服务时间：</div>
            <div class="value">
              <el-date-picker
                  v-model="formData.wantServiceTime"
                  class="cell-width-1"
                  clearable placeholder="选择日期时间"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
              />
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="" prop="demandUserName">
          <div class="items">
            <div class="label required">需求人：</div>
            <div class="value">
              <el-input v-model="formData.demandUserName" class="cell-width-1"/>
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="" prop="demandUserMobile">
          <div class="items">
            <div class="label required">联系电话：</div>
            <div class="value">
              <el-input v-model="formData.demandUserMobile" class="cell-width-1"/>
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="" prop="serviceLocation" style="display: block">
          <div class="items">
            <div class="label required">服务地点：</div>
            <div class="value">
              <el-input v-model="formData.serviceLocation" class="cell-width-1"/>
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="" prop="longitude">
          <div class="items">
            <div class="label required">位置坐标：</div>
            <div class="value">
              <!--              <div class="div_searchmap">
                              <el-input
                                  v-model="keyWords"
                                  class="cell-width-map"
                                  maxlength="50"
                                  placeholder="请输入关键字"
                                  size="mini"
                              />
                              <el-button size="mini" style="margin-left: 10px" type="primary" @click="handleSearchMap">
                                查询
                              </el-button>
                            </div>-->
              <div id="app_map" style="width: 100%"></div>
            </div>

          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="" prop="locationDetail">
          <div class="items">
            <div class="label">门牌号：</div>
            <div class="value">
              <el-input v-model="formData.locationDetail" class="cell-width-1"/>
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="" prop="serverId">
          <div class="items">
            <div class="label required">服务组织：</div>
            <div class="value serviceOrg">
              <el-select
                  v-model="formData.serviceType"
                  class="cell-width-1"
                  clearable placeholder="请选择"
                  @change="handleServiceChange('add', $event)"
              >
                <el-option
                    v-for="item in serviceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <div class="line">-</div>
              <el-select
                  v-model="formData.serverId"
                  class="cell-width-1"
                  clearable
                  filterable
                  placeholder="请选择"
              >
                <el-option
                    v-for="item in serviceOptiondList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </div>
          </div>
        </el-form-item>
      </el-col>
    </el-form>
  </el-row>
</template>

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

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: 'community',//	社区帮办：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: [],
      serviceOptiondList: [],
      // casOptions: [],
      iscascaderShow: 0,
      // selCategoryArray: [],
      // selCateObj: {},
      // optionProps: {
      //     value: "id",
      //     label: "categoryName",
      //     children: "children",
      //     level: 'categoryType',
      //     checkStrictly: true
      // },
      formData: iniFmData(),
      okflag: false,
      //地图相关
      keyWords: '',
      eventDetailCopy: {}
    };
  },
  components: {},
  computed: {
    dataRule() {
      return {
        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 {}
      }
    },
    transferObj: {
      type: Object,
      default() {
        return {}
      }
    },
    source: {//展示来源：manage  管理平台    visiual  可视化平台
      type: String,
      default: 'manage'
    }
  },
  watch: {
    demandUserName: function (val) {
      this.formData.reportUserName = val
      this.formData.demandUserName = val
    },
    demandUserMobile: function (val) {
      this.formData.reportUserMobile = val
      this.formData.demandUserMobile = val
    },
    "transferObj.longitude": {
      handler(newVal, oldVal) {
        console.log(this.transferObj, 'transferObj')
        this.$nextTick(() => {
          var center = new window.TMap.LatLng(this.transferObj.latitude || 36.0722275, this.transferObj.longitude || 120.38945519)

          map.setCenter(center)
        })
      },
      immediate: true  // 页面加载立即执行
    },
    demandUserId: function (val) {
      this.formData.demandUserId = val
    },
    formData: {
      handler(val) {
        this.$emit('change', val)
      },
      deep: true
    }
  },
  created() {
  },
  async mounted() {
    const {user} = this.$store.state
    this.agencyId = user.agencyId
    // this.getCategoryList();

    console.log(this.eventId, this.eventDetailData, 'eventDetailDataeventDetailDataeventDetailDataeventDetailData')
    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
      this.formData.demandUserId = this.eventDetailCopy.reportUserId
      this.formData.demandUserName = this.eventDetailCopy.name
      this.formData.demandUserMobile = this.eventDetailCopy.mobile
    } else {
      this.formData.demandUserName = this.demandUserName
      this.formData.demandUserMobile = this.demandUserMobile
      this.formData.demandUserId = this.demandUserId
    }
    this.getDemandOptions();
    this.getServiceOption()
    this.initMap()
  },

  methods: {
    async getDemandOptions() {
      const url = "/governance/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)
      }
    },

    async getServiceOption() {
      const url = "/sys/dict/data/dictlist"
      let params = {dictType: "user_demand_service_type",}
      const {data, code, msg} = await requestPost(url, params)
      if (code === 0) {
        this.serviceOptions = data;
      } 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) {
      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];
      }
    },

    async handleServiceChange(serverOrgType, val) {
      if (!val) return false;
      if (this.formData.categoryCode == "") {
        this.$message.error("请先选择服务类型!");
        return;
      }
      const url = "/actual/base/serviceitem/listServerOrg";
      let params = {
        serviceTypeId: this.formData.categoryCode,
        serverOrgType: val,
        businessType: "resi_service",
      };
      let {data, code, msg} = await requestPost(url, params);
      if (code == 0) {
        this.serviceOptiondList = data;
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },
    async getServiceuserList(serviceType) {
      if (!serviceType) return false;
      const {demandUserId} = this.formData;
      const params = {
        serviceName: this.formData.categoryCode,
        serviceType: serviceType,
        queryPurpose: 'query',
      };
      const url = "/governance/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_demand"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);
          // this.formData.categoryId = this.selCateObj.id
        } else {
          this.okflag = true
        }
      });
    },
    resetData() {
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap() {
      // 定义地图中心点坐标
      console.log(this.transferObj, 'this.transferObjthis.transferObj')
      var center = new window.TMap.LatLng(this.transferObj.latitude || 36.0722275, this.transferObj.longitude || 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('click', (e) => {
        this.handleMoveCenter(e)
      })
      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(e) {
      //修改地图中心点
      const center = e.latLng;
      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' scoped>
.tansfer {

  .items {
    font-size: 14px;
    line-height: 34px;
    position: relative;
    display: flex;
    align-items: flex-start;
    margin-bottom: 17px;

    .label {
      width: 100px;
      white-space: nowrap;
      color: #9CB4D3;
    }

    .value {
      color: #FFFFFF;
    }
  }

  .required:before {
    margin-right: 5px;
    content: '*';
    color: #f00;
  }

  .serviceOrg {
    display: flex;
    align-items: center;
  }

  /deep/ .el-input .el-input__inner {
    width: 100% !important;
  }

  .cell-width-1 {
    width: 100%;
  }

  .value {
    width: calc(100% - 120px);
  }

  .cell-width-area {
    width: 100% !important;
  }

  .line {
    margin: 0 20px;
  }

  .div_searchmap {
    position: static;
    display: flex;
    align-items: center;
  }

  .cell-width-map {
    width: 100%;
  }
}

</style>