<template>
<a-spin size="large" tip="图层加载中..." :spinning="spinning" wrapperClassName="solid-spin">
  <div class="statistical" id="bg-pan" ref="container">
    <Map
      @onload="handlerOnMapLoad"
      @handlerGetDetails="handlerGetDetails"
      @getDetailByFeature="getDetailByFeature"
      style="
        position: absolute;
        top: 0px;
        left: 0px;
        height: calc(100vh - 80px);
        width: 100%;
        z-index: 0;
      "
      ref="MapboxComponent"
      @showMonitor="showMonitor"
      @handlerQueryIntersectTif="handlerQueryIntersectTif"
      :layer="layerSettings"
      :defaultColor="defaultColor"
      @changeLoading="changeLoading"
    />

    <div style="position: absolute; left: 60px; bottom: 20px; z-index: 1" v-if="false">
      <div
        :class="`button-item ${buttonSelect == 1 ? 'button-select' : ''}`"
        style="margin-bottom: 10px"
        @click="changeLayer(1)"
        >导航地图</div
      >
      <div
        :class="`button-item ${buttonSelect == 2 ? 'button-select' : ''}`"
        style="margin-bottom: 10px"
        @click="changeLayer(2)"
        >卫星地图</div
      >
      <div
        :class="`button-item ${buttonSelect == 3 ? 'button-select' : ''}`"
        @click="changeLayer(3)"
        >白板地图</div
      >
    </div>

    <div class="legend" v-if="false">
      <div v-if="subject == '非法采矿'" class="button-item router-button" style="position: absolute;top: -50px;width: 200px;left: 0px;background-size: 100% 100%;height: 37px;
    font-size: 16px;cursor: pointer" @click="goRouter">汇总表</div>
      <div :class="`legend-item ${subject == '耕地非粮化'? 'flh-item': ''}`" v-for="(item, index) in legends" :key="index">
        <div class="legend-dot" :style="{ background: item.color }"></div>
        <div class="legend-label">{{ item.label }}</div>
      </div>
    </div>

    <a-modal
      class="dragModal"
      :width="`${hiddenInfoMap? '55%': '100%'}`"
      wrap-class-name="full-modal"
      v-model:open="showInfoOpen"
      :footer="null"
      :maskClosable="false"
      :destroyOnClose="true"
      @cancel="closeModal"
      ref="modalRef"
      :mask="false"
      :getContainer="getContainer"
    >
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move; user-select: none;padding: 16px;display: flex;align-items: center;">
          详情
           <div :class="`hidden-show-icon ${hiddenInfoMap? 'show-icon': 'hidden-icon'}`" @click="showOrHiddenInfoMap"></div>
        </div>
      </template>
      <template template #modalRender="{ originVNode }">
        <div :style="transformStyle">
          <component :is="originVNode" />
        </div>
      </template>
      <div class="modal-content">
        <template v-if="showInfoOpen">
          <SsnyInfoModal :showInfoData="showInfoData" :hiddenInfoMap="hiddenInfoMap"/>

          <!-- <ShowInfoModal :showInfoData="showInfoData" v-if="subject == '违法用地'" :hiddenInfoMap="hiddenInfoMap"/>
          <MainShowInfoModal :id="showMainInfoId" v-if="subject == '非法采矿'" :hiddenInfoMap="hiddenInfoMap"/>
          <DegrainingShowInfoModal :showInfoData="showInfoData" v-if="subject == '耕地非粮化'" :hiddenInfoMap="hiddenInfoMap"/>
          <KeyShowInfoModal :showInfoData="showInfoData" v-if="subject == '重点问题'" :hiddenInfoMap="hiddenInfoMap"/>
          <InspectionAuditShowInfoModal :showInfoData="showInfoData" v-if="subject == '巡察审计'" :hiddenInfoMap="hiddenInfoMap"/>
          <RedLineShowInfoModal :showInfoData="showInfoData" v-if="subject == '生态保护红线监管'" :hiddenInfoMap="hiddenInfoMap"/>
          <RepairShowInfoModal :showInfoData="showInfoData" v-if="subject == '生态修复'" :hiddenInfoMap="hiddenInfoMap"/> -->
        </template>
      </div>
    </a-modal>

    <!-- 图层控制 视频监控-->
    <div class="layer-center-container" 
        :style="style"
     >
      <div class="drag-area" 
        @mousedown="startDrag"
      ></div>
      <LayerCenter
        v-if="layerCenterShow"
        @drawPolygon="drawPolygon"
        @cancleDrawPolygon="cancleDrawPolygon"
        @changeTifLayer="changeTifLayer"
        :layerInfo="layerInfo"
        ref="LayerCenterComponent"
      ></LayerCenter>
    </div>

    <div class="TC-videoi-container" v-if="showTCLPlayer" v-drag>
      <div class="close-button" @click="showTCLPlayer = false">
        <CloseOutlined></CloseOutlined>
      </div>
      <Monitor v-if="showTCLPlayer" :play-url="playUrl"></Monitor>
    </div>

    <div
      class="attribute"
      :style="{
        height: isMinusAttributeWindow ? '540px' : '30px',
      }"
      v-if="showAttributeWindow"
    >
      <span class="span-title">详细信息</span>
      <a-tooltip placement="top">
        <template #title>
          <span>按下空格快速切换</span>
        </template>
        <a-button class="span-button-minus" type="link" @click="minusAttributeWindow">
          <MinusOutlined v-if="isMinusAttributeWindow" style="color: black" />
          <ExpandAltOutlined
            v-if="!isMinusAttributeWindow"
            :style="{ fontSize: '17px', color: 'black' }"
          />
        </a-button>
      </a-tooltip>
      <a-button class="span-button-close" type="link" @click="closeAttributeWindow">
        <CloseOutlined style="color: black" />
      </a-button>
      <AttributeWindow
        v-if="isMinusAttributeWindow"
        :showAttributeFeature="showAttributeFeature"
        :initNameList="initNameList"
      />
    </div>
  </div>
</a-spin>
</template>

<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, computed, watch, watchEffect } from 'vue';
  import Icon from '@/components/Icon/Icon.vue';
  import useDrag from './drag';

  const { style, startDrag } = useDrag();

  import { useDraggable } from '@vueuse/core';
  import Map from './Converge/index.vue';
  import layerButton from './mapComponent/left_layerButton.vue';
  import statisticalType from './mapComponent/left_statisticalType.vue';
  import county from './mapComponent/left_county.vue';
  import DataScreen from './dataScreen/index.vue';
  import Header from './mapComponent/top_title.vue';
  import {
    SsnyInfoModal,
    ShowInfoModal,
    MainShowInfoModal,
    DegrainingShowInfoModal,
    KeyShowInfoModal,
    InspectionAuditShowInfoModal,
    RedLineShowInfoModal,
    RepairShowInfoModal,
  } from './page';

  import { getLoadDroneCaseInfoDetail, getCaseInfoById,getDroneSsnyById } from '@/api/tiankongdi/index';
  import { useRoute } from 'vue-router';
  import { getConfig } from '@/api/sys/layerManagement';
  import { GetCaseInfoById } from '@/api/degraining/index';
  import { getInspectionAuditCaseInfoById } from '@/api/inspectionaudit/index';
  import { getRedLineCaseInfoById } from '@/api/redlinesupervision/index';
  import { getRepairCaseInfoById } from '@/api/shengtaixiufu/index';
  import { getCaseInfoByIdtotal } from '@/api/keyproblem/keyissuesI/index';
  import { getDataTableRecord } from '@/api/demo/system';
  import AttributeWindow from '@/views/demo/system/achievement/Display/AttributeWindow.vue';

  const route: any = useRoute();
  const subject = ref(route.params.id);
  const legends: any = ref([]);
  const layerSettings = ref();
  const initNameList: any = ref([]);
  // details
  const showInfoOpen = ref<Boolean>(false);
  const showInfoData = ref();
  const buttonSelect = ref(2);
  const showMainInfoId = ref();

  const modalTitleRef = ref(null);
  const { x, y, isDragging } = useDraggable(modalTitleRef);
  const startX = ref<number>(0);
  const startY = ref<number>(0);
  const startedDrag = ref(false);
  const transformX = ref(0);
  const transformY = ref(0);
  const preTransformX = ref(0);
  const preTransformY = ref(0);
  const hiddenInfoMap = ref(false)
  const spinning = ref(false)

  watch([x, y], () => {
  if (!startedDrag.value) {
    startX.value = x.value;
    startY.value = y.value;
    preTransformX.value = transformX.value;
    preTransformY.value = transformY.value;
  }
  startedDrag.value = true;

  const layerContainer = ref(null);
  const { layerContainerPositon } = useDraggable(layerContainer);
});

watch(isDragging, () => {
  if (!isDragging) {
    startedDrag.value = false;
  }
});

watchEffect(() => {
  if (startedDrag.value) {
    transformX.value = preTransformX.value + x.value - startX.value;
    transformY.value = preTransformY.value + y.value - startY.value;
  }
});

  const getInfoList = (id) => {
    
    console.log(subject.value);
    if (subject.value == '违法用地') {
      getCaseInfoById({ id: id }).then((res) => {
        if (res) {
          showInfoData.value = res;
          showInfoOpen.value = true;
        }
      });
    } else if (subject.value == '非法采矿') {
      showMainInfoId.value = id;
      showInfoOpen.value = true;
    } else if (subject.value == '耕地非粮化') {
      GetCaseInfoById({ id: id }).then((res) => {
        showInfoData.value = res;
        showInfoOpen.value = true;
      });
    } else if (subject.value == '重点问题') {
      getCaseInfoByIdtotal({ id: id }).then((res) => {
        showInfoData.value = res;
        showInfoOpen.value = true;
      });
    } else if (subject.value == '巡察审计') {
      getInspectionAuditCaseInfoById({ id: id }).then((res) => {
        showInfoData.value = res;
        showInfoOpen.value = true;
      });
    } else if (subject.value == '生态保护红线监管') {
      getRedLineCaseInfoById({ id: id }).then((res) => {
        showInfoData.value = res;
        showInfoOpen.value = true;
      });
    } else if (subject.value == '生态修复') {
      getRepairCaseInfoById({ id: id }).then((res) => {
        showInfoData.value = res;
        showInfoOpen.value = true;
      });
    } else {
      getDroneSsnyById({ id: id }).then((res) => {
        if (res) {
          console.log(res);
          showInfoData.value = res;
          showInfoOpen.value = true;
        }
      });
    }
  };

  const MapboxComponent = ref();
  const countyId = ref();
  const defaultColor = ref('#FFFFFF');
  const layerCenterShow = ref(true);
  function getLayerSettings() {
    let title = '';
    switch (subject.value) {
      case '违法用地':
        title = 'Subject_WFYD';
        defaultColor.value = '#F70303';
        break;
      case '非法采矿':
        title = 'Subject_FFCK';
        // legends.value.push({
        //   label: '默认',
        //   color: '#F4E004',
        // });
        defaultColor.value = '#F4E004';
        break;
      case '耕地非粮化':
        title = 'Subject_GDFLH';
        legends.value.push({
          label: '默认',
          color: '#FFFFFF',
        });
        defaultColor.value = '#FFFFFF';
        break;
      case '重点问题':
        title = 'Subject_ZDWT';
        // legends.value.push({
        //   label: '默认',
        //   color: '#FFFFFF',
        // });
        break;
      case '巡察审计':
        title = 'Subject_XCSJ';
        defaultColor.value = '#F70303';
        break;
      case '生态保护红线监管':
        title = 'Subject_STBHHXJG';
        // legends.value.push({
        //   label: '默认',
        //   color: '#FFFFFF',
        // });
        break;
      case '生态修复':
        title = 'Subject_STXF';
        // legends.value.push({
        //   label: '默认',
        //   color: '#F70303',
        // });
        defaultColor.value = '#F70303';
        break;
    }
    getConfig({
      // code: title,
      code:"Subject_WFYD",
    }).then((res) => {
      let obj = JSON.parse(res.codeValue);
      layerSettings.value = obj[0];
      layerInfo.value = layerSettings.value.layerinfo;
      layerCenterShow.value = true;
      let legend = layerSettings.value.legend[0];
      for (const key in legend) {
        legends.value.push({
          label: key,
          color: legend[key].colour,
        });
      }
    });
  }
  function handlerOnMapLoad() {}

  function handlerGetDetails(e) {
    getInfoList(e.Id);
  }

  // 选择区县
  const currentCounty = ref({ name: '', code: '' });
  function countyClick(data) {
    countyId.value = data.id;
    currentCounty.value = { name: data['name'], code: data['id'] };
    MapboxComponent.value.handlerChangeCounty(currentCounty.value);
  }

  // 图例点击
  function handlerChangePolygonType(data) {
    MapboxComponent.value.handlerLoadPolygon(currentCounty.value['code'], data);
  }

  // 切换图斑类型
  function changeLandType(type): void {
    MapboxComponent.value.handlerLoadPolygon(currentCounty.value['code'], '', type);
  }
  const changeLayer = (value) => {
    buttonSelect.value = value;
    switch (value) {
      case 1:
        MapboxComponent.value.handlerChangeLayerVisible('tdt-img-tiles', false);
        MapboxComponent.value.handlerChangeLayerVisible('tdt-vec-tiles', true);
        MapboxComponent.value.handlerChangeLayerVisible('countyPanelLayer', false);
        break;
      case 2:
        MapboxComponent.value.handlerChangeLayerVisible('tdt-img-tiles', true);
        MapboxComponent.value.handlerChangeLayerVisible('tdt-vec-tiles', false);
        MapboxComponent.value.handlerChangeLayerVisible('countyPanelLayer', false);
        break;
      case 3:
        MapboxComponent.value.handlerChangeLayerVisible('tdt-img-tiles', false);
        MapboxComponent.value.handlerChangeLayerVisible('tdt-vec-tiles', false);
        MapboxComponent.value.handlerChangeLayerVisible('countyPanelLayer', true);
        break;
    }
  };

  /*图层控制 视频监控*/
  import LayerCenter from './mapComponent/layers/index.vue';

  // 视频监控
  import Monitor from './mapComponent/monitor/index.vue';
  import { CloseOutlined, MinusOutlined, ExpandAltOutlined } from '@ant-design/icons-vue';
  import { is } from '@/utils/is';

  const showTCLPlayer = ref(false);
  const playUrl = ref('');
  function showMonitor(info) {
    playUrl.value = info.playUrl;
    showTCLPlayer.value = true;
  }

  // 历史影像

  function drawPolygon(state) {
    // 调用Map控件中的绘图方法
    MapboxComponent.value.handlerDrawPolygon();
  }

  function cancleDrawPolygon() {
    MapboxComponent.value.handlerDeletePolygon();
  }

  const LayerCenterComponent = ref();
  const layerInfo = ref([]);
  function handlerQueryIntersectTif(wktStr) {
    LayerCenterComponent.value.handlerQueryIntersectTif(wktStr);
  }

  function changeTifLayer(layer) {
    console.log('layer', layer);

    MapboxComponent.value.handlerChangeTifLayer(layer);
  }


  onMounted(() => {
    spinning.value = true
    getLayerSettings();
  });
  const changeLoading = (type: boolean) => {
    spinning.value = type
  }
  const goRouter = () => {
    route.push({ path: '/caseoffence/feifacaikuang' })
  }
  // 点击矢量图层展示点击块的属性------------------------------------------------------------
  const showAttributeWindow = ref(false);
  const isMinusAttributeWindow = ref(true);
  const showAttributeFeature: any = ref();

  const getDetailByFeature = (feature) => {
    getDataTableRecord({
      id: feature.properties.id,
      dataTable: feature.source,
    }).then((res) => {
      showAttributeFeature.value = res;
      showAttributeWindow.value = true;
      if (!showAttributeWindow.value) {
        isMinusAttributeWindow.value = true;
      }
    });
  };
  const minusAttributeWindow = () => {
    isMinusAttributeWindow.value = !isMinusAttributeWindow.value;
  };
  const closeAttributeWindow = () => {
    showAttributeWindow.value = false;
    isMinusAttributeWindow.value = true;
  };
  const transformStyle = computed(() => {
    return {
      transform: `translate(${transformX.value}px, ${transformY.value}px)`,
    };
  });
  const closeModal = () => {
    showInfoOpen.value = false
    transformX.value = 0
    transformY.value = 0
  }
  const getContainer = () => {
    return document.getElementById('bg-pan')
  }
  const showOrHiddenInfoMap = () => {
    hiddenInfoMap.value = !hiddenInfoMap.value
    if(hiddenInfoMap.value){
      transformX.value = window.innerWidth * 0.45
      transformY.value = 0
    }else{
      transformX.value = 0
      transformY.value = 0
    }
  }
</script>

<style lang="less" scoped>
  .statistical{

    :deep(.ant-modal-header){
      padding: 0px;
    }
    :deep(.ant-modal-wrap){
      overflow: hidden;
      pointer-events:none;
    }
    :deep(.dragModal){
      margin: 0 !important;
      .hidden-show-icon{
        width: 28px;
        height: 28px;
        background-size: 100% 100%;
        margin-left: 20px;
        cursor: pointer;
      }
      .hidden-icon{
        background-image: url('/public/iocn/map_hidden.png');
      }
      .show-icon{
        background-image: url('/public/iocn/map_show.png');
      }
    }
  }
  .button-item {
    width: 96px;
    height: 32px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 11px;
    color: #7ebbff;
    background: url('@/assets/statistical/blue_bg.png') no-repeat;
    background-size: cover;
  }
  .button-select {
    color: #06ebb7;
    background: url('@/assets/statistical/green_bg.png') no-repeat;
    background-size: cover;
  }
  .statistical {
    // position: relative;
    // 页面不能被选中
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE/Edge */
    user-select: none;
    width:100%;
    height:calc(-80px + 100vh);
    position:relative;
  }

  #bg-pan {

  }
  #alertOverlay::before,
  #alertOverlay::after {
    content: '';
    position: absolute;
    width: 50px;
    height: 100%;
  }

  #alertOverlay div::before,
  #alertOverlay div::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 50px;
  }

  #alertOverlay::before {
    background: linear-gradient(to right, rgba(0, 0, 0, 0.8), transparent);
    top: 0;
    left: 0;
    transform: rotate(0deg);
  }

  #alertOverlay::after {
    background: linear-gradient(to left, rgba(0, 0, 0, 0.8), transparent);
    top: 0%;
    left: 100%;
    transform: rotate(0deg) translate(calc(-1 * 50px), 0px);
  }

  #alertOverlay div::before {
    background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
    top: 0;
    left: 0;
    transform: rotate(180deg);
  }

  #alertOverlay div::after {
    background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
    top: 100%;
    left: 0;
    transform: rotate(0deg) translate(0px, calc(-1 * 50px));
  }

  #alertOverlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    opacity: 1;
    transition: opacity 0.5s;
    pointer-events: none;
    z-index: 1;
  }

  .alert-active {
    animation: blink 0s infinite;
  }

  @keyframes blink {
    0% {
      opacity: 0;
    }
    50% {
      opacity: 0.5;
    }
    100% {
      opacity: 0;
    }
  }

  .legend {
    width: 220px;
    padding: 10px;
    position: absolute;
    bottom: 20px;
    right: 20px;
    display: flex;
    flex-wrap: wrap;
    column-gap: 30px;
    border-radius: 8px;
    background-image: url('/statistical/left_statistical.png');
    background-size: 100% 100%;
    .legend-item {
      width: 82px;
      padding: 5px 0px;
      font-size: 14px;
      color: #666666;
      display: flex;
      flex: 48% 48%;
      color: #7ebbff;
      .legend-dot {
        width: 14px;
        height: 14px;
      }
      .legend-label {
        margin-left: 12px;
      }
    }
    .flh-item{
      width: 120px;
    }
  }

  /**图层控制 视频监控**/
  .layer-center-container {
    width:285px;
    position: absolute;
  }
  .drag-area{
    width:245px;
    height:40px;
    position:absolute;
    top:0px;
    left:0px;
    z-index:99999;
    cursor:move;
  }
  .TC-videoi-container {
    position: absolute;
    bottom: 48px;
    right: 38px;
    width: 418px;
    height: 300px;
    .close-button {
      width: 28px;
      height: 28px;
      background: rgba(0, 0, 0, 0.6);
      text-align: center;
      line-height: 28px;
      position: absolute;
      top: 4px;
      right: 4px;
      z-index: 999999;
      color: #fff;
      cursor: pointer;
    }
  }

  .selection-button {
    position: absolute;
    cursor: pointer;
    top: 20px;
    left: 220px;
    width: 140px;
    height: 40px;
    margin-left: 20px;
    background-image: url(/map/change-view-btn.png);
    background-size: 100% 100%;
    color: #efefef;
    text-align: center;
    line-height: 46px;
    font-size: 14px;
  }
</style>
<style>
.solid-spin.ant-spin-nested-loading > .ant-spin-blur::after {
  opacity: 1;
}
.solid-spin.ant-spin-nested-loading  .ant-spin{
  max-height: none;
}
</style>
