<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <div class="table-box">
      <BasicTable @register="registerTable" :searchInfo="searchInfo" @change="handleChange">
        <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="[
                {
                  // icon: 'ant-design:ellipsis-outlined',
                  label: '查看',
                  onClick: viewAccount.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </div>
    <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">
        <ShowInfoModal :showInfoData="showInfoData" />
      </div>
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getLoadMineralsLedger } from '@/api/minerals/index';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { columns } from './miningstatistics.data';
  import { getAppEnvConfig } from '@/utils/env';
  import axios from 'axios';
  import ShowInfoModal from '@/views/demo/tiankongdi/curbspotcity/MapList/ShowInfoModal/index.vue';
  import { GetCaseInfoById } from '@/api/illegalmining/index';
  import { dataProcessingCount } from '@/views/demo/tiankongdi/util';
  import { BasicForm, useForm } from '@/components/Form';
  import { PageWrapper } from '@/components/Page';

  const { VITE_GLOB_API_URL } = getAppEnvConfig();

  defineOptions({ name: 'RoleManagement' });

  const searchInfo = reactive<Recordable>({
    countyid: null,
  });
  const showInfoData = ref();
  const showInfoOpen = ref(false);
  const searchParams = ref({
    page: 1,
    limit: 15,
  });
  const areaParams = ref({
    tubanArea1: null,
    tubanArea2: null,
    gengdiArea1: null,
    gengdiArea2: null,
    jibenArea1: null,
    jibenArea2: null,
  });
  const tableData = ref([]);
  const tablePaginationRight = ref({
    current: 1,
    pageSize: 15,
    size: 'small',
    defaultPageSize: 15,
    showSizeChanger: true,
    pageSizeOptions: ['15', '50', '80', '100'],
    showQuickJumper: true,
    total: 0,
  });
  const [registerTable, { setTableData, reload, clearSelectedRowKeys, setPagination, setLoading }] =
    useTable({
      title: '统计报表-开采台账',
      dataSource: tableData.value,
      columns,
      rowKey: 'id',
      useSearchForm: false,
      showTableSetting: true,
      bordered: true,
      // 搜索
      handleSearchInfoFn(info) {
        searchParams.value = info;
        return info;
      },
      pagination: tablePaginationRight.value,
    });

  // 直接下载接口返回的二进制流
  function handleExport(exportType) {
    console.log(searchParams);
    let params = { ...searchParams.value };
    params.limit = 9999;
    let url = '';
    let fileName = '';
    if (exportType == 'excel') {
      url = VITE_GLOB_API_URL + '/api/DroneCaseInfoMinerals/ExprotMineralsLedger';
      fileName = '图斑汇总统计报表' + new Date().getTime() + '.xls';
    } else if (exportType == 'shp') {
      url = VITE_GLOB_API_URL + '/api/DroneCaseInfoSatellite/ExportCaseInfoWpxfShapefile';
      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 'btnExport':
        // open.value = true;
        handleExport('excel');
        break;
      default:
        break;
    }
  }
  function viewAccount(record) {
    GetCaseInfoById({ id: record.Id }).then((res) => {
      showInfoData.value = res;
      showInfoOpen.value = true;
    });
  }
  function handleChange(data) {
    searchParams.value.page = data.current;
    searchParams.value.limit = data.pageSize;
    tablePaginationRight.value = data;
    const querys = Object.assign(searchParams.value, areaParams.value);
    getTableData(querys);
  }
  function handleSubmit() {
    searchParams.value = getFieldsValue();
    searchParams.value.page = 1;
    tablePaginationRight.value.current = 1;
    searchParams.value.limit = tablePaginationRight.value.pageSize;
    const querys = Object.assign(searchParams.value, areaParams.value);
    getTableData(querys);
  }
  function getTableData(querys) {
    setLoading(true);
    getLoadMineralsLedger(querys).then((res) => {
      console.log(res);
      tableData.value = res.items;
      tablePaginationRight.value.total = res.total;
      setTableData(tableData.value);
      setPagination(tablePaginationRight.value);
      setLoading(false);
    });
  }
  function handleReset() {
    searchParams.value = {
      page: 1,
      limit: 15,
    };
    areaParams.value = {
      tubanArea1: null,
      tubanArea2: null,
      gengdiArea1: null,
      gengdiArea2: null,
      jibenArea1: null,
      jibenArea2: null,
    };
    tablePaginationRight.value.current = 1;
    getTableData(searchParams.value);
  }
  onMounted(() => {
    getTableData(searchParams.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%;
    }
  }
</style>
