<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="450">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="锁具机构类型" prop="locksetTypeId">
        <el-tree-select
          v-model="formData.locksetTypeId"
          :data="locksetTypeOptions"
          :props="{ label: 'locksetTypeName', value: 'locksetTypeId', children: 'children' }"
          placeholder="请选择锁具机构类型"
          class="!w-240px"
        />
      </el-form-item>
      <el-row>
        <el-col :span="15">
          <el-form-item label="锁具机构编码" prop="locksetCode">
            <el-input
              v-model="formData.locksetCode"
              placeholder="请输入锁具机构编码"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="80">
            <el-switch
              v-model="autoGenFlag"
              active-color="#13ce66"
              active-text="自动生成"
              @change="handleAutoGenChange"
              v-if="formType !== 'view'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="锁具机构名称" prop="locksetName">
        <el-input
          v-model="formData.locksetName"
          placeholder="请输入锁具机构名称"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="锁具机构NFC" prop="locksetNfc">
        <el-input
          v-model="formData.locksetNfc"
          placeholder="请输入锁具机构Nfc"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="锁具机构RFID" prop="locksetRfid">
        <el-input
          v-model="formData.locksetRfid"
          placeholder="请输入锁具机构RFID"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物资名称" prop="materialsId">
        <el-select
          v-model="formData.materialsId"
          placeholder="请选择物资名称"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in materialsOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="锁具机构型号" prop="locksetSpec">
        <el-input
          v-model="formData.locksetSpec"
          placeholder="请输入锁具机构型号"
          maxlength="16"
          class="!w-240px"
        />
      </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 { ref, reactive } from 'vue'
import { handleTree } from '@/utils/tree'
import * as LocksetApi from '@/api/hw/hardware/lockset/index'
import * as LocksetTypeApi from '@/api/hw/type/locksettype/index'
// import * as MaterialApi from '@/api/mes/material/information'
// import * as AutocodeApi from '@/api/system/autocode/rule'

defineOptions({ name: 'LockForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const autoGenFlag = ref(false) // 是否自动生成编码

const formData = ref({
  locksetId: undefined,
  locksetTypeId: undefined,
  locksetCode: '',
  locksetName: '',
  locksetNfc: '',
  locksetRfid: '',
  materialsId: undefined,
  locksetSpec: ''
})

const formRules = reactive({
  locksetCode: [{ required: true, message: '锁具机构编码不能为空', trigger: 'blur' }],
  locksetName: [{ required: true, message: '锁具机构名称不能为空', trigger: 'blur' }],
  locksetNfc: [{ required: true, message: '锁具机构NFC不能为空', trigger: 'blur' }],
  locksetRfid: [{ required: true, message: '锁具机构RFID不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
const locksetTypeOptions = ref([]) // 锁具机构类型选项
const materialsOptions = 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 LocksetApi.getLockInfoAPI(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    locksetId: undefined,
    locksetTypeId: undefined,
    locksetCode: '',
    locksetName: '',
    locksetNfc: '',
    locksetRfid: '',
    materialsId: undefined,
    locksetSpec: ''
  }
  autoGenFlag.value = false
  formRef.value?.resetFields()
}

/** 自动生成编码 */
const handleAutoGenChange = async (value: boolean) => {
  if (value) {
    formData.value.locksetCode = await AutocodeApi.genCode('LOCKSET_CODE')
  } else {
    formData.value.locksetCode = ''
  }
}

/** 获取锁具机构类型列表 */
const getLockTypeList = async () => {
  const data = { pageNo: 1, pageSize: -1 }
  const response = await LocksetTypeApi.listLockType(data)
  locksetTypeOptions.value = handleTree(response.records, 'locksetTypeId', 'parentTypeId', 'children')
}

/** 获取物资列表 */
const getMaterialList = async () => {
  const data = { pageNo: 1, pageSize: -1 }
  const response = await MaterialApi.listMaterials(data)
  materialsOptions.value = response.records.map(item => ({
    value: item.materialsCabinetId,
    label: item.materialsName
  }))
}

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