<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-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="线索下发">
          <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.typename
            }}</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.nongyongdi_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="占生态红线面积(亩)">{{
              dataProcessing(props.showInfoData.shengtaibaohuhongxian_area)
            }}</a-descriptions-item>
            <a-descriptions-item label="线索描述">{{
              props.showInfoData.case_description
            }}</a-descriptions-item>
            <a-descriptions-item label="备注">{{ props.showInfoData.remark }}</a-descriptions-item>
            <a-descriptions-item label="经度">{{ props.showInfoData.lng }}</a-descriptions-item>
            <a-descriptions-item label="纬度">{{ props.showInfoData.lat }}</a-descriptions-item>
            <a-descriptions-item label="下发时间">{{
              props.showInfoData.synchronoustime
            }}</a-descriptions-item>
            <a-descriptions-item label="线索照片">
              <div class="image-div">
                <a-image-preview-group
                  :preview="{
                    getContainer: getContainer,
                  }"
                >
                  <template v-for="(imageItem, imageIndex) in casepicList" :key="imageIndex">
                    <a-image
                      v-if="imageItem"
                      width="100px"
                      height="100px"
                      :src="`${VITE_GLOB_INFO_IMAGE_URL}/${imageItem}`"
                      :preview="{
                        getContainer,
                      }"
                    ></a-image>
                  </template>
                </a-image-preview-group>
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
        <a-tab-pane
          key="2"
          v-if="!['建设用地', '推堆土'].includes(props.showInfoData.typename)"
          tab="线索填报"
          force-render
        >
          <a-descriptions
            :column="2"
            bordered
            :contentStyle="{
              'text-align': 'center',
              'min-width': '250px',
              'word-break': 'break-all',
            }"
          >
            <a-descriptions-item label="判定结果">{{
              getLabel('is_illegal', props.showInfoData.is_illegal)
            }}</a-descriptions-item>
            <a-descriptions-item v-if="props.showInfoData.is_illegal == 1" label="项目名称">{{
              props.showInfoData.xiangmumc
            }}</a-descriptions-item>
            <a-descriptions-item v-if="props.showInfoData.is_illegal == 1" label="项目主体">{{
              props.showInfoData.xiangmuzhuti
            }}</a-descriptions-item>
            <a-descriptions-item v-if="props.showInfoData.is_illegal == 1" label="实际用途">{{
              props.showInfoData.actual_use_to
            }}</a-descriptions-item>

            <!-- <a-descriptions-item v-if="props.showInfoData.is_illegal == 1" label="是否对人处理">{{
              getLabel('is_chuli', props.showInfoData.is_chuli)
            }}</a-descriptions-item>
            <a-descriptions-item v-if="props.showInfoData.is_illegal == 1" label="处理情况说明">{{
              props.showInfoData.chuliqingkuangsm
            }}</a-descriptions-item> -->
            <a-descriptions-item v-if="props.showInfoData.is_illegal == 1" 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-item v-if="props.showInfoData.is_illegal == 0" label="附件">
              <a-image-preview-group :preview="{ getContainer }">
                <template v-for="(item, itemIndex) in hefafujianList" :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-item v-if="props.showInfoData.is_illegal == 2" label="实际用途">{{
              getLabel('qita_use_to', props.showInfoData.qita_use_to)
            }}</a-descriptions-item>
            <a-descriptions-item
              v-if="props.showInfoData.is_illegal == 2"
              label="实际用途其他说明"
              >{{ props.showInfoData.qita_shuoming }}</a-descriptions-item
            >
            <a-descriptions-item v-if="props.showInfoData.is_illegal == 2" label="附件">
              <a-image-preview-group :preview="{ getContainer }">
                <template v-for="(item, itemIndex) in qitafujianList" :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-item v-if="props.showInfoData.is_illegal == 1" label="整改措施">{{
              getLabel('measure_name', props.showInfoData.measure_name)
            }}</a-descriptions-item>
            <a-descriptions-item v-if="props.showInfoData.is_illegal == 1" label="验收表"
              ><a-image-preview-group :preview="{ getContainer }">
                <template v-for="(item, itemIndex) in yanshoubiaoList" :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-item label="判定依据说明">{{
              props.showInfoData.pandingyijushuoming
            }}</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"
                      @click="handlerPreviewImage(imageIndex, imageItem)"
                      width="100px"
                      height="100px"
                      :src="`${VITE_GLOB_INFO_IMAGE_URL}/${imageItem}`"
                      :preview="{
                        getContainer,
                      }"
                    ></a-image>
                  </template>
                </a-image-preview-group>
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="填报人">{{
              props.showInfoData.examiner_name
            }}</a-descriptions-item>
            <a-descriptions-item label="填报时间">{{
              props.showInfoData.examine_time
            }}</a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
        <a-tab-pane
          key="4"
          v-if="!['建设用地', '推堆土'].includes(props.showInfoData.typename)"
          tab="审核情况"
        >
          <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.xjshenhejieguo
            }}</a-descriptions-item>
            <a-descriptions-item label="审核意见">{{
              props.showInfoData.xianjiyijian
            }}</a-descriptions-item>
            <a-descriptions-item label="审核人">{{
              props.showInfoData.verifyuser
            }}</a-descriptions-item>
            <a-descriptions-item label="审核时间">{{
              props.showInfoData.verifytime
            }}</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="审核结果">{{
              props.showInfoData.sjshenhejieguo
            }}</a-descriptions-item>
            <a-descriptions-item label="审核意见">{{
              props.showInfoData.shijiyijian
            }}</a-descriptions-item>
            <a-descriptions-item label="审核人">{{
              props.showInfoData.hexiaoren
            }}</a-descriptions-item>
            <a-descriptions-item label="审核时间">{{
              props.showInfoData.hexiaotime?.split('.')[0]
            }}</a-descriptions-item>
            <!-- <a-descriptions-item v-if="weifaleixing == 0" label="无人机复飞照片" :span="2">
              <div class="image-div">
                <a-image-preview-group
                  :preview="{
                    getContainer:getContainer,
                  }"
                  >
                  <template v-for="(imageItem, imageIndex) in wrjffzhaopianList" :key="imageIndex">
                    <a-image
                      v-if="imageItem"
                      width="100px"
                      height="100px"
                      :src="`${VITE_GLOB_INFO_IMAGE_URL}/${imageItem}`"
                      :preview="{
                        getContainer,
                      }"
                    ></a-image>
                  </template>
                </a-image-preview-group>
              </div>
            </a-descriptions-item> -->
            <!-- <a-descriptions-item label="现场核查照片" :span="2">
              <div class="image-div">
                <a-image-preview-group
                  :preview="{
                    getContainer:getContainer,
                  }"
                  >
                  <template v-for="(imageItem, imageIndex) in xchczhaopianList" :key="imageIndex">
                    <a-image
                      v-if="imageItem"
                      width="100px"
                      height="100px"
                      :src="`${VITE_GLOB_INFO_IMAGE_URL}/${imageItem}`"
                      :preview="{
                        getContainer,
                      }"
                    ></a-image>
                  </template>
                </a-image-preview-group>
              </div>
            </a-descriptions-item> -->
          </a-descriptions>
        </a-tab-pane>
      </a-tabs>
    </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/redlinesupervision/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import axios from 'axios';
  import Icon from '@/components/Icon/Icon.vue';
  import { getAppEnvConfig } from '@/utils/env';
  import {
    mapTypeOptions,
    redLineMeasureOptions,
    illegalTypeList,
    resultOptions,
    qitaUseTOOptions,
    isChuliOptions,
  } from '@/utils/global';

  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 = redLineMeasureOptions;
        break;
      case 'result_name':
        result = resultOptions;
        break;
      case 'qita_use_to':
        result = qitaUseTOOptions;
        break;
      case 'is_chuli':
        result = isChuliOptions;
    }
    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('当前数据没有线索！');
    }
  }
  // const hanlderPreViewFile = (url) => {
  //   if (url.indexOf('.pdf') !== -1) {
  //     axios({
  //       method: 'get',
  //       url: `${VITE_GLOB_INFO_IMAGE_URL}/${url}`,
  //       responseType: 'blob',
  //       headers: {
  //         'Content-Disposition': 'inline',
  //       },
  //     })
  //       .then((response) => {
  //         let blob = new Blob([response.data], { type: 'application/pdf' });
  //         let url = window.URL.createObjectURL(blob);
  //         window.open(url);
  //       })
  //       .catch((error) => {
  //         console.error(error);
  //       });
  //   } else {
  //     window.open(`${VITE_GLOB_INFO_IMAGE_URL}/${url}`, '_blank');
  //   }
  // };

  ///////// 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 <= 2) {
        return value;
      }
      let resultString = value.replace('㎡', '');
      return Number(resultString).toFixed(2);
    }
  };
  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;
    :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>
