<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" @close="close" v-bind="dialogSmall">
    <div>
      <el-form ref="dialogFormRef" :model="formContent" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formContent.name" placeholder="请输入报告名称"/>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="formContent.version" placeholder="请输入版本号"/>
        </el-form-item>
        <el-form-item label="基础模板文件" prop="baseFile">
          <el-upload
              action="#"
              :limit="1"
              :on-change='BaseHandleChange'
              :auto-upload="false"
              :file-list="baseFileList"
              :on-exceed="BaseHandleExceed"
              :on-remove="BaseHandleRemove"
              style="width: 100% !important;"
              accept=".docx"
              class="upload-container"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
          仅支持上传大小不超过5MB的.docx文件
        </el-form-item>
        <el-form-item label="检测项模版文件" prop="detailFile">
          <el-upload
              action="#"
              :limit="1"
              :on-change='DataHandleChange'
              :auto-upload="false"
              :file-list="detailFileList"
              :on-exceed="DataHandleExceed"
              :on-remove="DataHandleRemove"
              style="width: 100% !important;"
              accept=".docx"
              class="upload-container"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
          仅支持上传大小不超过5MB的.docx文件
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="formContent.description" type="textarea" placeholder="请输入描述信息"/>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div>
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {dialogSmall} from '@/utils/elementBind'
import {type PqReport} from '@/api/device/interface/report'
import {ElMessage, UploadFile} from 'element-plus'
import {addPqReport, getPqReportById, updatePqReport} from '@/api/device/report'
import {computed, reactive, ref} from 'vue'

// 定义弹出组件元信息
const dialogFormRef = ref()
let excelFormData = new FormData()

const baseFileName = ref('')
const baseFileUrl = ref('')
const detailFileName = ref('')
const detailFileUrl = ref('')

const baseFileList = computed(() => {
  if (baseFileName.value && baseFileUrl.value) {
    return [{name: baseFileName.value, url: baseFileUrl.value}];
  }
  return [];
});

const detailFileList = computed(() => {
  if (detailFileName.value && detailFileUrl.value) {
    return [{name: detailFileName.value, url: detailFileUrl.value}];
  }
  return [];
});

function useMetaInfo() {
  const dialogVisible = ref(false)
  const titleType = ref('add')
  const formContent = ref<PqReport.ResReport>({
    id: '',
    name: '',
    version: '', // 版本号
    description: '', // 描述信息
    detailFile: '',//检测项模版文件路径
    baseFile: '',
    state: 1,
  })
  return {dialogVisible, titleType, formContent}
}

const {dialogVisible, titleType, formContent} = useMetaInfo()

// 清空formContent
const resetFormContent = () => {
  formContent.value = {
    id: '',
    name: '',
    version: '', // 版本号
    description: '', // 描述信息
    detailFile: '',//检测项模版文件路径
    baseFile: '',
    state: 1,
  }

}

let dialogTitle = computed(() => {
  return titleType.value === 'add' ? '新增报告模版' : '编辑报告模版'
})

// 关闭弹窗
const close = () => {
  excelFormData = new FormData()
  dialogVisible.value = false
  resetFormContent()
  dialogFormRef.value?.resetFields()
}

// 表单验证规则
const rules = reactive({
  name: [{required: true, message: '请输入报告名称', trigger: 'blur'}],
  version: [{required: true, message: '请输入版本号', trigger: 'blur'}],
  baseFile: [{required: true, message: '请上传基础模板文件', trigger: 'change'}],
  detailFile: [{required: true, message: '请上传检测项模版文件', trigger: 'change'}],
})

// 保存数据
const save = () => {
  try {
    dialogFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        // 清空 excelFormData
        excelFormData.delete('id')
        excelFormData.delete('name')
        excelFormData.delete('version')
        excelFormData.delete('description')

        excelFormData.append('name', formContent.value.name)
        excelFormData.append('version', formContent.value.version)
        excelFormData.append('description', formContent.value.description)
        let baseFileFlag = handleFileLimit(excelFormData.get('baseFile') as File)
        let detailFileFlag = handleFileLimit(excelFormData.get('detailFile') as File)
        if (!baseFileFlag || !detailFileFlag) {
          return
        }
        if (formContent.value.id) {

          excelFormData.append('id', formContent.value.id)
          await updatePqReport(excelFormData);
          ElMessage.success({message: `${dialogTitle.value}成功！`})
        } else {
          await addPqReport(excelFormData);
          ElMessage.success({message: `${dialogTitle.value}成功！`})

        }

        close()
        // 刷新表格
        await props.refreshTable!()
      }

    })
  } catch (err) {
    console.error('验证过程中出现错误', err)
  }
}

// 打开弹窗，可能是新增，也可能是编辑
const open = async (sign: string, data?: PqReport.ResReport) => {
  titleType.value = sign
  dialogVisible.value = true
  if (data?.id) {
    await getPqReportById(data).then((res) => {
      formContent.value.id = res.data.id
      formContent.value.name = res.data.name
      formContent.value.version = res.data.version
      formContent.value.description = res.data.description


      // 处理文件信息
      if (res.data.baseFileVO) {
        baseFileName.value = res.data.baseFileVO.name;
        baseFileUrl.value = res.data.baseFileVO.url;

        formContent.value.baseFile = res.data.baseFileVO.name
      }
      if (res.data.detailFileVO) {
        detailFileName.value = res.data.detailFileVO.name;
        detailFileUrl.value = res.data.detailFileVO.url;

        formContent.value.detailFile = res.data.detailFileVO.name
      }


    })
  } else {
    baseFileName.value = ''
    baseFileUrl.value = ''
    detailFileName.value = ''
    detailFileUrl.value = ''
    resetFormContent();
    dialogFormRef.value?.resetFields()
    // 清空 excelFormData
    excelFormData = new FormData();

  }

}

const DataHandleRemove = () => {
  excelFormData.delete('detailFile');
  formContent.value.detailFile = ''
};

const BaseHandleRemove = () => {
  excelFormData.delete('baseFile');
  formContent.value.baseFile = ''
};

const BaseHandleExceed = (files: File[]) => {
  // 移除旧文件
  excelFormData.delete('baseFile');
  // 添加新文件
  if (files.length > 0) {
    const newFile = files[0] as unknown as UploadFile;
    baseFileName.value = newFile.name;
    excelFormData.append('baseFile', newFile as Blob, newFile.name);

    formContent.value.detailFile = newFile.name
  }

};

const DataHandleExceed = (files: File[]) => {
  // 移除旧文件
  excelFormData.delete('detailFile');

  // 添加新文件
  if (files.length > 0) {
    const newFile = files[0] as UploadFile;
    detailFileName.value = newFile.name;
    excelFormData.append('detailFile', newFile as Blob, newFile.name);

    formContent.value.detailFile = newFile.name
  }

};

const BaseHandleChange = async (param: UploadFile) => {
  baseFileName.value = param.name;
  baseFileUrl.value = URL.createObjectURL(param.raw as Blob);
  excelFormData.append('baseFile', param.raw as Blob, param.name);

  formContent.value.baseFile = param.name;
};

const DataHandleChange = async (param: UploadFile) => {
  detailFileName.value = param.name;
  detailFileUrl.value = URL.createObjectURL(param.raw as Blob);
  excelFormData.append('detailFile', param.raw as Blob, param.name);

  formContent.value.detailFile = param.name;
};

const fileSizeLimit = 5 * 1024 * 1024; // 5MB

const handleFileLimit = (file: File) => {
  if (file) {
    if (file.size > fileSizeLimit) {
      ElMessage.error({message: `文件大小不能超过${fileSizeLimit / 1024 / 1024}MB`});
      return false;
    } else {
      return true;
    }
  }
  return true;
}


// 对外映射
defineExpose({open})
const props = defineProps<{
  refreshTable: (() => Promise<void>) | undefined
}>()
</script>
<style scoped>
.upload-container {
  display: flex;
  align-items: center;
}
</style>