<template>
    <a-form
      :model="form"
      ref="formRef"
      label-align="left"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-row>
        <a-col :span="12">
          <a-form-item
            label="上报来源"
          >
            <span class="ant-form-text">{{ form.applySource }}</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="运营区域"
          >
            <span class="ant-form-text">{{ form.regionName }}</span>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item
            label="昵称"
          >
            <span class="ant-form-text">{{ form.applyNickname }}</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="用户手机"
          >
            <span class="ant-form-text">{{ form.applyPhone }}</span>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item
            label="反馈时间"
          >
            <span class="ant-form-text">{{ form.applyTime }}</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="申请原因"
          >
            <span class="ant-form-text">{{ form.applyReason }}</span>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="反馈位置"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <span class="ant-form-text">{{ form.applyPosition }}</span>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <div class="map-container" style="width: auto; height: 300px;margin: 0px 0px 30px 0px;border: 1px solid #a1a1a1;">
            <tlbs-map
                ref="mapRef"
                :api-key="config.map.apiKey"
                :center="center"
                zoom="16"
                :control="control"
                :options="options"
                @map_inited="onMapInited"
            >
          </tlbs-map>
          </div>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="处理状态"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            required
            name="dealState"
            :rules="[{ required: true, message: '请选择处理状态' }]"
          >
            <a-select v-model:value="form.dealState" placeholder="请选择处理状态">
              <a-select-option value="1">处理中</a-select-option>
              <a-select-option value="2">已处理</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="备注"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            name="dealNote"
          >
            <a-textarea v-model:value="form.dealNote" placeholder="请输入备注"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import { callOrder, callOperate } from '@/apis/call.js'
  import { message } from 'ant-design-vue'
  import config from '@/utils/config.js'
  import { dataFormat } from '@/utils/tools'
  import { getCache } from '@/utils/authority';
  
  const formRef = ref();
  const formData = () => ({
    id: "",
    applySource: "",
    applyPosition: "",
    applyLng: 0,
    applyLat: 0,
    applyNickname: "",
    applyPhone: "",
    applyTime: "",
    applyReason: "",
    regionId: "",
    regionName: "",
    dealId: "",
    dealState: "",
    dealUser: "",
    dealTime: "",
    dealNote: ""
  });
  const form = ref(formData());

  const mapRef = ref(null);
  const center = ref(config.map.center);
  const control = ref({ scale: {}, zoom: { position: 'topRight',},});
  const options = ref({ renderOptions: { renderOptions: true, }});
  const dataRegion = ref({});

  const onMapInited = () => {
      if (mapRef.value) {
          const calculatedWidth = document.getElementsByClassName("map-container")[0].offsetWidth;
          const calculatedHeight = document.getElementsByClassName("map-container")[0].offsetHeight-4;
          // 调用地图实例的 resize 方法
          const map = mapRef.value.map;
          if (map) {
              map.resize(calculatedWidth, calculatedHeight);
          }
      }
      console.log(mapRef.value);
  };

  const openForm = (params = {}) => {
    // Object.assign(form.value, formData());
    // formRef.value.resetFields();
    form.value = {
      ...formData(),
      ...params,
    }
    form.value.dealState = params['dealState'] == '0'? '' : params['dealState']
    loadMarker();
    // if (params['id']) {
    //   form.value.id = params['id']
    //   callOrder("/ebikeUserBacksite/getInfo?id="+ params['id'], {}, "get").then(res => {
    //     if (res.code == 200) {
    //       if (res.data) {
    //         form.value = {
    //           ...form.value,
    //           id: res.data.id,
    //           applySource: res.data.applySource,
    //           applyPosition: res.data.applyPosition,
    //           applyLng: res.data.applyLng,
    //           applyLat: res.data.applyLat,
    //           applyNickname: res.data.applyNickname,
    //           applyPhone: res.data.applyPhone,
    //           applyTime: res.data.applyTime,
    //           applyReason: res.data.applyReason,
    //         };
    //         loadMarker();
    //       }
    //     } else {
    //       message.error(res.message);
    //     }
    //   });
    // }
    // if (params['dealId']) {
    //   form.value.dealId = params['dealId']
    //   form.value.dealNote = params['dealNote']
    //   form.value.dealState = params['dealState'] == '0'? '' : params['dealState']
    //   form.value.dealTime = params['dealTime']
    //   form.value.dealUser = params['dealUser']
    // }
    if(params['regionId'] != ""){
      form.value.regionId = params['regionId']
      callOperate("/ebikeRegion/getRegionInfo/" + params['regionId'], {}, "get").then((res) => {
        if (res.code != 200) {
            message.error(res.message)
            return
        }
        form.value.regionName = res.data.regionName;
        dataRegion.value = res.data;
        loadMap();
      });	
    }
  };

  const polygonRef = ref(null);
  const circleRef = ref(null);
  const markerRef = ref(null);
  let timer = null;
  const loadMap = () => {
    if (mapRef.value && mapRef.value.map && typeof(TMap) !== 'undefined') {
      clearTimeout(timer);
      if (dataRegion.value) {
        const { regionId ,points, shapeType, radius } = dataRegion.value;
        let shapeId = 'polygon' + regionId;
        if (shapeType == 1) {
            shapeId = 'circle' + regionId;
        }
        if (points) {
          if(shapeType == 1){
              // 初始化圆形
              if (circleRef.value) {
                  circleRef.value.setMap(null); // 清除之前的圆形
              }
              circleRef.value = new TMap.MultiCircle({
                  id: 'circle-layer', // 图层id
                  geometries: [
                      {
                          id: shapeId, // 圆形图形数据的标志信息
                          styleId: 'circle', // 样式id
                          center: new TMap.LatLng(points[0].latitude, points[0].longitude), // 圆形的位置信息
                          radius: radius, // 圆形的半径
                          properties: {
                              // 圆形的属性数据
                              title: 'circle',
                          }, 
                      }  
                  ]
              });
              circleRef.value.setMap(mapRef.value.map);
              // //设置视野范围
              // const mycircle = circleRef.value.getGeometryById(shapeId);
              // const boundary = TMap.geometry.computeBoundingRectangle(mycircle.paths);
              // mapRef.value.map.fitBounds(boundary,{
              //     padding: 100, // 设置地图边界的内边距
              // });
          }
          else if(shapeType == 2){
              const paths = [];
              points.forEach((point) => {
                  paths.push(new TMap.LatLng(point.latitude, point.longitude));
              });
              // 初始化多边形
              if (polygonRef.value) {
                  polygonRef.value.setMap(null); // 清除之前的多边形
              }
              polygonRef.value = new TMap.MultiPolygon({
                id: 'polygon-layer', // 图层id
                geometries: [
                  {
                    id: shapeId, // 多边形图形数据的标志信息
                    styleId: 'polygon', // 样式id
                    paths, // 多边形的位置信息
                    properties: {
                      // 多边形的属性数据
                      title: 'polygon',
                    },
                  },
                ],
              });
              polygonRef.value.setMap(mapRef.value.map);
              // //设置视野范围
              // const mypolygon = polygonRef.value.getGeometryById(shapeId);
              // const boundary = TMap.geometry.computeBoundingRectangle(mypolygon.paths);
              // mapRef.value.map.fitBounds(boundary,{
              //   padding: 100, // 设置地图边界的内边距
              // });
          }
        }
      }
    }
    else
    {
        timer = setTimeout(() => {
          loadMap();
        }, 1000)
    }
  };

  
  let timer1 = null;
  const loadMarker = () => {
    if (mapRef.value && mapRef.value.map && typeof(TMap)!== 'undefined') {
      clearTimeout(timer1);
      if (form.value.applyLng && form.value.applyLat) {
        // 初始化点标记
        if (markerRef.value) {
          markerRef.value.setMap(null); // 清除之前的多边形
        }
        markerRef.value = new TMap.MultiMarker({
          id: 'marker-layer', // 图层id
          styles: {
            "marker": new TMap.MarkerStyle({
                "width": 25,
                "height": 35,
                "anchor": { x: 16, y: 32 },
                "src": config.imgPath + 'assets/map/point.png'
            })
          },
          geometries: [
            // 点标记数据数组
            {
              // 标记位置(纬度，经度，高度)
              position: new TMap.LatLng(form.value.applyLat, form.value.applyLng),
              id: 'marker' + form.value.id,
              styleId: 'marker',
              properties: {
                // 标记的属性数据
                title: '反馈位置', 
              }
            },
          ],
        });
        markerRef.value.setMap(mapRef.value.map);
        //设置视野范围
        var ne = new TMap.LatLng(form.value.applyLat, form.value.applyLng);//东北角坐标
        var sw = new TMap.LatLng(form.value.applyLat, form.value.applyLng);//西南角坐标
        var latLngBounds = new TMap.LatLngBounds(sw, ne);
        mapRef.value.map.fitBounds(latLngBounds,{
            padding: 50, // 设置地图边界的内边距
        });
      } 
    }
    else
    {
      timer1 = setTimeout(() => {
          loadMarker();
        }, 1000)
    } 
  }

  const formSave = (callBack) => {
    formRef.value.validate().then(() => {
      const userinfo = getCache('ebike-userinfo');
      const params = {
        id: form.value.dealId,
        dealUser: userinfo.username,
        dealTime: dataFormat(new Date(),'yyyy-MM-dd HH:mm:ss'),
        dealNote: form.value.dealNote,
        dealState: form.value.dealState,
      }
      callOrder("/ebikeUserBacksite/updateDeal", params).then(res => {
        if (res.code != 200) {
          message.error(res.message);
          if (callBack) {
            callBack(false, res);
          }
          return;
        }
        if (callBack) {
          callBack(true, res);
        }
        resetAll();
      })
    }).catch(error => {
      if (callBack) {
          callBack(false, error);
        }
    });
  };

  const resetAll = (callBack) => {
    Object.assign(form.value, formData());
    formRef.value.resetFields();
    if (callBack) {
      callBack(true, form.value);
    }
  }

  defineExpose({ openForm, formSave, resetAll });
  </script>
  