<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <div class="search-box">
      <BasicForm
        @register="registerForm"
        :labelWidth="100"
        :schemas="searchFormSchema"
        :actionColOptions="{ span: 24 }"
      >
        <template #dangqianzhuangtai>
          <a-select
            allowClear
            showArrow
            mode="multiple"
            v-model:value="nowStatus"
            :options="nowStatusOptions"
            :max-tag-count="1"
            placeholder="请选择"
            @change="changeStatus"
          />
        </template>
        <template #tubanmianji>
          <div class="scope-box">
            <a-input v-model:value="areaParams.tubanArea1" placeholder="请输入" />
            -
            <a-input v-model:value="areaParams.tubanArea2" placeholder="请输入" />
          </div>
        </template>
        <template #gengdimianji>
          <div class="scope-box">
            <a-input v-model:value="areaParams.gengdiArea1" placeholder="请输入" />
            -
            <a-input v-model:value="areaParams.gengdiArea2" placeholder="请输入" />
          </div>
        </template>
        <template #jibennongtianmianji>
          <div class="scope-box">
            <a-input v-model:value="areaParams.jibenArea1" placeholder="请输入" />
            -
            <a-input v-model:value="areaParams.jibenArea2" placeholder="请输入" />
          </div>
        </template>
      </BasicForm>
    </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', '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 { 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, loadCaseInfoTuBanList } from '@/api/keyproblem/keyissuesI/index';
  import { dataProcessingCount } from '@/views/demo/tiankongdi/util';
  import { BasicForm, useForm } from '@/components/Form';
  import { PageWrapper } from '@/components/Page';
  import dayjs from 'dayjs';
  import { nowStatusOptions } from '@/utils/global';

  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 nowStatus = ref(undefined);
  const areaParams = ref({
    tubanArea1: null,
    tubanArea2: null,
    gengdiArea1: null,
    gengdiArea2: null,
    jibenArea1: null,
    jibenArea2: null,
    nowStatus: undefined,
  });
  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: 100,
    baseColProps: { span: 6 },
    actionColOptions: { span: 24 },
    autoSubmitOnEnter: true,
    submitFunc: handleSubmit,
    resetFunc: handleReset,
    autoSubmitOnEnter: 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/DroneCaseInfoZdwt1/ExportCaseInfoTuBanList';
      fileName = '图斑列表统计报表' + new Date().getTime() + '.xls';
    } else if (exportType == 'shp') {
      url = VITE_GLOB_API_URL + '/api/DroneCaseInfoZdwt1/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) {
    console.log(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 changeStatus(val) {
    console.log(val);
    areaParams.value.nowStatus = val.join(',');
  }
  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) {
    if (querys.startTime && querys.endTime) {
      querys.startTime = dayjs(querys.startTime).format('YYYY-MM-DD');
      querys.endTime = dayjs(querys.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
    }
    setLoading(true);
    loadCaseInfoTuBanList(querys).then((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: 10,
    };
    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%;
    }
  }
  ::v-deep .ant-select-selection-overflow-item:first-child .ant-select-selection-item {
    width: 80px;
  }
</style>
