<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <PermissionBtn @btn-event="onBtnClicked" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="['area', 'gengdiarea', 'nongyongdiarea'].includes(column.key)">
          {{ dataProcessingCount(record[column.key]) }}
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '查看',
                onClick: viewAccount.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <a-modal v-model:open="open" title="导出文件类型" :footer="null">
      <div>
        <a-button class="exportbutton" @click="handleExport('excel')">
          标签列表统计报表（execl）
        </a-button>
        <a-button class="exportbutton" @click="handleExport('shp')">
          标签列表矢量数据（shp）
        </a-button>
      </div>
    </a-modal>
    <a-modal
      style="width: 100vw; top: 0px; left: 0px; margin: 0px; padding: 0px"
      wrap-class-name="full-modal"
      v-model:open="showInfoOpen"
      title="详情"
      :footer="null"
      :maskClosable="true"
      :destroyOnClose="true"
      @cancel="showInfoOpen = false"
    >
      <div class="modal-content">
        <div class="handoff">
          <a-button type="primary" style="margin-right: 25px" @click="prevData">上一条</a-button>
          <a-button type="primary" @click="nextData">下一条</a-button>
        </div>
        <ShowInfoModal :showInfoData="showInfoData" />
      </div>
    </a-modal>
    <a-modal
      style="width: 50vw; margin: 0px; padding: 0px"
      wrap-class-name="full-modal"
      :centered="true"
      :mask="false"
      :maskClosable="false"
      :keyboard="false"
      v-model:open="uploadOpen"
      title="上传图片"
      :footer="null"
      @cancel="uploadOpen = false"
    >
      <UploadModal :allTableData="allTableData" />
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { LoadNewCaseInfoMineralsTuBanImportantList, MineralsNewGetCaseInfoById } from '@/api/illegalmining/index';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { columns, searchFormSchema } from './util';
  import { getAppEnvConfig } from '@/utils/env';
  import axios from 'axios';
  import ShowInfoModal from '@/components/illegalminingnew/ShowInfoModal/index.vue';
  import { GetCaseInfoById } from '@/api/illegalmining/index';
  import { dataProcessingCount } from '@/views/demo/tiankongdi/util';
  import { PageWrapper } from '@/components/Page';
  import { message } from 'ant-design-vue';
  import UploadModal from './uploadModal.vue';

  const { VITE_GLOB_API_URL } = getAppEnvConfig();

  defineOptions({ name: 'RoleManagement' });
  const nextShowDataId = ref();
  const prevShowDataId = ref();
  const showInfoId = ref();
  const showInfoData = ref();
  const showInfoOpen = ref(false);
  const tableData = ref([]);
  const searchParams = ref({
    page: 1,
    limit: 10,
  })
  const uploadOpen = ref(false);
  const [registerTable, { getForm, reload, getPaginationRef, getDataSource  }] =
    useTable({
      title: '标签列表',
      api: LoadNewCaseInfoMineralsTuBanImportantList,
      columns,
      rowKey: 'id',
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      actionColumn: {
        width: 80,
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
      },
      beforeFetch(params){
        let data = {...params}
        if(params.tubanlaiyuan){
          data.tubanlaiyuan = params.tubanlaiyuan.join(',')
        }
        return data
      },
      handleSearchInfoFn(info) {
        return info;
      },
    });

  // 直接下载接口返回的二进制流
  function handleExport(exportType) {
    const form = getForm();
    const params = form.getFieldsValue();
    if(params.tubanlaiyuan){
      params.tubanlaiyuan = params.tubanlaiyuan.join(',')
    }
    console.log('params',params)
    let url = '';
    let fileName = '';
    if (exportType == 'excel') {
      url = VITE_GLOB_API_URL + '/api/DroneCaseInfoSatellite/ExportCaseInfoWpxfTuBanList';
      fileName = '标签列表统计报表' + new Date().getTime() + '.xls';
    } else if (exportType == 'shp') {
      url = VITE_GLOB_API_URL + '/api/DroneCaseinfoMineralsNew/ExportNewIllegalCaiKuangShapefile';
      fileName = '标签列表矢量数据' + new Date().getTime() + '.zip';
    }
    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 open = ref<boolean>(false);
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnUpload':
        uploadOpen.value = true;
        break;
      case 'btnExport':
        // open.value = true;
        handleExport('shp')
        break;
      default:
        break;
    }
  }
  function viewAccount(record) {
    showInfoId.value = record.Id;
    getDetailData();
  }
  function getDetailData() {
    MineralsNewGetCaseInfoById({ id: showInfoId.value }).then((res) => {
      showInfoData.value = res;
      showInfoOpen.value = true;
    });
  }
  watch(
    () => showInfoId.value,
    () => {
      const data = getDataSource();
      let index = data.findIndex((item) => item.Id == showInfoId.value);
      getDetailData();
      if (index < data.length - 1) {
        nextShowDataId.value = data[index + 1].Id;
      } else {
        nextShowDataId.value = 0;
      }
      if (index > 0) {
        prevShowDataId.value = data[index - 1].Id;
      } else {
        prevShowDataId.value = 0;
      }
    },
  );
  async function prevData() {
    const pagination = getPaginationRef();
    console.log('pagination',pagination)
    console.log(pagination.current)
    if (prevShowDataId.value === 0) {
      if (pagination.current === 1) {
        message.warning('已经是第一条数据了');
        return;
      }
      pagination.current--;
      await reload();
      setTimeout(() => {
        const data = getDataSource();
        showInfoId.value = data[data.length - 1].Id;
      }, 10);
      return;
    } else {
      showInfoId.value = prevShowDataId.value;
    }
  }
  async function nextData() {
    const pagination = getPaginationRef();
    if (nextShowDataId.value === 0) {
      if (
        Math.ceil(pagination.total / pagination.defaultPageSize) <=
        pagination.current
      ) {
        message.warning('已经是最后一条数据了');
        return;
      }
      pagination.current++;
      await reload();
      setTimeout(() => {
        const data = getDataSource();
        showInfoId.value = data[0].Id;
      }, 10);
    } else {
      showInfoId.value = nextShowDataId.value;
    }
  }
</script>
<style lang="less" scoped>
  .data-preview-container {
    width: 100%;
    height: calc(100% - 0px);
    position: absolute;
    padding: 30px 10px;
    top: 0px;
    left: 0px;
    background: #fff;
  }
  .data-preview-container-option {
    width: 120px;
    height: 40px;
    position: absolute;
    top: 30px;
    right: 0px;
  }
  .data-preview-container-option div {
    width: 40px;
    height: 40px;
    line-height: 40px;
    float: left;
    text-align: center;
    cursor: pointer;
  }
  .full-modal {
    .ant-modal {
      min-width: 100vw;
      top: 0px;
      padding: 0px;
      margin: 0px;
    }
    .ant-modal-content {
      display: flex;
      flex-direction: column;
    }
    .ant-modal-body {
      flex: 1;
    }
  }
  .exportbutton {
    width: 510px;
    height: 60px;
    margin: 5px;
  }
  .search-box {
    background: @component-background;
    margin: 16px;
    padding: 16px;
  }
  ::v-deep .ant-col-24 {
    display: inline-block;
    max-width: fit-content;
    margin-left: 20px;
  }
  .table-box {
    margin: 16px;
  }
  .scope-box {
    display: flex;
    width: 100%;
    .ant-input {
      width: 48% !important;
      max-width: 48%;
      min-width: 48%;
    }
  }
  .select-dropdown {
    display: flex;
  }
  ::v-deep .ant-select-selection-overflow-item:first-child .ant-select-selection-item {
    width: 80px;
  }
  .handoff {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-right: 25px;
  }
</style>
