<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 50vw;min-height: 50vh" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
        <el-form-item :label="t('monitor.category')"  prop="deviceClassify">
          <el-tree-select
            filterable
            v-model="formData.deviceClassify"
            :data="productClassifyList"
            :props="defaultProps"
            check-strictly
            node-key="id"
            :placeholder="t('deviceForm.categoryHolder')"
            clearable
          />
        </el-form-item>
          </el-col>
        <el-col :span="12">
        <el-form-item :label="t('monitor.deviceName')" prop="deviceId">
          <el-select
            v-model="formData.deviceId"
            :model-value="deviceLabel"
            :placeholder="t('monitor.nameHolder')"
            @click="openForm"
          />
        </el-form-item>
          </el-col>
        <el-col :span="12">
        <el-form-item :label="t('inspect.InspectionItems')" prop="item">
          <el-input v-model="formData.item" :placeholder="t('inspect.itemHolder')" />
        </el-form-item>
          </el-col>
        <el-col :span="12">
        <el-form-item :label="t('common.sort')" prop="sort">
          <el-input v-model="formData.sort" type="number" :placeholder="t('common.sortHolder')" />
        </el-form-item>
          </el-col>
        <el-col :span="24">
          <el-form-item :label="t('inspect.InspectionStandards')" prop="standard">
            <el-input v-model="formData.standard" type="textarea" :placeholder="t('inspect.stanHolder')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('fileInfo.appendix')" prop="urls">
            <UploadFile v-model="formData.urls" :limit="1" :is-show-tip="false" class="min-w-80px" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
        <el-form-item :label="t('form.remark')" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :placeholder="t('deviceForm.remarkHolder')" />
        </el-form-item>
          </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('faultForm.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('faultForm.cancel') }}</el-button>
    </template>
  </Dialog>
  <DeviceList ref="deviceFormRef" @choose="deviceChoose" />
</template>
<script setup lang="ts">
import { IotInspectItemApi, IotInspectItemVO } from '@/api/pms/inspect/item'
import {defaultProps, handleTree} from "@/utils/tree";
import * as ProductClassifyApi from "@/api/pms/productclassify";
import DeviceList from "@/views/pms/failure/DeviceList.vue";
import {CACHE_KEY, useCache} from "@/hooks/web/useCache";
/** 巡检项 表单 */
defineOptions({ name: 'IotInspectItemForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const productClassifyList = ref<Tree[]>([]) // 树形结构
const deviceLabel = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  item: undefined,
  standard: undefined,
  sort: undefined,
  remark: undefined,
  deptId: undefined,
  deviceClassify: undefined,
  deviceClassifyName: undefined,
  deviceId: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  urls: undefined,
})
const formRules = reactive({
  deviceClassify: [{ required: true, message: '设备类别不能为空', trigger: 'blur' }],
  item: [{ required: true, message: '巡检项不能为空', trigger: 'blur' }],
  standard: [{ required: true, message: '巡检标准不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const deviceChoose = (row) => {
  formData.value.deviceId = row.id
  formData.value.deviceName = row.deviceName
  formData.value.deviceCode = row.deviceCode
  formData.value.deptId = row.deptId;
  deviceLabel.value = row.deviceName
}

/** 打开弹窗 */
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 IotInspectItemApi.getIotInspectItem(id)
      deviceLabel.value = formData.value.deviceName
    } finally {
      formLoading.value = false
    }
  }else {
    formData.value.sort = 0
    deviceLabel.value = ''
  }

  productClassifyList.value = handleTree(
    await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList()
  )
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const deviceFormRef = ref()
const openForm = () => {
  deviceFormRef.value.open(formData.value.deviceClassify)
}

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    item: undefined,
    standard: undefined,
    sort: undefined,
    remark: undefined,
    deptId: undefined,
  }
  formRef.value?.resetFields()
}
</script>
