<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="90px"
    >
      <el-form-item label="显示排序" prop="orderNum">
        <el-input-number
          v-model="formData.orderNum"
          controls-position="right"
          :min="0"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="标题" prop="instructionsTitle">
        <el-input v-model="formData.instructionsTitle" placeholder="请输入标题" class="!w-240px" />
      </el-form-item>
      <el-form-item label="物资类型" prop="materialsTypeId">
        <el-tree-select
          v-model="formData.materialsTypeId"
          :data="materialstypeOptions"
          :props="{ label: 'materialsTypeName', value: 'id' }"
          placeholder="请选择物资类型"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="类型" prop="fileType">
        <el-select v-model="formData.fileType" placeholder="请选择文件类型" class="!w-240px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.FILE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件" prop="fileUrl">
        <div v-if="formData.fileUrl">
          <div v-if="isVideo(formData.fileUrl)">
            <video :src="formData.fileUrl" width="300" height="200" controls></video>
          </div>
          <div v-if="isPdf(formData.fileUrl)">
            <iframe :src="formData.fileUrl" style="width: 300px; height: 200px;"></iframe>
          </div>
          <el-button type="danger" @click="handleDeleteFile">删除</el-button>
        </div>
        <div v-else>
          <UploadFile
            v-model="formData.fileUrl"
            :file-type="['mp4', 'pdf']"
            :limit="1"
            :file-size="100"
            class="min-w-80px"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { getAccessToken } from '@/utils/auth'
import { handleTree } from '@/utils/tree'
import * as InstructionsApi from '@/api/material/instructions/index'
import * as TypeApi from '@/api/material/type'

defineOptions({ name: 'InstructionsForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const uploadLoading = ref(false) // 上传的加载中

const formData = ref({
  instructionsId: undefined,
  instructionsTitle: '',
  materialsTypeId: undefined,
  fileType: undefined,
  fileUrl: '',
  orderNum: 0
})

const formRules = reactive({
  instructionsTitle: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  materialsTypeId: [{ required: true, message: '物资类型不能为空', trigger: 'change' }],
  fileType: [{ required: true, message: '类型不能为空', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref
const uploadRef = ref() // 上传 Ref
const materialstypeOptions = ref([]) // 物资类型选项


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InstructionsApi.getInstructionsInfo(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取物资类型树形结构 */
const getMaterialTypes = async () => {
  const data = await TypeApi.listType({
    pageNo: 1,
    pageSize: -1
  })
  materialstypeOptions.value = handleTree(data.list, 'id', 'parentId', 'children')
}

/** 判断是否为视频 */
const isVideo = (url: string) => {
  return url && (url.endsWith('.mp4') || url.includes('mp4'))
}

/** 判断是否为PDF */
const isPdf = (url: string) => {
  return url && (url.endsWith('.pdf') || url.includes('pdf'))
}

/** 删除文件 */
const handleDeleteFile = () => {
  formData.value.fileUrl = ''
}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await InstructionsApi.addInstructions(data)
      message.success(t('common.createSuccess'))
    } else {
      await InstructionsApi.updateInstructions(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    instructionsId: undefined,
    instructionsTitle: '',
    materialsTypeId: undefined,
    fileType: undefined,
    fileUrl: '',
    orderNum: 0
  }
  formRef.value?.resetFields()
  uploadRef.value?.clearFiles()
}

/** 初始化 **/
onMounted(async () => {
  await getMaterialTypes()
})
</script>
