<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!--      <el-form-item label="配置编号" prop="configId">
              <el-input v-model="formData.configId" placeholder="请输入配置编号" />
            </el-form-item>-->
      <el-form-item :label="t('FactoryModeling.EsopFile.tableCodeColumn')" prop="code">
        <el-input v-model="formData.code" placeholder="点击新增时自动生成" :readonly="true">
          <!--          <template #append>
                      <el-button @click="refreshCode" title="重新生成">
                        <Refresh />
                      </el-button>
                    </template>-->
        </el-input>
<!--        <div class="form-tips">注：此编号为系统自动生成</div>-->
      </el-form-item>
      <el-form-item :label="t('FactoryModeling.EsopFile.tableNameColumn')" prop="name">
        <el-input v-model="formData.name" :placeholder="t('FactoryModeling.EsopFile.searchFileNamePlaceholder')" />
      </el-form-item>
      <el-form-item :label="t('FactoryModeling.EsopFile.searchClassificationLabel')" prop="classification">
        <el-select
          v-model="formData.classification"
          clearable
          :placeholder="t('FactoryModeling.EsopFile.searchClassificationPlaceholder')"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.Classification)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="文件类型" prop="type">
        <el-input v-model="formData.type" placeholder="请输入文件类型" />
      </el-form-item>-->

      <el-form-item :label="t('FactoryModeling.EsopFile.searchStatusLabel')" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.FILE_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="uploadUrl"
      :auto-upload="false"
      :before-upload="beforeUpload"
      :data="data"
      :disabled="isEdit"
      :limit="1"
      :on-change="handleFileChange"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      :http-request="httpRequest"
      accept=".jpg, .png, .gif ,.pdf,.word,.excel,.ppt,.pptx,.mp4,.avi,.mov"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">  {{t('FactoryModeling.EsopFile.messageThree')}} <em>{{t('FactoryModeling.EsopFile.messageFour')}}</em></div>
      <template #tip>
        <div class="el-upload__tip" style="color: red">
          {{t('FactoryModeling.EsopFile.messageOne')}} .jpg, .png, .gif ,.pdf,.word,.excel,.ppt,.pptx,.mp4,.avi,.mov  {{t('FactoryModeling.EsopFile.messageTwo')}}！
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitFileForm">{{t('FactoryModeling.EsopFile.dialogSubmitButton')}}</el-button>
      <el-button @click="dialogVisible = false">{{t('FactoryModeling.EsopFile.dialogCancelButton')}}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import {useUpload} from "@/views/mes/esopFile/useUpload";
import {FileApi, FileVO} from "@/api/mes/esopFile";
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import {FeedingRecordPlanApi, FeedingRecordPlanVO} from "@/api/mes/feedingplan";

defineOptions({ name: 'InfraFileForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const isEdit = ref(false)
const fileList = ref([]) // 文件列表
const data = ref({ path: '' })
const uploadRef = ref()
const dialogTitle = ref('') // 弹窗的标题
const { uploadUrl, httpRequest } = useUpload()
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  configId: undefined,
  code: undefined,
  name: undefined,
  path: undefined,
  url: undefined,
  type: undefined,
  classification: undefined,
  status: 1,
  size: undefined,
})

const formRules = reactive({
  path: [{ required: true, message: '文件路径不能为空', trigger: 'blur' }],
  url: [{ required: true, message: '文件 URL不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '文件状态不能为空', trigger: 'blur' }],
  size: [{ required: true, message: '文件大小不能为空', trigger: 'blur' }],
})
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  fileList.value =[]
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    isEdit.value = true
    try {
      formData.value = await FileApi.getFile(id)
      let file = {
        name: formData.value.name,
        url: formData.value.url,
        size: formData.value.size,
      }
      fileList.value.push(file)
    } finally {
      formLoading.value = false
    }
  }else{
    formData.value = {}
    await getGeneratedCode()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 处理上传的文件发生变化 */
const handleFileChange = (file) => {
  data.value.path = file.name
}
const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 100
  if (!isLt2M) {
    message.error('上传文件大小不能超过 100MB!')
  }
  return isLt2M
}

/** 提交表单 */
const submitFileForm = async () => {
  data.value.params = formData
  if(isEdit.value){
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as FileVO
      await FileApi.updateFile(data)
      message.success(t('common.updateSuccess'))
      dialogVisible.value = false
      emit('success')
    } finally {
      formLoading.value = false
    }
  }else{
    isEdit.value=false
    if (fileList.value.length == 0) {
      message.error('请上传文件')
      return
    }
    unref(uploadRef)?.submit()
  }

}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitFormSuccess = () => {
  // 清理
  dialogVisible.value = false
  formLoading.value = false
  unref(uploadRef)?.clearFiles()
  // 提示成功，并刷新
  message.success(t('common.createSuccess'))
  emit('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

// 获取生成的编码
const getGeneratedCode = async () => {
  try {
    const res = await FileApi.generateCode()  // 传递编码规则
    if (res !== undefined) {
      formData.value.code = res
      formData.value.status = 1
    }
  } catch (error) {
    console.error('获取编码失败:', error)
    // 可以给用户一个默认编码或提示
    formData.value.code = 'ESOP_' + Date.now()
  }
}
</script>
