<template>
  <div class="curb-spot-city">
    <div class="show-list">
      <a-spin :spinning="spinning">
        <!-- <AuditProgress
          v-if="!showInfo"
          :year="year" 
          :batch="batch" 
          :batchOptions="batchOptions" 
          :yearOptions="yearOptions" 
          :dataList="dataList"
          @auditProgressScreenChange="auditProgressScreenChange"
          @showInfo="changeShowInfo"
          /> -->
        <MapList
          :infoScreenData="infoScreenData"
          :cityType="cityType"
          :pageNo="pageNo"
          :pageSize="pageSize"
          :total="total"
          :infoDataList="infoDataList"
          :municipalAreaOptions="municipalAreaOptions"
          :countiesAreaOptions="countiesAreaOptions"
          :streetsAreaOptions="streetsAreaOptions"
          :communitiesAreaOptions="communitiesAreaOptions"
          @infoDataListSort="infoDataListSort"
          @changeInfoPage="changeInfoPage"
          @getInfoList="getInfoList"
          @mapListScreenChange="mapListScreenChange"
          @closeShowInfo="changeShowInfo"
          @changeTask="changeTask"
          @collectChange="collectChange"
          @resetScreenData="resetScreenData"
          @changeInfoDataList="changeInfoDataList"
        />
      </a-spin>
    </div>
    <!-- <div id="showMap" class="map"></div> -->
    <MapboxMap
      :mapConfig="mapConfig"
      @handlerDrawComplete="handlerDrawComplete"
      @mapOnLoad="onMapboxLoad"
      ref="MapboxComponent"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, watch, defineAsyncComponent } from 'vue';
  import mapboxgl, { Map } from 'mapbox-gl';
  import { MapboxConfig, MapboxDefaultStyle } from '@/components/MapboxMaps/src/config';
  import AuditProgress from './AuditProgress/index.vue';
  import MapList from './MapList/index.vue';
  import {
    getLoadDroneCaseInfoCount,
    getLoadDroneCaseInfoDetail,
    getLoadParents,
  } from '@/api/tiankongdi/index.ts';
  import { batchOptions, yearOptions } from '@/views/utils/global';
  import { getChildrenTree } from '@/api/demo/system';
  import { getGeom, getConfig } from '@/api/sys/layerManagement';
  import dayjs from 'dayjs';

  const MapboxMap = defineAsyncComponent(() => import('@/components/MapboxMaps/MapComponent.vue'));
  const MapboxComponent = ref();
  const mapConfig = ref({ isShowMap: false });

  function onMapboxLoad(): void {
    getConfig({ code: 'mapsetting' }).then((res) => {
      mapConfig.value = JSON.parse(res.codeValue);
    });
  }
  const showInfo = ref(true);
  const year = ref<number>();
  const batch = ref();
  const dataList = ref<any>([]);
  const infoDataList = ref<any>([]);
  const infoScreenData = ref({
    landType: 0,
    year: '',
    batch: '',
    patchSource: '',
    mapNo: '',
    mapType: '',
    // countyId: '',
    streetId: '',
    // downtownId: '',
    // communityId: '',
    startTime: '',
    endTime: '',
    isOverdue: '',
    illegalType: '',
    measure: '',
    mapStatus: '',
    markType: '',
    sort: '',
    order: '',
    type: '', // 收藏
    mapAreaFirst: '',
    mapAreaLast: '',
    arableAreaFirst: '',
    arableAreaLast: '',
  });
  const pageNo = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const municipalAreaOptions = ref<any[]>([]);
  const countiesAreaOptions = ref([{ label: '全部', value: '' }]);
  const streetsAreaOptions = ref([{ label: '全部', value: '' }]);
  const communitiesAreaOptions = ref([{ label: '全部', value: '' }]);
  const cityType = ref();
  const spinning = ref(false);
  const auditProgressScreenChange = (value, type) => {
    switch (type) {
      case 'year':
        year.value = value;
        break;
      case 'batch':
        batch.value = value;
        break;
    }
    let params = {
      year: year.value,
    };
    spinning.value = true;
    getLoadDroneCaseInfoCount(params)
      .then((res) => {
        console.log(res);
        dataList.value = res;
      })
      .finally(() => {
        spinning.value = false;
      });
  };
  const mapListScreenChange = (value, type) => {
    switch (type) {
      case 'landType':
        infoScreenData.value.landType = value;
        pageNo.value = 1;
        getInfoList();
        break;
      case 'year':
        infoScreenData.value.year = value;
        break;
      case 'batch':
        infoScreenData.value.batch = value;
        break;
      case 'patchSource':
        infoScreenData.value.patchSource = value;
        break;
      case 'mapNo':
        infoScreenData.value.mapNo = value;
        break;
      // case 'countyId':
      //   infoScreenData.value.countyId = value
      //   break
      case 'streetId':
        infoScreenData.value.streetId = value;
        break;
      case 'time':
        if (value) {
          infoScreenData.value.startTime = dayjs(value[0]).format('YYYY-MM-DD');
          infoScreenData.value.endTime = dayjs(value[1]).format('YYYY-MM-DD');
        } else {
          infoScreenData.value.startTime = '';
          infoScreenData.value.endTime = '';
        }
        break;
      // case 'communityId':
      //   infoScreenData.value.communityId = value
      //   break
      case 'mapType':
        infoScreenData.value.mapType = value;
        if (value !== 1) {
          infoScreenData.value.illegalType = '';
          infoScreenData.value.measure = '';
        }
        break;
      case 'illegalType':
        infoScreenData.value.illegalType = value;
        if (value !== 0) {
          infoScreenData.value.measure = '';
        }
        break;
      case 'measure':
        infoScreenData.value.measure = value;
        break;
      case 'mapStatus':
        infoScreenData.value.mapStatus = value;
        break;
      case 'isOverdue':
        infoScreenData.value.isOverdue = value;
        break;
      case 'markType':
        infoScreenData.value.markType = value;
        break;
      case 'mapAreaFirst':
        infoScreenData.value.mapAreaFirst = value;
        break;
      case 'mapAreaLast':
        infoScreenData.value.mapAreaLast = value;
        break;
      case 'arableAreaFirst':
        infoScreenData.value.arableAreaFirst = value;
        break;
      case 'arableAreaLast':
        infoScreenData.value.arableAreaLast = value;
        break;
    }
  };
  const changeShowInfo = async (value, item) => {
    if (item) {
      cityType.value = item;
      let childList = await getChildrenTree({ parentId: item.areaid });
      let params = {
        childId: item.areaid,
      };
      let parents = await getLoadParents(params);
      parents.forEach((parent) => {
        switch (parent.level) {
          case 0:
            municipalAreaOptions.value.push({
              label: parent.name,
              value: parent.id,
            });
            infoScreenData.value.downtownId = parent.id;
            childList.forEach((cityItem) => {
              countiesAreaOptions.value.push({
                label: cityItem.name,
                value: cityItem.id,
              });
            });
            break;
          case 1:
            countiesAreaOptions.value.push({
              label: parent.name,
              value: parent.id,
            });
            infoScreenData.value.countyId = parent.id;
            childList.forEach((cityItem) => {
              streetsAreaOptions.value.push({
                label: cityItem.name,
                value: cityItem.id,
              });
            });
            break;
          case 2:
            streetsAreaOptions.value.push({
              label: parent.name,
              value: parent.id,
            });
            infoScreenData.value.streetId = parent.id;
            childList.forEach((cityItem) => {
              communitiesAreaOptions.value.push({
                label: cityItem.name,
                value: cityItem.id,
              });
            });
            break;
          case 3:
            communitiesAreaOptions.value.push({
              label: parent.name,
              value: parent.id,
            });
            infoScreenData.value.communityId = parent.id;
            break;
        }
      });
      await getInfoList();
      showInfo.value = value;
    } else {
      cityType.value = null;
      showInfo.value = value;
    }
    console.log(item);
  };
  const getParams = () => {
    let result = {};
    let params = {
      landType: infoScreenData.value.landType, //0 农用地 1建设用地
      isOutTime: infoScreenData.value.isOverdue, //是否超期
      year: infoScreenData.value.year, //年
      tubanlaiyuan: infoScreenData.value.patchSource, //图斑来源
      picihao: infoScreenData.value.batch, //批次号
      // countyid: infoScreenData.value.countyId,
      streetid: infoScreenData.value.streetId,
      // communityId: infoScreenData.value.communityId,
      caseNo: infoScreenData.value.mapNo, //图版编号
      startTime: infoScreenData.value.startTime, // 下发开始时间
      endTime: infoScreenData.value.endTime, // 下发结束时间
      // is_illegal: infoScreenData.value.mapType,
      // weifaleixing: infoScreenData.value.illegalType,
      // measure_name: infoScreenData.value.measure,
      nowStatus: infoScreenData.value.mapStatus, // 当前状态
      isBuildName: infoScreenData.value.markType, // 标注
      tubanArea1: infoScreenData.value.mapAreaFirst, // 图斑面积1
      tubanArea2: infoScreenData.value.mapAreaLast, // 图斑面积2
      gengdiArea1: infoScreenData.value.arableAreaFirst, //耕地面积1
      gengdiArea2: infoScreenData.value.arableAreaLast, //耕地面积2
      // areaid: cityType.value.areaid,
      // level: cityType.value.level,
      page: pageNo.value,
      limit: pageSize.value,
      sortType: infoScreenData.value.sort,
      order: infoScreenData.value.order,
      type: infoScreenData.value.type,
    };
    Object.keys(params).forEach((key) => {
      if (params[key] !== '' && params[key] !== null) {
        if (key === 'nowStatus') {
          result[key] = params[key].join(',');
        } else if (key === 'isOutTime') {
          if (params[key].length == 1) {
            result[key] = params[key][0];
          }
        } else {
          result[key] = params[key];
        }
      }
    });
    return result;
  };
  watch(
    () => year.value,
    (newVal) => {
      infoScreenData.value.year = newVal;
    },
  );
  watch(
    () => batch.value,
    (newVal) => {
      infoScreenData.value.batch = newVal;
    },
  );
  let map: Map;
  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;
    // map = initMap();
    getLoadDroneCaseInfoCount()
      .then((res) => {
        dataList.value = res;
      })
      .catch((err) => {
        console.log(err);
      });
  });
  onUnmounted(() => {
    map && map.remove();
  });
  const initMap = () => {
    return new mapboxgl.Map({
      container: 'showMap',
      language: 'zh-cmn',
      projection: 'equirectangular', // wgs84参考系
      style: MapboxDefaultStyle,
      maxZoom: 22,
      minZoom: 6,
      zoom: 10,
      // ...props.mapOptions,
      center: [117.984425, 35.270654],
    });
  };
  const getInfoList = () => {
    spinning.value = true;
    return getLoadDroneCaseInfoDetail(getParams())
      .then((res) => {
        total.value = res.total;
        infoDataList.value = res.items;
      })
      .finally(() => {
        spinning.value = false;
      });
  };
  const changeInfoPage = async (page, limit) => {
    pageNo.value = page;
    pageSize.value = limit;
    await getInfoList();
  };
  const changeInfoDataList = (list, totalNumber, page) => {
    infoDataList.value = list;
    total.value = totalNumber;
    pageNo.value = page;
  };
  const collectChange = (value) => {
    pageNo.value = 1;
    infoScreenData.value.type = value;
    getInfoList();
  };

  function changeTask(val) {
    let getGeomPrams = {
      TableName: 'drone_shp_data ',
      FieldName: 'gid',
      FieldValue: val?.split(','),
      page: 1,
      limit: 999,
      key: null,
    };
    if (val) {
      getGeom(getGeomPrams).then((res) => {
        let geoms = [];
        if (res) {
          if (res.items?.length > 0) {
            res.items.forEach((item, index) => {
              let geom = {
                key: item.gid,
                mapgeom: item.geometry,
              };
              geoms.push(geom);
            });
          }
          // MapboxComponent.value.handlerDraw(status,mapgemoList.value, false);
          MapboxComponent.value.handlerDraw('Details', geoms, false);
        } else {
          createMessage.error('当前数据没有图斑！');
        }
      });
    } else {
      createMessage.error('当前数据没有图斑！');
    }
  }
  const infoDataListSort = (type, order) => {
    switch (order) {
      case 0:
        infoScreenData.value.sort = '';
        infoScreenData.value.order = '';
        break;
      case 1:
        infoScreenData.value.sort = type;
        infoScreenData.value.order = 'asc';
        break;
      case 2:
        infoScreenData.value.sort = type;
        infoScreenData.value.order = 'desc';
        break;
    }
    spinning.value = true;
    getLoadDroneCaseInfoDetail(getParams())
      .then((res) => {
        total.value = res.total;
        infoDataList.value = res.items;
        // pageNo.value = 1
      })
      .finally(() => {
        spinning.value = false;
      });
  };
  const resetScreenData = () => {
    infoScreenData.value.mapNo = '';
    infoScreenData.value.streetId = '';
    infoScreenData.value.mapType = '';
    infoScreenData.value.illegalType = '';
    infoScreenData.value.measure = '';
    infoScreenData.value.mapStatus = '';
    infoScreenData.value.markType = '';
    getInfoList();
  };
  onMounted(() => {
    getInfoList();
  });
</script>

<style lang="scss" scoped>
  .curb-spot-city {
    height: 100%;
    display: flex;
    .show-list {
      width: 590px;
      background: #efefef;
      :deep(.ant-spin-nested-loading) {
        height: 100%;
      }
      :deep(.ant-spin-container) {
        height: 100%;
      }
    }
    .map {
      width: 65%;
      background: burlywood;
    }
  }
</style>
