<template>
  <div class="detail-container">

    <!-- 加载框 -->
    <div class="load-mask" v-if="isLandTypeSpliting">
      <a-spin class="loader-block" size="large" tip="正在分割中......" />
    </div>

    <div class="left-container">
      <a-divider orientation="left">图斑信息</a-divider>
      <div class="map-container">
        <MapboxMap
          :caseno="case_no"
          :countyname="countyname"
          :geomsList="geomsList"
          :mapConfig="mapConfig"
          @handlerSplitPolygon="handlerSplitPolygon"
          @handlerStartSpliting="handlerStartSpliting"
          @mapOnLoad="onMapboxLoad"
          :splitPlugin="true"
          @onFeatureClick="onFeatureClick"
          ref="MapboxComponent"
          v-if="mapshow"
        />
      </div>

      <div class="info-container" id="info-container">
        <a-tabs v-model:activeKey="activeKey" style="height: 100%">
          <a-tab-pane key="1" tab="线索下发">
            <a-descriptions
              :column="2"
              bordered
              size="small"
              :contentStyle="{
                'text-align': 'center',
                'min-width': '250px',
                'word-break': 'break-all',
              }"
            >
              <a-descriptions-item label="图斑编号">{{ case_no }}</a-descriptions-item>
              <a-descriptions-item label="图斑类型">{{ typename }}</a-descriptions-item>
              <a-descriptions-item label="县区">{{ countyname }}</a-descriptions-item>
              <a-descriptions-item label="乡镇">{{ streetname }}</a-descriptions-item>
              <a-descriptions-item label="社区/村">{{ communityname }}</a-descriptions-item>
              <a-descriptions-item label="图斑面积(亩)">{{
                dataProcessing(area)
              }}</a-descriptions-item>
              <a-descriptions-item label="农用地面积(亩)">{{
                dataProcessing(nongyongdi_area)
              }}</a-descriptions-item>
              <a-descriptions-item label="耕地面积(亩)">{{
                dataProcessing(gengdi_area)
              }}</a-descriptions-item>
              <a-descriptions-item label="永农面积(亩)">{{
                dataProcessing(yongjiujibennongtian_area)
              }}</a-descriptions-item>
              <!-- <a-descriptions-item label="占重点区域面积(亩)">{{ dataProcessing(zhongdianquyu_area) }}</a-descriptions-item> -->
              <a-descriptions-item label="占生态红线面积(亩)">{{
                dataProcessing(shengtaibaohuhongxian_area)
              }}</a-descriptions-item>
              <!-- <a-descriptions-item label="占空间规划面积(亩)">{{ dataProcessing(guotukongjianguihua_area) }}</a-descriptions-item> -->
              <a-descriptions-item label="图斑描述">{{ case_description }}</a-descriptions-item>
              <!-- <a-descriptions-item label="图斑地址">{{ address }}</a-descriptions-item> -->
              <a-descriptions-item label="备注">{{ remark }}</a-descriptions-item>
              <a-descriptions-item label="经度">{{ lng }}</a-descriptions-item>
              <a-descriptions-item label="纬度">{{ lat }}</a-descriptions-item>
              <a-descriptions-item label="下发时间">{{ createtime }}</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-item label="接收人">{{ jieshou_people }}</a-descriptions-item>
              <a-descriptions-item label="接收时间">{{
                jieshou_time?.split('.')[0]
              }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          <a-tab-pane
            key="2"
            v-if="!['建设用地', '推堆土'].includes(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', is_illegal)
              }}</a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 1" label="项目名称">{{
                xiangmumc
              }}</a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 1" label="项目主体">{{
                xiangmuzhuti
              }}</a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 1" label="实际用途">{{
                actual_use_to
              }}</a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 1" label="违法类型">{{
                getLabel('weifaleixing', weifaleixing)
              }}</a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 1" label="附件">
                <template v-for="(item, itemIndex) in fujianList" :key="itemIndex">
                  <div v-if="item" style="margin-top: 10px">
                    <Icon
                      :style="`font-size: 30px; cursor: pointer;`"
                      icon="ion:document-attach-outline"
                      @click="hanlderPreViewFile(item)"
                    />
                    {{ handlerDealFileName(item) }}
                  </div>
                </template>
              </a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 0" label="附件">
                <template v-for="(item, itemIndex) in hefafujianList" :key="itemIndex">
                  <div v-if="item" style="margin-top: 10px">
                    <Icon
                      :style="`font-size: 30px; cursor: pointer;`"
                      icon="ion:document-attach-outline"
                      @click="hanlderPreViewFile(item)"
                    />
                    {{ handlerDealFileName(item) }}
                  </div>
                </template>
              </a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 2" label="实际用途">{{
                getLabel('qita_use_to', qita_use_to)
              }}</a-descriptions-item>
              <a-descriptions-item v-if="is_illegal == 2" label="附件">
                <template v-for="(item, itemIndex) in qitafujianList" :key="itemIndex">
                  <div v-if="item" style="margin-top: 10px">
                    <Icon
                      :style="`font-size: 30px; cursor: pointer;`"
                      icon="ion:document-attach-outline"
                      @click="hanlderPreViewFile(item)"
                    />
                    {{ handlerDealFileName(item) }}
                  </div>
                </template>
              </a-descriptions-item>
              <a-descriptions-item label="判定依据说明">{{
                pandingyijushuoming
              }}</a-descriptions-item>
              <a-descriptions-item label="照片">
                <div class="image-div">
                  <a-image-preview-group
                    :preview="{
                      getContainer: getContainer,
                    }"
                  >
                    <template
                      v-for="(imageItem, imageIndex) in anjianzhaopianList"
                      :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="填报人">{{ examiner_name }}</a-descriptions-item>
              <a-descriptions-item label="填报时间">{{ examine_time }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          <a-tab-pane
            key="3"
            tab="整改情况"
            v-if="weifaleixing == 0 && !['建设用地', '推堆土'].includes(typename)"
          >
            <a-descriptions
              :column="2"
              bordered
              :contentStyle="{
                'text-align': 'center',
                'min-width': '250px',
                'word-break': 'break-all',
              }"
            >
              <a-descriptions-item label="整改措施">{{
                getLabel('measure_name', measure_name)
              }}</a-descriptions-item>
              <a-descriptions-item v-if="measure_name == 0" label="附件">
                <template v-for="(item, itemIndex) in yanshoubiaoList" :key="itemIndex">
                  <div v-if="item">
                    <Icon
                      :style="`font-size: 30px; cursor: pointer;`"
                      icon="ion:document-attach-outline"
                      @click="hanlderPreViewFile(item)"
                    />
                    {{ handlerDealFileName(item) }}
                  </div>
                </template>
              </a-descriptions-item>
              <a-descriptions-item v-if="measure_name == 0" label="照片">
                <div class="image-div">
                  <a-image-preview-group
                    :preview="{
                      getContainer: getContainer,
                    }"
                  >
                    <template
                      v-for="(imageItem, imageIndex) in chaichufugenghoupicList"
                      :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 v-if="measure_name == 1" label="附件">
                <template v-for="(item, itemIndex) in zhenggaifujianList" :key="itemIndex">
                  <div v-if="item">
                    <Icon
                      :style="`font-size: 30px; cursor: pointer;`"
                      icon="ion:document-attach-outline"
                      @click="hanlderPreViewFile(item)"
                    />
                    {{ handlerDealFileName(item) }}
                  </div>
                </template>
                <!-- {{ zhenggaifujian }} -->
              </a-descriptions-item>
              <a-descriptions-item v-if="measure_name == 1" label="照片">
                <div class="image-div">
                  <a-image-preview-group
                    :preview="{
                      getContainer: getContainer,
                    }"
                  >
                    <template
                      v-for="(imageItem, imageIndex) in bubanzhaopianList"
                      :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="办理人">{{ transactor_name }}</a-descriptions-item>
              <a-descriptions-item label="办理时间">{{ transact_time }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          <a-tab-pane key="4" v-if="!['建设用地', '推堆土'].includes(typename)" tab="审核">
            <a-descriptions
              :column="2"
              bordered
              :contentStyle="{
                'text-align': 'center',
                'min-width': '250px',
                'word-break': 'break-all',
              }"
            >
              <a-descriptions-item label="审核人">{{ verifyuser }}</a-descriptions-item>
              <a-descriptions-item label="审核时间">{{ verifytime }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>

    <div class="right-container">
      <a-divider orientation="left">图斑分割结果 </a-divider>
      <div class="data-list">
        <div
          v-for="(item, index) in splitPolygonForm"
          :key="index"
          class="data-list-item"
          @click="changeCurrentPolygon(index, item)"
          :style="{ 'border-color': currentPolygon == index ? '#408eff' : '#fff' }"
        >
          <div class="data-list-layout-div">
            <div class="data-list-checked">
              <a-checkbox v-model:checked="item.checked"></a-checkbox>
            </div>
            <div class="data-list-title-div">
              <img
                src="/positioning.png"
                class="map-mark"
                style="cursor: pointer"
                @click="locationFun(item)"
              />
              <div class="label-div">
                <div class="item-label">{{ item.countyname }}</div>
                <div class="item-sub-label">
                  <span style="margin-right: 12px">{{ item.streetname }}</span>
                  <span>{{ item.caseno }}</span>
                </div>
              </div>
              <div class="item-mark" v-if="item.isbuildname">{{ item.isbuildname }}</div>
            </div>
            <div class="data-item-type-div" style="cursor: pointer" @click="goAudit(item)">
              {{ item.unitname }}
            </div>
          </div>
          <div class="data-list-info-div">
            <div class="info-layout-div">
              <div
                class="info-item"
                :style="{
                  width: '130px',
                  'border-color': areaAbnormal['area'] ? 'orange' : 'rgba(237, 237, 237, 0.55)',
                }"
              >
                <div class="info-label">总面积</div>
                <div class="info-data" :title="`${item.area || '0'}亩`"
                  >{{ item.area ? item.area : 0 }}亩</div
                >
              </div>
              <div
                class="info-item"
                :style="{
                  'border-color': areaAbnormal['nongyongdi_area']
                    ? 'orange'
                    : 'rgba(237, 237, 237, 0.55)',
                }"
              >
                <div class="info-label">农用地</div>
                <div class="info-data" :title="`${item.nongyongdi_area || '0'}亩`"
                  >{{ item.nongyongdi_area ? item.nongyongdi_area : 0 }}亩</div
                >
              </div>
              <div
                class="info-item"
                :style="{
                  'border-color': areaAbnormal['gengdi_area']
                    ? 'orange'
                    : 'rgba(237, 237, 237, 0.55)',
                }"
              >
                <div class="info-label">耕地</div>
                <div class="info-data" :title="`${item.gengdi_area || '0'}亩`"
                  >{{ item.gengdi_area ? item.gengdi_area : 0 }}亩</div
                >
              </div>
              <div
                class="info-item"
                :style="{
                  width: '120px',
                  'border-color': areaAbnormal['yongjiujibennongtian_area']
                    ? 'orange'
                    : 'rgba(237, 237, 237, 0.55)',
                }"
              >
                <div class="info-label">永农面积</div>
                <div class="info-data" :title="`${item.yongjiujibennongtian_area || '0'}亩`"
                  >{{ item.yongjiujibennongtian_area ? item.yongjiujibennongtian_area : 0 }}亩</div
                >
              </div>
            </div>

            <div class="info-layout-div">
              <span class="info-time">{{ item.createdate }}</span>
              <div>
                <Icon
                  title="详情"
                  style="font-size: 30px; cursor: pointer"
                  icon="bx:detail"
                  @click="showInfo(index, item)"
                />
              </div>
            </div>
          </div>
        </div>
        <a-empty
          v-if="splitPolygonForm.length == 0"
          style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%)"
        />
      </div>
      <div class="split-operation">
        <!-- <a-button type="primary" :disabled="isSpliting" @click="mergeSplitResult">合并图斑</a-button> -->
        <!-- &nbsp;
        <a-button type="error" :disabled="isSpliting" @click="deleteSplitResult">删除图斑</a-button> -->
        &nbsp;
        <a-button type="primary" :disabled="isSpliting" @click="reductionSplit">还原分割</a-button>
        &nbsp;
        <a-button type="primary" :disabled="isSpliting" @click="saveSplitResult">保存分割</a-button>
      </div>
    </div>
  </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 -->

  <a-modal
    v-model:open="splitPolygonDetailShow"
    style="width: 600px"
    title="面积设置"
    @ok="handleOk"
  >
    <div class="" style="padding: 20px">
      <a-form
        :model="splitPolygonAreaForm"
        name="面积设置"
        :label-col="{ span: 11 }"
        :wrapper-col="{ span: 14 }"
        autocomplete="off"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item label="图斑面积" name="area">
              <a-input
                v-model:value="splitPolygonAreaForm.area"
                @keydown.stop
                @blur="checkArea('area')"
                :status="areaAbnormal['area'] ? 'error' : ''"
                addon-after="亩"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="农用地面积" name="nongyongdi_area">
              <a-input
                v-model:value="splitPolygonAreaForm.nongyongdi_area"
                @keydown.stop
                :status="areaAbnormal['nongyongdi_area'] ? 'error' : ''"
                @blur="checkArea('nongyongdi_area')"
                addon-after="亩"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="耕地面积" name="gengdi_area">
              <a-input
                v-model:value="splitPolygonAreaForm.gengdi_area"
                @keydown.stop
                :status="areaAbnormal['gengdi_area'] ? 'error' : ''"
                @blur="checkArea('gengdi_area')"
                addon-after="亩"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="永农面积" name="yongjiujibennongtian_area">
              <a-input
                v-model:value="splitPolygonAreaForm.yongjiujibennongtian_area"
                @keydown.stop
                :status="areaAbnormal['yongjiujibennongtian_area'] ? 'error' : ''"
                @blur="checkArea('yongjiujibennongtian_area')"
                addon-after="亩"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="占生态红线面积" name="shengtaibaohuhongxian_area">
              <a-input
                v-model:value="splitPolygonAreaForm.shengtaibaohuhongxian_area"
                @keydown.stop
                :status="areaAbnormal['shengtaibaohuhongxian_area'] ? 'error' : ''"
                @blur="checkArea('shengtaibaohuhongxian_area')"
                addon-after="亩"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- <a-row>
          <a-col :span="12">
            <a-form-item label="占重点区域面积" name="zhongdianquyu_area">
              <a-input
                v-model:value="splitPolygonAreaForm.zhongdianquyu_area"
                :status="areaAbnormal['zhongdianquyu_area'] ? 'error' : ''"
                @blur="checkArea('zhongdianquyu_area')"
                addon-after="亩"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="占空间规划面积" name="guotukongjianguihua_area">
              <a-input
                v-model:value="splitPolygonAreaForm.guotukongjianguihua_area"
                :status="areaAbnormal['guotukongjianguihua_area'] ? 'error' : ''"
                @blur="checkArea('guotukongjianguihua_area')"
                addon-after="亩"
              />
            </a-form-item>
          </a-col>
        </a-row> -->
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { onMounted, defineProps, ref, computed, defineEmits } from 'vue';
  import axios from 'axios';
  import MapboxMap from '@/components/MapboxMaps/MapComponent.vue';
  import { getConfig } from '@/api/sys/layerManagement';
  import { getGeom,calTubanArea } from '@/api/sys/layerManagement';
  import { CalTubanAreaModel } from '@/api/sys/model/layerModel';
  import { splitCase } from '@/api/redlinesupervision/index';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import Icon from '@/components/Icon/Icon.vue';
  import { getAppEnvConfig } from '@/utils/env';
  const { VITE_GLOB_API_URL, VITE_GLOB_INFO_IMAGE_URL } = getAppEnvConfig();
  import { GeojsonToWkt,removeZM } from '@/components/MapboxMaps/src/WktGeojsonTransform';
  import {
    mapTypeOptions,
    illegalTypeOptions,
    measureOptions,
    mapStatusOptions,
    markTypeOptions,
    illegalTypeList,
    resultOptions,
    qitaUseTOOptions,
  } from '@/utils/global';
  import { getLoadDroneCaseInfoDetail } from '@/api/redlinesupervision/index';
  import ShowInfoModal from '@/views/demo/tiankongdi/curbspotcity/MapList/ShowInfoModal/index';
  import { dataProcessing, dataProcessingCount } from '@/views/demo/tiankongdi/util';
  import { itemProps } from '@/components/Menu/src/props';

  const MapboxComponent = ref();
  const mapConfig = ref({});
  getConfig({ code: 'mapsetting' }).then((res) => {
    mapConfig.value = JSON.parse(res.codeValue);
  });

  const emits = defineEmits(['closeModal']);
  const props = defineProps(['showInfoData']);
  const activeKey = ref('1');
  const geomsList = ref();

  const isSpliting = ref<Boolean>(false);

  const mapshow = ref<Boolean>(false);
  onMounted(() => {
    mapshow.value = true;
  });
  const {
    id,
    case_no,
    case_name,
    case_description,
    start_time,
    end_time,
    address,
    lng,
    lat,
    typeid,
    typename,
    handle_status_id,
    handle_status_name,
    case_status_i,
    case_status_name,
    createtime,
    createuser,
    drone_no,
    deal_userid,
    deal_username,
    createusername,
    is_delete,
    countyid,
    countyname,
    streetid,
    streetname,
    communityid,
    communityname,
    remark,
    is_closed,
    area,
    is_illegal,
    close_user,
    close_time,
    identification_user,
    identification_time,
    is_intact,
    close_userid,
    identification_userid,
    verifyuserid,
    verifyuser,
    verifytime,
    is_improve,
    improve_reason,
    is_dispense,
    dispense_userid,
    dispense_time,
    dispense_username,
    verifystatus,
    verifystatusname,
    is_checked,
    deal_time,
    is_drawback,
    examiner_id,
    examiner_name,
    examine_time,
    measure_name,
    casepic,
    opinion,
    result,
    result_name,
    opinion_name,
    handletime,
    handleuser,
    handleusername,
    is_assist,
    measure_name_deal,
    qita_use_to,
    illegal_contact,
    illegal_shenfenzhenghao,
    investigation_type,
    investigation_result,
    registr_number,
    is_build_complete,
    actual_use_to,
    transactor_id,
    transactor_name,
    transact_time,
    geomid,
    nongyongdi_area,
    gengdi_area,
    yongjiujibennongtian_area,
    zhongdianquyu_area,
    shengtaibaohuhongxian_area,
    guotukongjianguihua_area,
    fujian,
    hefafujian,
    qitafujian,
    jieshou_people,
    jieshou_time,
    pandingyijushuoming,
    xiangmumc,
    xiangmuzhuti,
    weifaleixing,
    yanshoubiao,
    zhenggaifujian,
    chaichufugenghoupic,
    bubanzhaopian,
    is_jieshou,
    anjianzhaopian,
    processid,
  } = props.showInfoData;

  const anjianzhaopianList = computed(() => {
    return anjianzhaopian ? anjianzhaopian.split(',') : [];
  });
  const casepicList = computed(() => {
    return casepic ? casepic.split(',') : [];
  });
  const chaichufugenghoupicList = computed(() => {
    return chaichufugenghoupic ? chaichufugenghoupic.split(',') : [];
  });
  const bubanzhaopianList = computed(() => {
    return bubanzhaopian ? bubanzhaopian.split(',') : [];
  });
  const fujianList = computed(() => {
    return fujian ? fujian.split(',') : [];
  });
  const hefafujianList = computed(() => {
    return hefafujian ? hefafujian.split(',') : [];
  });
  const qitafujianList = computed(() => {
    return qitafujian ? qitafujian.split(',') : [];
  });
  const zhenggaifujianList = computed(() => {
    return zhenggaifujian ? zhenggaifujian.split(',') : [];
  });
  const yanshoubiaoList = computed(() => {
    return yanshoubiao ? yanshoubiao.split(',') : [];
  });

  function onMapboxLoad() {
    changeTask();
  }

  // 附件名称显示处理函数
  function handlerDealFileName(path) {
    const regex = /([^/\\]+)(?=\.[^/\\]*$|$)/;
    const matchStr = path.match(regex);
    if (matchStr?.length) {
      return matchStr[0];
    }
  }

  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;
  };
  function changeTask() {
    if (props.showInfoData.geomid) {
      let getGeomPrams = {
        TableName: 'drone_shp_data',
        FieldName: 'gid',
        FieldValue: props.showInfoData.geomid?.split(','),
        page: 1,
        limit: 999,
        key: null,
      };
      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) => {
  //   window.open(`${VITE_GLOB_INFO_IMAGE_URL}/${url}`, 'mozillaTab');
  // };

  ///////// 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 isLandTypeSpliting = ref<Boolean>(false);
  // 开始分割
  const handlerStartSpliting = (e)=> {
    isLandTypeSpliting.value = e;
  }

  const splitPolygonForm = ref([]);
  const splitAfterPolygon = ref([]);
  const handlerSplitPolygon = (e) => {


    // 删除被分割的图斑
    if(currentPolygon.value){
      splitPolygonForm.value?.splice(currentPolygon.value,1);
      splitAfterPolygon.value?.splice(currentPolygon.value,1);
    }

    isLandTypeSpliting.value = false;

    // 面积计算
    let sumArea = 0.0;

    e?.forEach((item, index) => {
      // 去除GeoJSON Z坐标
      let afterItem = removeZM(item['geometry'])

      let calAreaParams:CalTubanAreaModel = {
        "wktgeom": GeojsonToWkt(item['geometry']),
      }
      
      calTubanArea(calAreaParams).then(resultItem=>{
        if(resultItem){
          
            let form = {
              fid: null,
              unitname: '',
              createdate: createtime,
              caseno: case_no + '  分割图斑',
              countyname: countyname,
              streetname: streetname,
              isbuildname: '',
              nongyongdi_area: resultItem.nongyongdi > 0 ? resultItem.nongyongdi : 0.00,
              gengdi_area: resultItem.gengdi > 0 ? resultItem.gengdi : 0.00,
              yongjiujibennongtian_area: resultItem.jibennongtian > 0 ? resultItem.jibennongtian : 0.00,
              shengtaibaohuhongxian_area: resultItem.shengtaihongxian > 0 ? resultItem.shengtaihongxian : 0.00,
              guotukongjianguihua_area: null,
              area: resultItem.totalmianji > 0 ? resultItem.totalmianji : 0.00,
              geom: item,
              checked:false,
            };

            splitPolygonForm.value?.push(form);
            splitAfterPolygon.value?.push(form.geom)


            // 分割完成后重新渲染面数据
            let splitAfterFeatures = {
              type: 'FeatureCollection',
              features: [],
            };
            splitPolygonForm.value?.forEach((item,idnex)=>{
              splitAfterFeatures.features.push(item.geom);
            })
            
            const areKeyDownChange = MapboxComponent.value.handlerDetails(splitAfterFeatures);

        }
      })

      // var polygon = null;
      // if(item.geometry.type == 'Polygon'){
      //   polygon = turf.polygon(item.geometry.coordinates)
      // }else if(item.geometry.type == 'MultiPolygon'){
      //   polygon  =  turf.multiPolygon(item.geometry.coordinates)
      // }   
      // let are = (turf.area(polygon) / 666.666666666667).toFixed(2);

      // if(index == e.length-1){
      //   are = (parseFloat(area) - sumArea).toFixed(2);
      // }
      // sumArea = sumArea + are;

      
    });



    // 清空选中图斑
    let geoms = {
      type: 'FeatureCollection',
      features: [],
    };

    MapboxComponent.value.handlerDetails(geoms, 'splitPolygonSource', 'splitPolygonLayer', {
      lineStyle: { 'line-color': '#408eff', 'line-width': 3 },
      fillStyle: { 'fill-color': '#408eff', 'fill-opacity': 0.1 },
    });

    currentPolygon.value = null;

  };

  const handlerEditPolygonInfo = (e) => {
    console.log(e);
  };

  const infoDataList = ref([]);

  const getInfoList = () => {
    getLoadDroneCaseInfoDetail({}).then((res) => {
      infoDataList.value = res.items;
    });
  };

  getInfoList();

  const splitPolygonDetailShow = ref(false);
  const splitPolygonAreaForm = ref({
    nongyongdi_area: null,
    gengdi_area: null,
    yongjiujibennongtian_area: null,
    shengtaibaohuhongxian_area: null,
    guotukongjianguihua_area: null,
    area: null,
    geom: null,
  });
  const showInfo = (index, item) => {
    splitPolygonAreaForm.value = splitPolygonForm.value[index];
    splitPolygonDetailShow.value = true;
  };

  // 切换图斑
  const currentPolygon = ref(null);
  const changeCurrentPolygon = (index, item) => {
    let geoms = {
      type: 'FeatureCollection',
      features: [item.geom],
    };
    // 绘图图斑
    MapboxComponent.value.handlerDetails(geoms, 'splitPolygonSource', 'splitPolygonLayer', {
      lineStyle: { 'line-color': '#408eff', 'line-width': 3 },
      fillStyle: { 'fill-color': '#408eff', 'fill-opacity': 0.1 },
    });
    currentPolygon.value = index;
  };

  // 图斑点击事件
  const onFeatureClick = (feature) => {
    splitPolygonForm.value?.forEach((item, index) => {
      if (item['geom']['properties']['id'] == feature.properties.id) {
        changeCurrentPolygon(index, item);
      }
    });
  };

  // handleOk
  const handleOk = () => {
    splitPolygonDetailShow.value = false;
  };

  // 还原分割
  const reductionSplit = () => {
    changeTask();
    let geoms = {
      type: 'FeatureCollection',
      features: [],
    };
    MapboxComponent.value.handlerDetails(geoms, 'splitPolygonSource', 'splitPolygonLayer', {
      lineStyle: { 'line-color': '#408eff', 'line-width': 3 },
      fillStyle: { 'fill-color': '#408eff', 'fill-opacity': 0.1 },
    });
    splitPolygonForm.value = [];
    splitAfterPolygon.value = [];
    currentPolygon.value = null;
  };

  // 删除图斑
  const deleteSplitResult = () => {
    // 剔除选中数据
    let deleteIndexs = [];
    splitPolygonForm.value?.forEach((item, index) => {
      if (item.checked) {
        deleteIndexs.push(index);
      }
    });

    if (deleteIndexs.length < 1) {
      createMessage.error('请选择需要删除的图斑！');
      return;
    }

    removeElementsByIndexes(splitAfterPolygon.value, deleteIndexs);
    removeElementsByIndexes(splitPolygonForm.value, deleteIndexs);

    // 渲染图斑数据
    let geoms = {
      type: 'FeatureCollection',
      features: splitAfterPolygon.value ? splitAfterPolygon.value : [],
    };
    console.log('geoms123', geoms);
    MapboxComponent.value.handlerDetails(geoms, 'detailsSource', 'detailsLayer', {
      lineStyle: { 'line-color': '#fcf003', 'line-width': 3 },
      fillStyle: { 'fill-color': '#fcf003', 'fill-opacity': 0.1 },
    });

    let checkedGeoms = {
      type: 'FeatureCollection',
      features: [],
    };
    console.log('geoms12345', checkedGeoms);

    MapboxComponent.value.handlerDetails(checkedGeoms, 'splitPolygonSource', 'splitPolygonLayer', {
      lineStyle: { 'line-color': '#408eff', 'line-width': 3 },
      fillStyle: { 'fill-color': '#408eff', 'fill-opacity': 0.1 },
    });
  };

  // 删除操作
  function removeElementsByIndexes(arr, indexes) {
    // 确保下标数组是从大到小排序的，以避免在删除过程中索引发生变化
    indexes.sort((a, b) => b - a);

    // 遍历下标数组，从数组中删除对应的元素
    for (const index of indexes) {
      arr.splice(index, 1);
    }
  }

  // 合并图斑
  const mergeSplitResult = () => {
    let mergeArr = [];
    let deleteIndexs = [];

    splitPolygonForm.value?.forEach((item, index) => {
      if (item.checked) {
        let turfPolygon = turf.polygon(splitAfterPolygon.value[index].geometry.coordinates);
        mergeArr.push(turfPolygon);
        deleteIndexs.push(index);
      }
    });

    if (deleteIndexs.length != 2) {
      createMessage.error('请选择两个图斑进行合并！');
      return;
    }

    removeElementsByIndexes(splitAfterPolygon.value, deleteIndexs);
    removeElementsByIndexes(splitPolygonForm.value, deleteIndexs);

    // 合并后图斑

    let union = turf.union(mergeArr[0], mergeArr[1]);

    let polygon = {
      fid: null,
      unitname: '',
      createdate: createtime,
      caseno: case_no + '  分割图斑',
      countyname: countyname,
      streetname: streetname,
      isbuildname: '',
      nongyongdi_area: null,
      gengdi_area: null,
      yongjiujibennongtian_area: null,
      shengtaibaohuhongxian_area: null,
      guotukongjianguihua_area: null,
      area: null,
      geom: union,
      checked: false,
    };

    splitAfterPolygon.value?.push(union);
    splitPolygonForm.value?.push(polygon);

    // 渲染图斑数据
    let geoms = {
      type: 'FeatureCollection',
      features: splitAfterPolygon.value ? splitAfterPolygon.value : [],
    };
    MapboxComponent.value.handlerDetails(geoms, 'detailsSource', 'detailsLayer', {
      lineStyle: { 'line-color': '#fcf003', 'line-width': 3 },
      fillStyle: { 'fill-color': '#fcf003', 'fill-opacity': 0.1 },
    });

    let checkedGeoms = {
      type: 'FeatureCollection',
      features: [],
    };
    MapboxComponent.value.handlerDetails(checkedGeoms, 'splitPolygonSource', 'splitPolygonLayer', {
      lineStyle: { 'line-color': '#408eff', 'line-width': 3 },
      fillStyle: { 'fill-color': '#408eff', 'fill-opacity': 0.1 },
    });
  };

  // 保存分割
  const saveSplitResult = () => {
    isSpliting.value = true;

    if (splitPolygonForm.value?.length == 0) {
      createMessage.error('请先使用分割工具分割图斑！');
      isSpliting.value = false;
      return null;
    }
    let checkResult = handlerBeforeSubmitCheckArea();
    if (!checkResult) {
      isSpliting.value = false;
      return null;
    }

    let params = {
      parts: [],
      caseid: id,
      processid: props.showInfoData.processid,
    };

    splitPolygonForm.value?.forEach((item, index) => {
      let polygon = {
        nongyongdi_area: item['nongyongdi_area'] ? item['nongyongdi_area'] : '0.00',
        gengdi_area: item['gengdi_area'] ? item['gengdi_area'] : '0.00',
        yongjiujibennongtian_area: item['yongjiujibennongtian_area']
          ? item['yongjiujibennongtian_area']
          : '0.00',
        shengtaibaohuhongxian_area: item['shengtaibaohuhongxian_area']
          ? item['shengtaibaohuhongxian_area']
          : '0.00',
        guotukongjianguihua_area: item['guotukongjianguihua_area']
          ? item['guotukongjianguihua_area']
          : '0.00',
        zhongdianquyu_area: item['zhongdianquyu_area'] ? item['zhongdianquyu_area'] : '0.00',
        area: item['area'] ? item['area'] : '0.00',
        geom: GeojsonToWkt(item['geom']['geometry']),
      };
      params.parts.push(polygon);
    });
    try {
      splitCase(params).then((res) => {
        if (res) {
          createMessage.success('操作成功！');
          emits('closeModal');
          isSpliting.value = false;
        }
      });
    } catch (e) {
      isSpliting.value = false;
    }
  };

  // 检查面积
  const areaAbnormal = ref({
    nongyongdi_area: false,
    gengdi_area: false,
    yongjiujibennongtian_area: false,
    shengtaibaohuhongxian_area: false,
    guotukongjianguihua_area: false,
    zhongdianquyu_area: false,
    area: false,
  });

  const checkArea = (type) => {
    let area = 0.0;
    splitPolygonForm.value.forEach((item, index) => {
      if (item[type]) {
        area += parseFloat(item[type]);
      }
    });

    if (parseFloat(area.toFixed(4)) != dataProcessingCount(props.showInfoData[type])) {
      areaAbnormal.value[type] = true;
    } else {
      areaAbnormal.value[type] = false;
    }
  };

  const handlerBeforeSubmitCheckArea = () => {
    for (let key in areaAbnormal.value) {
      checkArea(key);
    }
    for (let key in areaAbnormal.value) {
      if (areaAbnormal.value[key]) {
        createMessage.error('分割后总面积与原图斑总面积不一致！');
        return false;
      }
    }
    return true;
  };
</script>

<style lang="scss" scoped>
  .image-div {
    min-width: 340px;
    max-height: 220px;
    overflow: auto;
  }
  :deep(.ant-image) {
    margin-right: 10px;
    margin-bottom: 10px;
  }
  :deep(.ant-image-preview-switch-right) {
    position: absolute;
  }
  :deep(.ant-image-preview-switch-left) {
    position: absolute;
  }
  .detail-container {
    width: calc(100vw - 15px);
    height: calc(100vh - 120px);
    display: flex;
    .load-mask{
      width:100%;
      height:100%;
      position:absolute;
      top:0px;
      left:0px;
      background:rgba(0,0,0,0.5);
      z-index:9999;
      .loader-block{
        position: absolute;
        left:50%;
        top:50%;
        transform:translate(-50%,-50%);
      }
    }
    .left-container {
      flex: 1;
      height: 100%;
      .map-container {
        float: left;
        width: 100%;
        height: 400px;
        margin-bottom: 20px;
      }
      .info-container {
        width: 100%;
        height: calc(100% - 470px);
        overflow: hidden;
        float: left;
        position: relative;
        :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;
          }
        }
      }
    }
    .right-container {
      flex: 1;
      padding-left: 20px;
      height: 100%;
      .data-list {
        width: calc(100% - 20px);
        height: calc(100% - 95px);
        background: #f6f6f6;
        padding: 12px 0px;
        position: relative;
        overflow-y: auto;
        .data-list-item {
          cursor: pointer;
          background: #fff;
          padding: 10px;
          border: 2px solid #fff;
          width: calc(100% - 22px);
          border-radius: 12px;
          // border-radius:6px;
          margin: 0px auto;
          margin-bottom: 12px;
          .data-list-layout-div {
            display: flex;
            justify-content: space-between;
            padding-bottom: 8px;
            border-bottom: 1px solid #e5e5e5;
            height: 45px;
            gap: 20px;
            .data-list-checked {
              width: 28px;
              height: 28px;
              margin-top: 8px;
            }
            .data-list-title-div {
              flex: auto;
              display: flex;
              align-items: center;
              .map-mark {
                width: 17px;
                height: 17px;
              }
              .label-div {
                display: flex;
                align-items: baseline;
                margin-right: 12px;
              }
              .item-label {
                font-family: Alibaba PuHuiTi;
                font-weight: 500;
                font-size: 23px;
                color: #000000;
                margin-left: 9px;
                margin-right: 10px;
              }
              .item-sub-label {
                font-family: Alibaba PuHuiTi;
                font-weight: 500;
                font-size: 17px;
                color: #000000;
              }
              .item-mark {
                font-family: Alibaba PuHuiTi;
                font-weight: 500;
                font-size: 13px;
                color: #ffffff;
                background: rgba(0, 0, 0, 0.59);
                padding: 5px 8px;
                border-radius: 14px;
              }
            }
            .data-item-type-div {
              font-family: Alibaba PuHuiTi;
              font-weight: 500;
              font-size: 15px;
              color: #696969;
              display: flex;
              align-items: center;
              cursor: pointer;
              user-select: none;
            }
          }
          .data-list-info-div {
            display: flex;
            justify-content: space-between;
            padding-top: 10px;
            .info-layout-div {
              display: flex;
              align-items: center;
              .info-time {
                font-family: HarmonyOS Sans;
                font-weight: 500;
                font-size: 15px;
                color: #000000;
                margin-right: 5px;
              }
            }
            .info-item {
              display: flex;
              background: rgba(237, 237, 237, 0.55);
              border: 1px dashed orange;
              align-items: center;
              width: 110px;
              border-radius: 7px;
              margin-right: 8px;
              height: 30px;
              justify-content: center;
              .info-label {
                font-family: Alibaba PuHuiTi;
                font-weight: 400;
                font-size: 16px;
                color: #959494;
                // width:45%;
                display: flex;
                justify-content: center;
                padding-right: 5px;
                white-space: nowrap;
              }
              .info-data {
                font-family: HarmonyOS Sans;
                font-weight: 500;
                font-size: 16px;
                color: #000000;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
          }
        }
        .data-list-item:nth-last-child(1) {
          border-bottom-left-radius: 6px;
          border-bottom-right-radius: 6px;
        }
      }
      .split-operation {
        background: #f6f6f6;
        width: calc(100% - 20px);
        padding: 15px 15px;
        text-align: right;
      }
    }
  }
  .detail-container::after {
    content: '';
    display: block;
    clear: both;
    height: 0;
    visibility: none;
  }

  ::v-deep .ant-tabs .ant-tabs-content-holder {
    overflow: auto;
    height: calc(100vh - 700px);
    overflow: auto;
  }
</style>
