<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="设备类别" prop="deviceClassify">
          <el-tree-select
            filterable
            v-model="formData.deviceClassify"
            :data="productClassifyList"
            :props="defaultProps"
            check-strictly
            node-key="id"
            placeholder="请选择设备类别"
            clearable
          />
        </el-form-item>
          </el-col>
        <el-col :span="12">
        <el-form-item label="设备名称" prop="deviceId">
          <el-select
            v-model="formData.deviceId"
            :model-value="deviceLabel"
            placeholder="请输入设备"
            @click="openForm"
          />
        </el-form-item>
          </el-col>
        <el-col :span="12">
        <el-form-item label="巡检项" prop="item">
          <el-input v-model="formData.item" placeholder="请输入巡检项" />
        </el-form-item>
          </el-col>
        <el-col :span="12">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" type="number" placeholder="请输入排序" />
        </el-form-item>
          </el-col>
        <el-col :span="24">
          <el-form-item label="巡检标准" prop="standard">
            <el-input v-model="formData.standard" type="textarea" placeholder="请输入巡检标准" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件" 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="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
          </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</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,
  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.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 {
    debugger
    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>
