<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <div class="search-box">
      <BasicForm
        @register="registerForm"
        :labelWidth="100"
        :schemas="searchFormSchema"
        :actionColOptions="{ span: 24 }"
      >
        <template #advanceBefore>
          <PermissionBtn @btn-event="onBtnClicked" />
        </template>
      </BasicForm>
      <div class="table-box">
        <a-table
          :columns="columns"
          :data-source="data"
          bordered
          :pagination="false"
          :scroll="{ x: 1500, y: 680 }"
        >
          <template #name="{ text }">
            <a>{{ text }}</a>
          </template>
        </a-table>
      </div>
    </div>
    <a-modal v-model:open="open_chuantou" title="导出文件" :footer="null">
      <div>
        <a-button
          class="exportbutton"
          @click="handleExport('jiexifenxi_execl', '解析分析数据交付与费用记账表')"
        >
          解析分析数据交付与费用记账表（execl）
        </a-button>
        <a-button
          class="exportbutton"
          @click="
            handleExport('weixingyaoganyingxiang_shp', '卫星遥感影像补充数据交付与费用记录表')
          "
        >
          卫星遥感影像补充数据交付与费用记录表（execl）
        </a-button>
        <a-button
          class="exportbutton"
          @click="handleExport('wurenjixunfei_shp', '无人机巡飞数据交付与费用记录表')"
        >
          无人机巡飞数据交付与费用记录表（execl）
        </a-button>
      </div>
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { searchFormSchema } from './data';
  import { getAiShpDataExpenseAccountingTable } from '@/api/demo/statistics';
  import dayjs from 'dayjs';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { BasicForm, useForm } from '@/components/Form';
  import { PageWrapper } from '@/components/Page';
  import { ColumnProps } from 'ant-design-vue/es/table/interface';
  import axios from 'axios';
  import { getAppEnvConfig } from '@/utils/env';
  import { getCurMonthFirstOrLast } from '@/utils/global';

  const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const open_chuantou = ref<boolean>(false);
  const searchParams = ref({
    beginTime: getCurMonthFirstOrLast(0),
    endTime: getCurMonthFirstOrLast(),
  });
  const columns: ColumnProps[] = [
    {
      title: '序号',
      dataIndex: 'index',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          record.index = '合计：';
          obj.props.colSpan = 2;
        } else {
          record.index = index + 1;
        }
        return obj;
      },
    },
    {
      title: '日期',
      dataIndex: 'shapDate',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          obj.props.colSpan = 0;
        }
        return obj;
      },
    },
    {
      title: '影像生产',
      dataIndex: 'shpProduction',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          record.shpProduction = record.totalShpProduction;
        } else {
          record.index = record.shpProduction;
        }
        return obj;
      },
    },
    {
      title: '影像翻译',
      dataIndex: 'shpInterpretation',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          record.shpInterpretation = record.totalShpInterpretation;
        } else {
          record.index = record.shpInterpretation;
        }
        return obj;
      },
    },
    {
      title: '研判分析',
      dataIndex: 'judgment',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          record.judgment = record.totalJudgment;
        } else {
          record.index = record.judgment;
        }
        return obj;
      },
    },
    {
      title: '图斑推送',
      dataIndex: 'push',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          record.push = record.totalPush;
        } else {
          record.index = record.push;
        }
        return obj;
      },
    },
    {
      title: '初始提取个数',
      dataIndex: 'cost',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          record.cost = record.totalCost;
        } else {
          record.index = record.cost;
        }
        return obj;
      },
    },
    {
      title: '最终下发个数',
      dataIndex: 'issuedCount',
      customRender: ({ text, record, index }) => {
        const obj = {
          children: text,
          props: {} as any,
        };
        if (record.title == '合计') {
          record.issuedCount = record.totalIssuedCount;
        } else {
          record.index = record.issuedCount;
        }
        return obj;
      },
    },
    {
      title: '文件夹名称',
      dataIndex: 'folderPath',
    },
    {
      title: '格式',
      dataIndex: 'format',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
  ];
  const data = ref([]);
  const [registerForm, { validate, getFieldsValue }] = useForm({
    schemas: searchFormSchema,
    labelWidth: 100,
    baseColProps: { span: 6 },
    actionColOptions: { span: 24 },
    autoSubmitOnEnter: true,
    submitFunc: handleSubmit,
    resetFunc: handleReset,
    autoSubmitOnEnter: handleSubmit,
  });
  async function getTableData(querys) {
    if (querys.beginTime && querys.endTime) {
      querys.beginTime = dayjs(querys.beginTime).format('YYYY-MM-DD');
      querys.endTime = dayjs(querys.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
    }
    await getAiShpDataExpenseAccountingTable(querys).then((res) => {
      console.log(res);
      var list = res.respData;
      list.forEach((item, index) => {
        item.index = index + 1;
      });
      list.push({
        title: '合计',
        totalCost: res.totalCost,
        totalIssuedCount: res.totalIssuedCount,
        totalJudgment: res.totalJudgment,
        totalPush: res.totalPush,
        totalShpArea: res.totalShpArea,
        totalShpCount: res.totalShpCount,
        totalShpInterpretation: res.totalShpInterpretation,
        totalShpProduction: res.totalShpProduction,
      });
      data.value = list;
    });
  }
  function handleSubmit() {
    searchParams.value = getFieldsValue();
    getTableData(searchParams.value);
  }
  function handleReset() {
    getTableData(searchParams.value);
  }
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnExport':
        open_chuantou.value = true;
        break;
      default:
        break;
    }
  }
  onMounted(() => {
    getTableData(searchParams.value);
  });
  // 直接下载接口返回的二进制流
  function handleExport(exportType, name) {
    let url = '';
    let fileName = '';
    let params: any = {};
    let afterTitle: any = '';
    console.log(searchParams.value);
    if (searchParams.value?.beginTime && searchParams.value?.endTime) {
      params.startTime = dayjs(searchParams.value.beginTime).format('YYYY-MM-DD');
      params.endTime = dayjs(searchParams.value.endTime).endOf('day').format('YYYY-MM-DD');
      if (
        dayjs(searchParams.value?.beginTime).startOf('day').format('YYYY-MM-DD') ===
        dayjs(searchParams.value?.endTime).endOf('day').format('YYYY-MM-DD')
      ) {
        afterTitle = dayjs(searchParams.value?.beginTime).startOf('day').format('YYYY-MM-DD');
      } else {
        afterTitle =
          dayjs(searchParams.value?.beginTime).startOf('day').format('YYYY-MM-DD') +
          '至' +
          dayjs(searchParams.value?.endTime).endOf('day').format('YYYY-MM-DD');
      }
    } else {
      afterTitle = new Date().getTime();
    }

    fileName = name + afterTitle + '.xls';
    switch (exportType) {
      case 'jiexifenxi_execl':
        url = VITE_GLOB_API_URL + '/api/DataAnalysis/AiShpDataExpenseAccountingTableToExcel';
        break;
      case 'weixingyaoganyingxiang_shp':
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoSingle/ExportShapefile';
        break;
      case 'wurenjixunfei_shp':
        url = VITE_GLOB_API_URL + '/api/DroneCaseInfoSingle/CaseOffenceToExcel';
        break;
      default:
        break;
    }
    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);
    });
  }
</script>
<style lang="less">
  .full-modal {
    .ant-modal {
      max-width: 100%;
      top: 0;
    }

    .ant-modal-content {
      height: calc(100vh);
    }

    .ant-modal-body {
      height: 85%;
    }
  }
</style>
<style lang="less" scoped>
  .search-box {
    background: @component-background;
    height: inherit;
    margin: 16px;
    padding: 16px;
  }
  ::v-deep .ant-col-24 {
    display: inline-block;
    max-width: fit-content;
    margin-left: 20px;
  }
  ::v-deep .ant-form-item-control-input-content {
    display: flex;
  }
  .exportbutton {
    width: 510px;
    height: 60px;
    margin: 5px;
  }
  .table-box {
    height: calc(100vh - 200px);
    overflow: auto;
  }
</style>
