<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="510">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
<!--      <el-form-item label="物资柜编码" prop="cabinetCode">-->
<!--        <el-input-->
<!--          v-model="formData.cabinetCode"-->
<!--          placeholder="请输入物资柜编码"-->
<!--          style="width: 200px; margin-right: 10px"-->
<!--        />-->
<!--        <el-switch-->
<!--          v-model="autoGenFlag"-->
<!--          active-color="#13ce66"-->
<!--          active-text="自动生成"-->
<!--          @change="handleAutoGenChange"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="物资柜名称" prop="cabinetName">
        <el-input
          v-model="formData.cabinetName"
          placeholder="请输入物资柜名称"
          style="width: 348px"
        />
      </el-form-item>
      <el-form-item label="所属区域" prop="workstationId">
        <el-tree-select
          v-model="formData.workstationId"
          :data="marsOptions"
          :props="{ label: 'workstationName', value: 'id', children: 'children' }"
          placeholder="选择所属区域"
          style="width: 348px"
        />
      </el-form-item>
      <el-form-item label="物资柜图片" prop="cabinetPicture">
        <UploadImg
          v-model="formData.cabinetPicture"
          :limit="1"
          height="64px"
          width="64px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入内容"
          style="width: 348px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        v-if="formType === 'view'"
        type="primary"
        @click="dialogVisible = false"
      >
        返回
      </el-button>
      <el-button
        v-else
        :disabled="formLoading"
        type="primary"
        @click="submitForm"
      >
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { handleTree } from '@/utils/tree'
import * as CabinetApi from '@/api/material/lockers'
import * as MarsDeptApi from '@/api/system/marsdept'

// import * as AutoCodeApi from '@/api/system/autocode/rule'


// 响应式数据
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref<string>('')
const formLoading = ref<boolean>(false)
const formType = ref<string>('')
const autoGenFlag = ref<boolean>(false)

const formData = ref<any>({
  cabinetCode: '',
  cabinetName: '',
  workstationId: '',
  remark: '',
  cabinetPicture: ''
})

// 下拉选项数据
const marsOptions = ref<[]>([])


// 表单校验规则
const formRules = reactive({
  // cabinetCode: [{ required: true, message: '物资柜编码不能为空', trigger: 'blur' }],
  cabinetName: [{ required: true, message: '物资柜名称不能为空', trigger: 'blur' }],
  workstationId: [{ required: true, message: '所属区域不能为空', trigger: 'change' }]
})

const formRef = ref()

// 获取下拉数据
const getDropdownData = async (): Promise<void> => {
  const data = {
    pageNo: 1,
    pageSize: -1
  }

  try {
    const response = await MarsDeptApi.listMarsDept(data)
    const filteredData = response.list.filter((item: any) => item.parentId == 0)
    marsOptions.value = handleTree(filteredData, 'id', 'parentId')
  } catch (error) {
    console.error('获取下拉数据失败:', error)
  }
}

// 自动生成编码
// const handleAutoGenChange = async (autoGenFlag: boolean): Promise<void> => {
//   if (autoGenFlag) {
//     try {
//       const response = await AutoCodeApi.genCode('MATERIALS_CABINET')
//       formData.value.cabinetCode = response
//     } catch (error) {
//       console.error('自动生成编码失败:', error)
//     }
//   } else {
//     formData.value.cabinetCode = ''
//   }
// }

// 打开弹窗
const open = async (type: string, id?: string): Promise<void> => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增物资柜信息' : '修改物资柜信息'
  formType.value = type
  resetForm()

  // 获取下拉数据
  await getDropdownData()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const response = await CabinetApi.getMaterialsCabinetInfo(id)

      formData.value = response
    } finally {
      formLoading.value = false
    }
  }
}

// 提交表单
const emit = defineEmits(['success'])
const submitForm = async (): Promise<void> => {
  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 CabinetApi.addMaterialsCabinet(data)
      ElMessage.success('新增成功')
    } else {
      await CabinetApi.updateMaterialsCabinet(data)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    formLoading.value = false
  }
}

// 重置表单
const resetForm = (): void => {
  formData.value = {
    cabinetCode: '',
    cabinetName: '',
    workstationId: '',
    remark: '',
    cabinetPicture: ''
  }
  autoGenFlag.value = false
  formRef.value?.resetFields()
}

// 暴露方法
defineExpose({ open })
</script>
