<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <PermissionBtn @btnEvent="buttonClick"></PermissionBtn>
      </template>
      <template #bodyCell="{ column, record }">
        <!-- 县区 -->
        <!-- <template v-if="column.key === 'countyname'">
          <a @click="getOrgCaseList(column, record)">
            {{ record.countyname }}
          </a>
        </template> -->

        <!-- 下发图斑·宗数 -->
        <template v-if="column.key === 'xftbzs'">
          <a @click="handlePreViewData(column, record, 1)"> {{ record.xftbzs }} </a>
        </template>
        <!-- 下发图斑·面积 -->
        <template v-if="column.key === 'xfmj'">
          <!-- <a @click="handlePreViewData(column, record, 1)"> -->
          {{ record.xfmj == 0 ? 0 : record.xfmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 下发图斑·耕地面积 -->
        <template v-if="column.key === 'xfgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 1)"> -->
          {{ record.xfgdmj == 0 ? 0 : record.xfgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>

        <!-- 合法·宗数 -->
        <template v-if="column.key === 'hfzs'">
          <a @click="handlePreViewData(column, record, 2)"> {{ record.hfzs }} </a>
        </template>
        <!-- 合法·面积 -->
        <template v-if="column.key === 'hfmj'">
          <!-- <a @click="handlePreViewData(column, record, 2)"> -->
          {{ record.hfmj == 0 ? 0 : record.hfmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 合法·耕地面积 -->
        <template v-if="column.key === 'hfgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 2)"> -->
          {{ record.hfgdmj == 0 ? 0 : record.hfgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>

        <!-- 违法·小计·宗数 -->
        <template v-if="column.key === 'wfzs'">
          <a @click="handlePreViewData(column, record, 3)"> {{ record.wfzs }} </a>
        </template>
        <!-- 违法·小计·面积 -->
        <template v-if="column.key === 'wfmj'">
          <!-- <a @click="handlePreViewData(column, record, 3)"> -->
          {{ record.wfmj == 0 ? 0 : record.wfmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 违法·小计·耕地面积 -->
        <template v-if="column.key === 'wfgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 3)"> -->
          {{ record.wfgdmj == 0 ? 0 : record.wfgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>

        <!-- 违法·非农化·宗数 -->
        <template v-if="column.key === 'fnhzs'">
          <a @click="handlePreViewData(column, record, 10)"> {{ record.fnhzs }} </a>
        </template>
        <!-- 违法·非农化·面积 -->
        <template v-if="column.key === 'fnhmj'">
          <!-- <a @click="handlePreViewData(column, record, 10)"> -->
          {{ record.fnhmj == 0 ? 0 : record.fnhmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 违法·非农化·耕地面积 -->
        <template v-if="column.key === 'fnhgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 10)"> -->
          {{ record.fnhgdmj == 0 ? 0 : record.fnhgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>

        <!-- 违法·非粮化·宗数 -->
        <template v-if="column.key === 'flhzs'">
          <a @click="handlePreViewData(column, record, 5)"> {{ record.flhzs }} </a>
        </template>
        <!-- 违法·非粮化·面积 -->
        <template v-if="column.key === 'flhmj'">
          <!-- <a @click="handlePreViewData(column, record, 5)"> -->
          {{ record.flhmj == 0 ? 0 : record.flhmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 违法·非粮化·耕地面积 -->
        <template v-if="column.key === 'flhgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 5)"> -->
          {{ record.flhgdmj == 0 ? 0 : record.flhgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>

        <!-- 其他·宗数 -->
        <template v-if="column.key === 'qtzs'">
          <a @click="handlePreViewData(column, record, 4)"> {{ record.qtzs }} </a>
        </template>
        <!-- 其他·面积 -->
        <template v-if="column.key === 'qtmj'">
          <!-- <a @click="handlePreViewData(column, record, 4)"> -->
          {{ record.qtmj == 0 ? 0 : record.qtmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 其他·耕地面积 -->
        <template v-if="column.key === 'qtgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 4)"> -->
          {{ record.qtgdmj == 0 ? 0 : record.qtgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>

        <!-- 整改情况·补办手续·宗数 -->
        <template v-if="column.key === 'bbsxzs'">
          <a @click="handlePreViewData(column, record, 6)"> {{ record.bbsxzs }} </a>
        </template>
        <!-- 整改情况·补办手续·面积 -->
        <template v-if="column.key === 'bbsxmj'">
          <!-- <a @click="handlePreViewData(column, record, 6)"> -->
          {{ record.bbsxmj == 0 ? 0 : record.bbsxmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 整改情况·补办手续·耕地面积 -->
        <template v-if="column.key === 'bbsxgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 6)"> -->
          {{ record.bbsxgdmj == 0 ? 0 : record.bbsxgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 整改情况·拆除复耕·宗数 -->
        <template v-if="column.key === 'cczs'">
          <a @click="handlePreViewData(column, record, 7)"> {{ record.cczs }} </a>
        </template>
        <!-- 整改情况·拆除复耕·面积 -->
        <template v-if="column.key === 'ccmj'">
          <!-- <a @click="handlePreViewData(column, record, 7)"> -->
          {{ record.ccmj == 0 ? 0 : record.ccmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 整改情况·拆除复耕·耕地面积 -->
        <template v-if="column.key === 'ccgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 7)"> -->
          {{ record.ccgdmj == 0 ? 0 : record.ccgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>

        <!-- 新增违法占用耕地情况·核实后新增违法耕地·宗数 -->
        <template v-if="column.key === 'hshxzwfgdzs'">
          <a @click="handlePreViewData(column, record, 8)"> {{ record.hshxzwfgdzs }} </a>
        </template>
        <!-- 新增违法占用耕地情况·核实后新增违法耕地·耕地面积 -->
        <template v-if="column.key === 'hshxzwfgdgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 8)"> -->
          {{ record.hshxzwfgdgdmj == 0 ? 0 : record.hshxzwfgdgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 新增违法占用耕地情况·整改后剩余违法耕地·宗数 -->
        <template v-if="column.key === 'zghsywfgdzs'">
          <a @click="handlePreViewData(column, record, 9)"> {{ record.zghsywfgdzs }} </a>
        </template>
        <!-- 新增违法占用耕地情况·整改后剩余违法耕地·耕地面积 -->
        <template v-if="column.key === 'zghsywfgdgdmj'">
          <!-- <a @click="handlePreViewData(column, record, 9)"> -->
          {{ record.zghsywfgdgdmj == 0 ? 0 : record.zghsywfgdgdmj.toFixed(2) }}
          <!-- </a> -->
        </template>
        <!-- 面积只取小数点后两位 -->
        <!-- <template v-if="column.key.slice(-2) === 'mj' && record.countyname == '总计'">
          {{ record[column.key].toFixed(2) }}
        </template> -->
      </template>
    </BasicTable>

    <a-modal v-model:open="open_mingxi" title="导出表格种类" :footer="null">
      <div>
        <a-button class="exportbutton" @click="handleExport('mingxi_1')">
          无人机全域巡查图斑情况统计表
        </a-button>
        <a-button class="exportbutton" @click="handleExport('mingxi_2')">
          土地卫片新增违法占用耕地情况统计表
        </a-button>
        <a-button class="exportbutton" @click="handleExport('mingxi_3')">
          无人机全域巡查违法用地情况统计表
        </a-button>
      </div>
    </a-modal>
    <a-modal v-model:open="open_chuantou" title="导出文件类型" :footer="null">
      <div>
        <a-button class="exportbutton" @click="handleExport('chuantou_execl')">
          统计明细图斑信息（execl）
        </a-button>
        <a-button class="exportbutton" @click="handleExport('chuantou_shp')">
          统计明细矢量数据（shp）
        </a-button>
      </div>
    </a-modal>
    <a-modal
      v-model:open="showRecordList"
      width="1710px"
      :closable="false"
      :footer="null"
      @ok="handleOk"
    >
      <div>
        <CloseOutlined id="closeIconButton" @click="handleCloseAllRecordList" />
        <MinusOutlined id="closeIconButton" @click="handleCloseRecordList" />
        <CloudDownloadOutlined id="closeIconButton" @click="exportList" />
      </div>
      <template #footer>
        <a-button type="primary" @click="exportList">
          <template #icon>
            <CloudDownloadOutlined />
          </template>
          导出
        </a-button>
      </template>
      <a-tabs
        v-model:activeKey="activeKey"
        hide-add
        type="editable-card"
        @edit="onEdit"
        @change="handleTabChange"
      >
        <a-tab-pane
          v-for="(pane, index) in tablist"
          :key="index.toString()"
          :tab="pane.countyname + '-' + pane.label"
          :closable="pane.closable"
        />
      </a-tabs>
      <RecordList :tablist="tablist" :currentListQuery="currentListQuery.listQuery" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, watch, createVNode, unref } from 'vue';
  import { useModal } from '@/components/Modal';
  import { BasicTable, useTable } from '@/components/Table';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { PageWrapper } from '@/components/Page';
  import { cloneDeep } from 'lodash-es';
  import { getCaseOffence } from '@/api/inspectionaudit';
  import { columns, searchFormSchema } from './index.data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { RecordList } from './page';
  import { MinusOutlined, CloseOutlined, CloudDownloadOutlined } from '@ant-design/icons-vue';
  import { getAppEnvConfig } from '@/utils/env';
  import axios from 'axios';
  import dayjs from 'dayjs';

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

  // 页面表格
  const searchParams = ref();
  const [registerTable] = useTable({
    api: getCaseOffence,
    columns: columns,
    // title: '无人机全域巡查图斑情况统计表',
    // titleHelpMessage: '合法、其他、非粮化、补办手续、拆除复耕均需市级审核通过才可判定为举证类型。',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    showIndexColumn: false,
    striped: false,
    bordered: true,
    canResize: false,
    useSearchForm: true,
    showTableSetting: true,
    pagination: false,
    beforeFetch: (data) => {
      // 接口请求前 参数处理
      // 默认展示昨天的
      var temp = {
        startTime: data.startTime
          ? dayjs(data.startTime).startOf('day').format('YYYY-MM-DD')
          : dayjs().startOf('day').add(-1, 'day').format('YYYY-MM-DD'),
        endTime: data.endTime
          ? dayjs(data.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss')
          : dayjs().endOf('day').add(-1, 'day').format('YYYY-MM-DD HH:mm:ss'),
        tubanlaiyuan: data.tubanlaiyuan && data.tubanlaiyuan.join(','),
      };
      searchParams.value = temp;
      return temp;
    },
    afterFetch: (res) => {},
  });

  const showRecordList = ref<boolean>(false);

  // 标签页面数据
  let activeKey = ref('0');
  const tablist = reactive<
    { countyname: string; label: string; listQuery: searchListSchema; closable?: boolean }[]
  >([]);
  let currentListQuery = reactive({ listQuery: {} });
  // 查询条件
  interface searchListSchema {
    AreaId?: string;
    CaseType?: number;
    startTime?: string;
    endTime?: string;
    page?: number;
    limit?: number;
    tubanlaiyuan?: string;
  }
  // 打开标签页面
  function handlePreViewData(column, record: Recordable, CaseType: number) {
    const searchForm = reactive<searchListSchema>({
      AreaId: record.countyid,
      CaseType: CaseType,
      startTime: dayjs(searchParams.value?.startTime).startOf('day').format('YYYY-MM-DD'),
      endTime: dayjs(searchParams.value?.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      tubanlaiyuan: searchParams.value?.tubanlaiyuan,
      page: 1,
      limit: 10,
    });
    // 标签页面信息
    let tabItem: any = {
      countyname: record.countyname,
      label: '',
      listQuery: searchForm,
    };
    switch (CaseType) {
      case 1:
        tabItem.label = '下发图斑';
        break;
      case 2:
        tabItem.label = '合法';
        break;
      case 3:
        tabItem.label = '违法·小计';
        break;
      case 4:
        tabItem.label = '其他';
        break;
      case 5:
        tabItem.label = '违法·非粮化';
        break;
      case 6:
        tabItem.label = '整改情况·补办手续';
        break;
      case 7:
        tabItem.label = '整改情况·拆除复耕';
        break;
      case 8:
        tabItem.label = '核实后新增违法耕地';
        break;
      case 9:
        tabItem.label = '整改后剩余违法耕地';
        break;
      case 10:
        tabItem.label = '违法·非农化';
        break;
      default:
        break;
    }
    tablist.push(tabItem);
    // 当前标签页面
    activeKey.value = tablist.length > 1 ? (tablist.length - 1).toString() : '0';
    // 打开标签页面
    showRecordList.value = true;
    // 标签页面的搜索条件
    currentListQuery.listQuery = searchForm;
  }
  // 编辑标签页
  function onEdit(targetKey: string) {
    tablist.splice(parseInt(targetKey), 1);
    if (tablist.length == 0) {
      showRecordList.value = false;
    }
    if (parseInt(targetKey) > 1) {
      activeKey.value = (parseInt(targetKey) - 1).toString();
    } else {
      activeKey.value = '0';
    }
    currentListQuery.listQuery = tablist[activeKey.value].listQuery;
  }
  // 修改标签页
  function handleTabChange(e) {
    currentListQuery.listQuery = tablist[e].listQuery;
  }
  // 穿透显示的明细表缩小
  function handleCloseRecordList() {
    showRecordList.value = false;
  }
  // 穿透显示的明细表关闭
  function handleCloseAllRecordList() {
    for (let i = 0; i < tablist.length; i++) {
      tablist.pop();
    }
    showRecordList.value = false;
  }
  // 穿透显示的明细表导出
  function exportList() {
    open_chuantou.value = true;
  }

  // 导出种类
  const open_mingxi = ref<boolean>(false);
  const open_chuantou = ref<boolean>(false);

  // 直接下载接口返回的二进制流
  function handleExport(exportType) {
    let url = '';
    let fileName = '';
    let params: any = {};
    let afterTitle = '';
    if (
      dayjs(searchParams.value?.startTime).startOf('day').format('YYYY-MM-DD') ===
      dayjs(searchParams.value?.endTime).endOf('day').format('YYYY-MM-DD')
    ) {
      afterTitle = dayjs(searchParams.value?.startTime).startOf('day').format('YYYY-MM-DD');
    } else {
      afterTitle =
        dayjs(searchParams.value?.startTime).startOf('day').format('YYYY-MM-DD') +
        '至' +
        dayjs(searchParams.value?.endTime).endOf('day').format('YYYY-MM-DD');
    }
    switch (exportType) {
      case 'chuantou_execl':
        // 穿透-导出图斑明细execl
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoXcsj/ExprotCaseListByType';
        fileName =
          '统计明细图斑信息 ' +
          tablist[activeKey.value].countyname +
          '-' +
          tablist[activeKey.value].label +
          ' ' +
          afterTitle +
          '.xls';
        break;
      case 'chuantou_shp':
        // 穿透-导出图斑明细shp
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoXcsj/ExportShapefile';
        fileName =
          '统计明细矢量数据 ' +
          tablist[activeKey.value].countyname +
          '-' +
          tablist[activeKey.value].label +
          ' ' +
          afterTitle +
          '.zip';
        break;
      case 'mingxi_1':
        // 无人机全域巡查图斑情况统计表
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoXcsj/CaseOffenceToExcel';
        fileName = '无人机全域巡查图斑情况统计表 ' + afterTitle + '.xls';
        break;
      case 'mingxi_2':
        // 土地卫片新增违法占用耕地情况统计表
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoXcsj/CaseOffenceSimpleToExcel';
        fileName = '土地卫片新增违法占用耕地情况统计表 ' + afterTitle + '.xls';
        break;
      case 'mingxi_3':
        // 无人机全域巡查违法用地情况统计表
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoSingle/CaseOffenceSimpleToExcel2';
        fileName = '无人机全域巡查违法用地情况统计表 ' + afterTitle + '.xls';
        break;
      default:
        break;
    }

    if (['chuantou_execl', 'chuantou_shp'].includes(exportType)) {
      params = currentListQuery.listQuery;
      delete params.limit;
      delete params.page;
    }
    if (['mingxi_1', 'mingxi_2', 'mingxi_3'].includes(exportType)) {
      params = {
        startTime: dayjs(searchParams.value?.startTime).startOf('day').format('YYYY-MM-DD'),
        endTime: dayjs(searchParams.value?.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
        tubanlaiyuan: searchParams.value?.tubanlaiyuan
      };
    }

    axios({
      method: 'post',
      url: url,
      params: params,
      headers: {
        'X-Token': localStorage.getItem('X-Token'),
      },
      responseType: 'blob',
    }).then((res) => {
      const elink = document.createElement('a');
      elink.download = fileName;
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(res.data);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);
      document.body.removeChild(elink);
    });
  }
  // 按键分类
  const buttonClick = async (type) => {
    switch (type) {
      case 'btnExport':
        open_mingxi.value = true;
        break;
      default:
        break;
    }
  };
</script>
<style lang="less" scoped>
  #closeIconButton {
    width: 40px;
    height: 50px;
    line-height: 50px;
    float: right;
    text-align: center;
    cursor: pointer;
  }

  .exportbutton {
    width: 510px;
    height: 60px;
    margin: 5px;
  }

  ::v-deep .ant-table-container table {
    line-height: 1.1 !important;

    .ant-table-row {
      td {
        padding-top: 8px !important;
        padding-bottom: 8px !important;
      }
    }
  }
</style>
