<template>
  <BasicDialog ref="basicDialogRef" title="导出报废记录" @refresh="refreshFromData">
    <template #form>
      <BasicForm
        ref="basicFormRef"
        :formData="ruleFormData"
        :formRules="formRules"
        :formConfig="ruleFormConfig"
        style="margin-bottom: 15px"
      >
        <template #discardTime>
          <el-date-picker
            v-model="ruleFormData.discardTime"
            type="daterange"
            range-separator="至"
            start-placeholder="请选择开始日期"
            end-placeholder="请选择截止日期"
            style="width: 100%"
          ></el-date-picker>
        </template>
      </BasicForm>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleDownload">提交</el-button>
      <el-button @click="basicDialogRef?.closeDialog">取消</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicDialog from '@/components/BasicDialog.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { ExportDiscardForm } from '@/types/emergency-supplier';
  import { exportDiscardRecord } from '@/api/emergency-supplier';
  import { EXPORT_DISCARD_FROM_CONFIG, EXPORT_DISCARD_FROM_DATA, EXPORT_DISCARD_FROM_RULES } from '../config';
  import { downloadFile } from '@/views/disaster/utils/download';
  import dayjs from 'dayjs';

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const { ruleFormConfig, ruleFormData, formRules } = useFormConfigHook<ExportDiscardForm>(
    EXPORT_DISCARD_FROM_CONFIG,
    EXPORT_DISCARD_FROM_DATA,
    EXPORT_DISCARD_FROM_RULES,
  );

  const openDialog = () => {
    basicDialogRef.value?.openDialog();
  };
  const handleDownload = async () => {
    const validate = await basicFormRef.value?.validateForm();
    if (!validate) return;

    try {
      const res = await exportDiscardRecord(
        dayjs(ruleFormData.discardTime[0]).format('YYYY-MM-DD'),
        dayjs(ruleFormData.discardTime[1]).add(1, 'day').format('YYYY-MM-DD'),
      );
      if (res.size === 0) return;
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      downloadFile(url, '物资报废记录.xlsx');
      ElMessage.success('导出报废记录成功');
      basicDialogRef.value?.closeDialog();
    } catch (e) {
      ElMessage.error('下载失败');
      console.log(e);
    }
  };
  const refreshFromData = () => {
    basicFormRef.value?.clearValidate();
  };
  defineExpose({
    openDialog,
  });
</script>

<style scoped lang="scss"></style>
