<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <div class="search-box">
      <BasicForm
        @register="registerForm"
        :labelWidth="100"
        :schemas="searchFormSchema"
        :actionColOptions="{ span: 24 }"
      />
    </div>
    <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'].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 { loadCaseInfoTuBanList } from '@/api/demo/system';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { columns, searchFormSchema } from './patchsummary.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/tiankongdi/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: 10,
  });
  const tableData = ref([]);
  const tablePaginationRight = ref({
    current: 1,
    pageSize: 10,
    size: 'small',
    defaultPageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '80', '100'],
    showQuickJumper: true,
    total: 0,
  });
  const [registerForm, { validate, getFieldsValue }] = useForm({
    schemas: searchFormSchema,
    labelWidth: 80,
    baseColProps: { span: 6 },
    actionColOptions: { span: 24 },
    autoSubmitOnEnter: true,
    submitFunc: handleSubmit,
  });
  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;
      },
      actionColumn: {
        width: 80,
        title: '操作',
        dataIndex: 'action',
        // slots: { customRender: 'action' },
        fixed: 'right',
      },
      pagination: tablePaginationRight.value,
    });

  // 直接下载接口返回的二进制流
  function handleExport(exportType) {
    console.log(searchParams);
    let params = { ...searchParams.value };
    let url = '';
    let fileName = '';
    if (exportType == 'excel') {
      url = VITE_GLOB_API_URL + '/api/DroneCaseInfoSingle/ExportCaseInfoTuBanList';
      fileName = '图斑汇总统计报表' + new Date().getTime() + '.xls';
    } else if (exportType == 'shp') {
      url = VITE_GLOB_API_URL + '/api/DroneCaseInfoSingle/ExportCaseInfoShapefile';
      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;
        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;
    getTableData();
  }
  function handleSubmit() {
    searchParams.value = getFieldsValue();
    searchParams.value.page = 1;
    tablePaginationRight.value.current = 1;
    searchParams.value.limit = tablePaginationRight.value.pageSize;
    getTableData();
  }
  function getTableData() {
    setLoading(true);
    loadCaseInfoTuBanList(searchParams.value).then((res) => {
      tableData.value = res.items;
      tablePaginationRight.value.total = res.total;
      setTableData(tableData.value);
      setPagination(tablePaginationRight.value);
      setLoading(false);
    });
  }
  onMounted(() => {
    getTableData();
  });
</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;
  }
</style>
