<template>
  <div class="detail-container">
    <div class="map-container" v-if="!props.hiddenInfoMap">
      <MapboxMap
        :caseno="props.showInfoData.case_no"
        :countyname="props.showInfoData.countyname"
        :imageList="imageList"
        :geomsList="geomsList"
        :mapConfig="mapConfig"
        @handlerDrawComplete="handlerDrawComplete"
        @mapOnLoad="onMapboxLoad"
        ref="MapboxComponent"
      />
    </div>
    <div class="info-container" id="info-container">
      <a-divider>基本信息</a-divider>
      <a-descriptions
        :column="2"
        bordered
        :contentStyle="{
          'text-align': 'center',
          'min-width': '250px',
          'word-break': 'break-all',
        }"
      >
        <a-descriptions-item label="线索编号">{{
          props.showInfoData.case_no
        }}</a-descriptions-item>
        <a-descriptions-item label="项目名称">{{
          props.showInfoData.case_name
        }}</a-descriptions-item>
        <a-descriptions-item label="县区">{{
          props.showInfoData.countyname
        }}</a-descriptions-item>
        <a-descriptions-item label="乡镇">{{
          props.showInfoData.streetname
        }}</a-descriptions-item>
        <a-descriptions-item label="社区/村">{{
          props.showInfoData.communityname
        }}</a-descriptions-item>
        <a-descriptions-item label="图斑面积(亩)">{{
          dataProcessing(props.showInfoData.area)
        }}</a-descriptions-item>
        <a-descriptions-item label="耕地面积(亩)">{{
          dataProcessing(props.showInfoData.gengdi_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="永农面积(亩)">{{
          dataProcessing(props.showInfoData.yongjiujibennongtian_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="线索照片">
          <div class="image-div">
            <a-image-preview-group
              :preview="{
                getContainer: getContainer,
                onVisibleChange: handlerImageChange,
              }"
            >
              <template v-for="(imageItem, imageIndex) in casepicList" :key="imageIndex">
                <a-image
                  v-if="imageItem"
                  width="100px"
                  height="100px"
                  @click="handlerPreviewImage(imageIndex, imageItem)"
                  :src="`${VITE_GLOB_INFO_IMAGE_URL}/${imageItem}`"
                  :preview="{
                    getContainer,
                  }"
                ></a-image>
              </template>
            </a-image-preview-group>
          </div>
        </a-descriptions-item>
      </a-descriptions>
      <a-divider>核实信息</a-divider>
      <a-descriptions
        :column="2"
        bordered
        :contentStyle="{
          'text-align': 'center',
          'min-width': '250px',
          'word-break': 'break-all',
        }"
      >
        <a-descriptions-item label="2022建设用地面积(亩)">{{
          dataProcessing(props.showInfoData.jsyd_area_2022)
        }}</a-descriptions-item>
        <a-descriptions-item label="2022农用地面积(亩)">{{
          dataProcessing(props.showInfoData.nyd_area_2022)
        }}</a-descriptions-item>
        <a-descriptions-item label="2022耕地面积(亩)">{{
          dataProcessing(props.showInfoData.gd_area_2022)
        }}</a-descriptions-item>
        <a-descriptions-item label="套合永农面积(亩)">{{
          dataProcessing(props.showInfoData.taoheyn_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="三调建设用地面积(亩)">{{
          dataProcessing(props.showInfoData.sandiaojsyd_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="三调农用地面积(亩)">{{
          dataProcessing(props.showInfoData.sandiaonyd_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="三调耕地面积(亩)">{{
          dataProcessing(props.showInfoData.sandiaogd_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="是否占用生态红线">{{
          yesOrNoOptions(props.showInfoData.is_zhanyongsthx)
        }}</a-descriptions-item>
        <a-descriptions-item label="占用生态红线面积(亩)">{{
          dataProcessing(props.showInfoData.is_zhanyongsthx_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="占用生态红线类型">{{
          props.showInfoData.is_zhanyongsthx_lx
        }}</a-descriptions-item>
        <a-descriptions-item label="是否办理占用手续">{{
          yesOrNoOptions(props.showInfoData.is_zhanyongsthx_shouxu)
        }}</a-descriptions-item>
        <a-descriptions-item label="是否占用重点区域">{{
          yesOrNoOptions(props.showInfoData.is_zhanyongzdqy)
        }}</a-descriptions-item>
        <a-descriptions-item label="占重点区域面积(亩)">{{
          dataProcessing(props.showInfoData.is_zhanyongzdqy_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="用途分类">{{
          getYongtufenleiSpan(props.showInfoData.yongtufenlei)
        }}</a-descriptions-item>
        <a-descriptions-item label="产业类-分类">{{
          props.showInfoData.yongtufenlei_chy
        }}</a-descriptions-item>
        <a-descriptions-item label="公共管理服务类-分类">{{
          props.showInfoData.yongtufenlei_ggglfw
        }}</a-descriptions-item>
        <a-descriptions-item label="具体用途">{{
          props.showInfoData.yongtufenlei_jtyt
        }}</a-descriptions-item>
      </a-descriptions>
      <a-divider>处置情况</a-divider>
      <a-descriptions
        :column="2"
        bordered
        :contentStyle="{
          'text-align': 'center',
          'min-width': '250px',
          'word-break': 'break-all',
        }"
      >
        <a-descriptions-item label="是否处罚完成">{{
          yesOrNoOptions(props.showInfoData.is_chufa)
        }}</a-descriptions-item>
        <a-descriptions-item label="已处罚面积(亩)">{{
          dataProcessing(props.showInfoData.is_chufa_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="处置措施">{{
          props.showInfoData.is_chuzhicuosi
        }}</a-descriptions-item>
        <a-descriptions-item label="是否处置完成">{{
          yesOrNoOptions(props.showInfoData.is_chuzhiwancheng)
        }}</a-descriptions-item>
        <!-- ======= -->
        <a-descriptions-item label="是否位于城镇开发边界内">{{
          yesOrNoOptions(props.showInfoData.is_chzkfbj)
        }}</a-descriptions-item>
        <a-descriptions-item label="位于城镇开发边界内面积(亩)">{{
          dataProcessing(props.showInfoData.is_chzkfbj_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="是否符合规划">{{
          yesOrNoOptions(props.showInfoData.is_fuheguihua)
        }}</a-descriptions-item>
        <a-descriptions-item label="符合规划面积(亩)">{{
          dataProcessing(props.showInfoData.is_fuheguihua_area)
        }}</a-descriptions-item>
        <a-descriptions-item label="规划类型">{{
          props.showInfoData.is_fuheguihua_lx
        }}</a-descriptions-item>
        <a-descriptions-item label="土地征收项目是否纳入成片开发方案">{{
          yesOrNoOptions(props.showInfoData.is_tdzsxmnrcpkffa)
        }}</a-descriptions-item>
        <a-descriptions-item label="是否符合城镇开发边界外产业布局类型">{{
          yesOrNoOptions(props.showInfoData.is_chzkfbjwcybjlx)
        }}</a-descriptions-item>
        <a-descriptions-item label="具体产业类型">{{
          props.showInfoData.is_chzkfbjwcybjlx_shi
        }}</a-descriptions-item>
        <a-descriptions-item label="是否属于公益性项目">{{
          yesOrNoOptions(props.showInfoData.is_gongyixingxm)
        }}</a-descriptions-item>
        <a-descriptions-item label="是否属于乡村振兴项目">{{
          yesOrNoOptions(props.showInfoData.is_xiangcunzhxxm)
        }}</a-descriptions-item>
        <a-descriptions-item label="项目是否符合产业政策、供地政策合节约集约用地标准要求">{{
          yesOrNoOptions(props.showInfoData.is_yongdibiaozhunyq)
        }}</a-descriptions-item>
        <a-descriptions-item label="存在问题">{{
          props.showInfoData.is_yongdibiaozhunyq_wt
        }}</a-descriptions-item>
        <a-descriptions-item label="其他需要说明的情况">{{
          props.showInfoData.qitashuoming
        }}</a-descriptions-item>
        <a-descriptions-item label="现场照片">
          <div class="image-div">
            <a-image-preview-group
              :preview="{
                getContainer: getContainer,
                onVisibleChange: handlerImageChange,
              }"
            >
              <template v-for="(imageItem, imageIndex) in anjianzhaopianList" :key="imageIndex">
                <a-image
                  v-if="imageItem"
                  width="100px"
                  height="100px"
                  @click="handlerPreviewImage(imageIndex, imageItem)"
                  :src="`${VITE_GLOB_INFO_IMAGE_URL}/${imageItem}`"
                  :preview="{
                    getContainer,
                  }"
                ></a-image>
              </template>
            </a-image-preview-group>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="附件">
          <a-image-preview-group :preview="{ getContainer }">
            <template v-for="(item, itemIndex) in fujianList" :key="itemIndex">
              <a-image
                v-if="showImage(item)"
                style="width: 100px; height: 100px"
                :src="`${VITE_GLOB_INFO_IMAGE_URL}/${item}`"
                :preview="{ getContainer }"
              ></a-image>
              <div v-else>
                <Icon
                  v-if="item"
                  :style="`font-size: 30px; cursor: pointer;`"
                  icon="ion:document-attach-outline"
                  @click="hanlderPreViewFile(item)"
                />
                {{ handlerDealFileName(item) }}
              </div>
            </template>
          </a-image-preview-group>
        </a-descriptions-item>
      </a-descriptions>
    </div>
    <!-- File Preview && Download Start -->
    <a-modal
      v-model:open="previewFileModalVisible"
      style="width: 100vw"
      title="文件预览"
      wrap-class-name="full-modal"
    >
      <FilePreview v-if="previewFileModalVisible" :fileUrl="previewFileUrl"></FilePreview>
      <template #footer>
        <a-button key="cancel" @click="handleCancelPreviewFile">取消</a-button>
        <a-button key="confirm" type="primary" @click="handlerDownloadFle">下载</a-button>
      </template>
    </a-modal>
    <!--File Preview && Download End -->
  </div>
</template>

<script setup lang="ts">
  import { defineProps, ref, computed, onBeforeMount, watch } from 'vue';
  import MapboxMap from '@/components/MapboxMaps/MapComponent.vue';
  import { getConfig } from '@/api/sys/layerManagement';
  import { getGeom } from '@/api/sys/layerManagement';
  import { getLoadCaseImgList } from '@/api/farmland';
  import { useMessage } from '@/hooks/web/useMessage';
  import axios from 'axios';
  import Icon from '@/components/Icon/Icon.vue';
  import { getAppEnvConfig } from '@/utils/env';
  import {
    mapTypeOptions,
    measureOptions,
    illegalTypeList,
    resultOptions,
    qitaUseTOOptions,
  } from '@/utils/global';
  import { getYongtufenleiSpan, yesOrNoOptions } from '@/components/farmland/util'

  const { createMessage } = useMessage();
  const { VITE_GLOB_INFO_IMAGE_URL } = getAppEnvConfig();

  const MapboxComponent = ref();
  const mapConfig = ref({});
  watch(
    () => props.showInfoData,
    () => {
      getConfig({ code: 'mapsetting' }).then((res) => {
        mapConfig.value = JSON.parse(res.codeValue);
      });
      changeTask();
    },
  );
  const props = defineProps(['showInfoData','hiddenInfoMap']);
  const activeKey = ref('1');

  const geomsList = ref();
  const imageList = ref([]);

  async function getCaseImgList() {
    imageList.value = await getLoadCaseImgList({
      caseid: props.showInfoData.id,
      category: '乱占耕地建房',
    });
    MapboxComponent.value.handlerLoadPictureAzimuth(imageList.value);

    // 匹配去除无效图片
    // let zhengshiImageList = [];
    // imageList.value?.forEach((item,index)=>{
    //   let obj = anjianzhaopianList.value?.find((it,idx)=>{
    //     return item.filePath == it;
    //   })
    //   if(obj){
    //     zhengshiImageList.push(imageList.value[index]);
    //   }
    // })
  }

  function handlerDealFileName(path) {
    const regex = /([^/\\]+)(?=\.[^/\\]*$|$)/;
    const matchStr = path.match(regex);
    if (matchStr?.length) {
      return matchStr[0];
    }
  }

  function handlerPreviewImage(index, url) {
    const regex = /([^/\\]+)(?=\.[^/\\]*$|$)/;
    const match = url.match(regex);
    if (match) {
      MapboxComponent.value.handlerCurrentImageChange(match[1]);
    }
  }

  const isInitImageLisener = ref<Boolean>(false);
  // 监听预览图片地址变化进行箭头切换
  function handlerImageChange(e): void {
    isInitImageLisener.value = false;
    if (e && !isInitImageLisener.value) {
      setTimeout(function () {
        const targetNode = document.getElementsByClassName('ant-image-preview-img');
        targetNode?.forEach((node,index)=>{
          let imageObserver = new MutationObserver((mutationsList)=>{
            for(const mutation of mutationsList){
              if (node.getAttribute(mutation.attributeName).match('http')){
                handlerPreviewImage(0, node.getAttribute(mutation.attributeName));
              }
            }
          })
          const config = { attributes: true };
          imageObserver.observe(node, config);
          isInitImageLisener.value = true;
        })
      }, 250);
    }
  }

  onBeforeMount(() => {});

  const anjianzhaopianList = computed(() => {
    getCaseImgList();
    return props.showInfoData.anjianzhaopian ? props.showInfoData.anjianzhaopian.split(',') : [];
  });
  const casepicList = computed(() => {
    return props.showInfoData.casepic ? props.showInfoData.casepic.split(',') : [];
  });
  const chaichufugenghoupicList = computed(() => {
    return props.showInfoData.chaichufugenghoupic
      ? props.showInfoData.chaichufugenghoupic.split(',')
      : [];
  });
  const bubanzhaopianList = computed(() => {
    return props.showInfoData.bubanzhaopian ? props.showInfoData.bubanzhaopian.split(',') : [];
  });
  const fujianList = computed(() => {
    return props.showInfoData.fujian ? props.showInfoData.fujian.split(',') : [];
  });
  const hefafujianList = computed(() => {
    return props.showInfoData.hefafujian ? props.showInfoData.hefafujian.split(',') : [];
  });
  const qitafujianList = computed(() => {
    return props.showInfoData.qitafujian ? props.showInfoData.qitafujian.split(',') : [];
  });
  const zhenggaifujianList = computed(() => {
    return props.showInfoData.zhenggaifujian ? props.showInfoData.zhenggaifujian.split(',') : [];
  });
  const yanshoubiaoList = computed(() => {
    return props.showInfoData.yanshoubiao ? props.showInfoData.yanshoubiao.split(',') : [];
  });
  const wrjffzhaopianList = computed(() => {
    return props.showInfoData.wrjffzhaopian ? props.showInfoData.wrjffzhaopian.split(',') : [];
  });
  const xchczhaopianList = computed(() => {
    return props.showInfoData.xchczhaopian ? props.showInfoData.xchczhaopian.split(',') : [];
  });
  function onMapboxLoad() {
    changeTask();
  }
  const getLabel = (type, value) => {
    let result: any[] = [];
    let label = '';
    switch (type) {
      case 'is_illegal':
        result = mapTypeOptions;
        break;
      case 'weifaleixing':
        result = illegalTypeList;
        break;
      case 'measure_name':
        result = measureOptions;
        break;
      case 'result_name':
        result = resultOptions;
        break;
      case 'qita_use_to':
        result = qitaUseTOOptions;
        break;
    }
    result.forEach((item) => {
      if (item.value == value) {
        label = item.label;
      }
    });
    return label;
  };
  async function changeTask() {
    let getGeomPrams = {
      TableName: 'drone_shp_data ',
      FieldName: 'gid',
      FieldValue: props.showInfoData.geomid?.split(','),
      page: 1,
      limit: 999,
      key: null,
    };
    if (props.showInfoData.geomid) {
      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);
              geomsList.value = geoms;
            });
          }
          // MapboxComponent.value.handlerDraw(status,mapgemoList.value, false);
          MapboxComponent.value.handlerDraw('Details', geoms, false);
        } else {
          geomsList.value = null;
          createMessage.error('当前数据没有线索！');
        }
      });
    } else {
      createMessage.error('当前数据没有线索！');
    }
  }

///////// File Preview && Download  ////////

import FilePreview from '@/components/Upload/src/components/FilePreview.vue';

const previewFileModalVisible = ref(false);
const previewFileUrl = ref("");

const hanlderPreViewFile = (url)=>{
  previewFileUrl.value = `${VITE_GLOB_INFO_IMAGE_URL}/${url}`;
  previewFileModalVisible.value = true;
}

const handlerDownloadFle = ()=>{
  window.open(previewFileUrl.value, 'mozillaTab');
}

const handleCancelPreviewFile = ()=>{
  previewFileModalVisible.value = false;
}
///////

  const getContainer = () => {
    return document.getElementById('info-container');
  };
  const dataProcessing = (value) => {
    if (!value) {
      return '0';
    }
    if (value.indexOf('.') == -1) {
      return value;
    } else {
      if (value.split('.')[1].length <= 3) {
        return value;
      }
      let resultString = value.replace('㎡', '');
      return Number(resultString).toFixed(3);
    }
  };
  const showImage = (url) => {
    if (url.indexOf('.png') !== -1 || url.indexOf('.jpg') !== -1 || url.indexOf('.jpeg') !== -1) {
      return true;
    } else {
      return false;
    }
  };
</script>

<style lang="scss" scoped>
  .image-div {
    min-width: 340px;
    max-height: 220px;
    overflow: auto;
  }
  .detail-container {
    width: 100%;
    height: calc(100vh - 120px);
    display: flex;
    padding: 0px 20px;
  }
  .detail-container::after {
    content: '';
    display: block;
    clear: both;
    height: 0;
    visibility: none;
  }
  .map-container {
    float: left;
    width: 45vw;
    height: calc(100vh - 100px);
    margin-right: 20px;
  }
  :deep(.ant-image) {
    margin-right: 10px;
    margin-bottom: 10px;
  }
  :deep(.ant-image-preview-switch-left) {
    position: absolute;
  }
  :deep(.ant-image-preview-switch-right) {
    position: absolute;
  }
  .info-container {
    // float: left;
    position: relative;
    flex: 1;
    height: 100%;
    overflow: auto;
    :deep(.ant-image-preview-wrap) {
      position: absolute;
    }
    :deep(.ant-image-preview-mask) {
      position: absolute;
    }
    :deep(.ant-image-preview-operations-wrapper) {
      height: 100%;
      position: absolute;
      .ant-image-preview-operations {
        position: absolute;
        top: 0;
        width: 100%;
        .ant-image-preview-operations-operation {
          // flex:1;
        }
      }
      .ant-image-preview-operations-operation:nth-last-child(1) {
        display: none;
      }
      .ant-image-preview-operations-operation:nth-last-child(2) {
        display: none;
      }
    }
  }
  ::v-deep .ant-tabs .ant-tabs-content-holder {
    overflow: auto;
    height: 80vh;
    overflow: auto;
    padding-right: 10px;
  }
</style>
