<script setup lang="ts">
import MessageUtils from "@/utils/MessageUtils.ts";
import BaseErrorApi from "@/api/baseError.ts";
import {ref} from "vue";
import {genFileId, type UploadInstance, type UploadProps, type UploadRawFile} from "element-plus";
import type {AppServeResponse} from "@/interface/api/AppServeResponse.ts";
import {AppServeResponseCodeEnum} from "@/constant/enums/AppServeResponseCodeEnum.ts";
import ErrorBaseEquipmentTypeFormatter from "@/plugin/formatter/ErrorBaseEquipmentTypeFormatter.ts";

const errorBaseEquipmentTypeFormatter = new ErrorBaseEquipmentTypeFormatter(); // 设备报警基础资料设备型号格式化
const modelValue = defineModel('modelValue', {required: true, default: false});
const emit = defineEmits(['reLoadingTableData']);
const close = () => { modelValue.value = false; };
const clearEquipmentType = ref<number>(1);
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
};
// 开始导入
const submitUpload = () => {
  if(!upload.value) {
    MessageUtils.errMessageBox('请选择文件');
    return;
  }
  upload.value.submit()
};
// 下载模版
const downloadModel = () => {
  const loadingInstance = MessageUtils.loading("请稍后");
  BaseErrorApi.downLoadImportExample().then(res => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '设备报警基础资料导入模版.xlsx');
    document.body.appendChild(link);
    MessageUtils.successMessage('您的下载将尽快开始，请稍后');
    link.click();
    document.body.removeChild(link);
  }).catch(() => {}).finally(() => {
    loadingInstance.close();
  });
};
// 导入成功
const handleSuccess = (response: any, file: any, fileList: any) => {
  const res = JSON.parse(JSON.stringify(response)) as AppServeResponse;
  if (res.code == AppServeResponseCodeEnum.SUCCESS) {
    MessageUtils.successMessage('导入成功');
    emit('reLoadingTableData');
    close();
    setTimeout(() => {
      upload.value!.clearFiles();
    }, 2000);
    return;
  }
  MessageUtils.errMessageBox(res.msg);
  setTimeout(() => {
    upload.value!.clearFiles();
  }, 2000);
};
// 清理数据
const clearData = () => {
  if(!clearEquipmentType.value && clearEquipmentType.value != 0) {
    MessageUtils.warningMessageBox('请选择设备型号');
    return;
  }
  MessageUtils.confirmMessageBox('确定清理选中设备类型的数据？删除后不可恢复','清理确认').then(()=>{
    const loadingInstance = MessageUtils.loading('清理中');
    BaseErrorApi.deleteBaseError(clearEquipmentType.value).then((res) => {
      const response = JSON.parse(JSON.stringify(res.data)) as AppServeResponse;
      if (response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('清理成功');
        emit('reLoadingTableData');
        return;
      }
      MessageUtils.errMessageBox(response.msg);
    }).catch(() => {}).finally(() => {
      loadingInstance.close();
    })
  }).catch(()=> {});
};

</script>

<template>
  <el-dialog v-model="modelValue" title="批量导入基础报警信息资料" @close="close" :close-on-click-modal="false">
    <el-scrollbar style="height:50vh;">
      <el-text type="warning">请按照如下模版格式填写数据，并上传</el-text>
      <el-row>
        <el-image src="/image/app/importBaseErrorExample.png" alt="模版图片"></el-image>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-upload :action="BaseErrorApi.getImportUrl()" accept=".xlsx" ref="upload"
                   :limit="1"
                   :headers="BaseErrorApi.getHeaders()"
                   :on-exceed="handleExceed"
                   :auto-upload="false"
                   :on-error="(error: any, file: any, fileList: any) => MessageUtils.errMessageBox('上传失败:' + error.message)"
                   :on-success="handleSuccess">
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              如有需要请下载模版填写后上传
            </div>
          </template>
        </el-upload>
      </el-row>
      <el-text style="margin-top: 20px" type="warning">部分情况下建议先清理数据，避免数据重复</el-text>
      <el-row style="margin-top: 10px">
        <el-form label-position="left" label-width="150px" inline>
          <el-form-item label="要清理的设备型号：" style="width: 250px;">
            <el-select v-model="clearEquipmentType"  placeholder="请选择设备型号">
              <el-option v-for="item in errorBaseEquipmentTypeFormatter.equipmentType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-button type="danger" @click="clearData">清理数据</el-button>
      </el-row>
    </el-scrollbar>
    <template #footer>
      <el-button-group>
        <el-button type="info" @click="downloadModel">下载模版</el-button>
        <el-button type="primary" @click="submitUpload">确定导入</el-button>
        <el-button type="danger" @click="close">关闭窗口</el-button>
      </el-button-group>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>