<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 50vw">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading">
      <el-form-item :label="t('fileInfo.fileDirectory')" prop="classId">
        <el-input v-model="displayNodeName" disabled placeholder="请选择文件目录" />
      </el-form-item>
      <el-form-item :label="t('fileInfo.appendix')" prop="filePath">
        <file-upload
          style="height: 300px"
          @uploadSuccess="handleUploadSuccess"
          @uploadError="handleUploadError"
          @uploadComplete="handleUploadComplete"
          :deviceId="props.classId" />
      </el-form-item>
      <el-form-item :label="t('fileInfo.fileType')" prop="fileType">
        <el-select
          v-model="formData.fileType"
          placeholder="请选择"
          :disabled="formType === 'detail'">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PMS_FILE_TYPE)"
            :key="dict.label"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('fileInfo.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          :disabled="formType === 'detail'"
          type="textarea"
          :placeholder="t('deviceForm.remarkHolder')" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        v-if="formType !== 'detail'"
        type="primary"
        :disabled="formLoading"
        @click="submitForm">
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DataLibraryApi } from '@/api/pms/qhse/index'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import FileUpload from '@/components/UploadFile/src/FileUpload.vue'

defineOptions({ name: 'IotInfoFormTree' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const displayNodeName = ref('')
const formRef = ref()
const formRules = reactive({})

const formData = ref({
  id: undefined,
  deviceId: undefined,
  classId: undefined,
  deptId: undefined,
  filename: undefined,
  fileType: undefined,
  filePath: undefined,
  remark: undefined,
  fileList: [],
  folderTree: [],
  folderJson: undefined
})

const props = defineProps<{
  deviceId: string
  classId: string
  nodeId: string
  deptId: string
  nodeName: string
}>()

const emit = defineEmits(['success'])

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 DataLibraryApi.getIotInfo(id)
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.fileType = 'file'
  }

  displayNodeName.value = props.nodeName
  formData.value.classId = props.classId
  formData.value.deptId = props.deptId
}

defineExpose({ open })

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true

  try {
    const data = formData.value
    if (formType.value === 'create') {
      data.deviceId = props.deviceId
      data.classId = props.classId
      data.deptId = props.deptId
      data.folderJson = JSON.stringify(data.folderTree)
      await DataLibraryApi.createIotInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await DataLibraryApi.updateIotInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceId: undefined,
    classId: undefined,
    deptId: undefined,
    filename: undefined,
    fileType: undefined,
    filePath: undefined,
    remark: undefined,
    fileList: [],
    folderTree: [],
    folderJson: undefined
  }
  displayNodeName.value = ''
  formRef.value?.resetFields()
}

const handleUploadSuccess = (data) => {
  if (!Array.isArray(formData.value.folderTree)) {
    formData.value.folderTree = []
  }
  formData.value.folderTree.push(data.response.data)
  message.success(`"${data.name}" 上传成功`)
}

const handleUploadError = (error) => {
  console.error('上传失败', error)
  message.error(`"${error.name}" 上传失败: ${error.error.message}`)
}

const handleUploadComplete = () => {
  message.info('所有上传任务已处理完成')
}
</script>
