<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <PermissionBtn @btnEvent="buttonClick"></PermissionBtn>
      </template>
      <template #bodyCell="{ column, record }">
        <!-- 下发线索·宗数 -->
        <template v-if="column.key.endsWith('zs') && column.key != 'xftbzs'">
          <!-- <a @click="handlePreViewData(column, record, getCaseType(column.dataIndex))"> {{ record[column.dataIndex] }} </a> -->
          {{ record[column.dataIndex] }}
        </template>
        <!-- 下发线索·面积 -->
        <template v-if="column.key.endsWith('mj')">
          {{ record[column.dataIndex] == 0? 0: record[column.dataIndex].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/farmland';
  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';
  import { getCaseType } from './util'

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

  // 页面表格
  const searchParams = ref();
  const [registerTable] = useTable({
    api: getCaseOffence,
    columns: columns,
    title: '非住宅类农村乱占耕地建房存量问题情况统计表',
    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;
      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/DroneCaseInfoLzwjf/ExprotCaseListByType';
        fileName =
          '统计明细线索信息 ' +
          tablist[activeKey.value].countyname +
          '-' +
          tablist[activeKey.value].label +
          ' ' +
          afterTitle +
          '.xls';
        break;
      case 'chuantou_shp':
        // 穿透-导出线索明细shp
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoLzwjf/ExportShapefile';
        fileName =
          '统计明细矢量数据 ' +
          tablist[activeKey.value].countyname +
          '-' +
          tablist[activeKey.value].label +
          ' ' +
          afterTitle +
          '.zip';
        break;
      case 'mingxi_1':
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoLzwjf/CaseOffenceLzgdjfToExcel';
        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':
        handleExport('mingxi_1')
        // 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>
