<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="700">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="父类型" prop="parentId" v-if="shouldShowParentType&&formData.parentId!==0">
        <el-tree-select
          v-model="formData.parentId"
          :data="typeOptions"
          :props="{ label: 'materialsTypeName', value: 'id', children: 'children' }"
          placeholder="请选择父类型"
          class="!w-240px"
        />
      </el-form-item>
      <!--      <el-row>-->
      <!--        <el-col :span="17">-->
      <!--          <el-form-item label="物资类型编码" prop="materialsTypeCode">-->
      <!--            <el-input-->
      <!--              v-model="formData.materialsTypeCode"-->
      <!--              placeholder="请输入物资类型编码"-->
      <!--              class="!w-240px"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--        <el-col :span="6">-->
      <!--          <el-form-item label-width="30">-->
      <!--            <el-switch-->
      <!--              v-model="autoGenFlag"-->
      <!--              active-text="自动生成"-->
      <!--              @change="handleAutoGenChange"-->
      <!--            />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->
      <el-form-item label="物资类型名称" prop="materialsTypeName">
        <el-input
          v-model="formData.materialsTypeName"
          placeholder="请输入物资类型名称"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物资规格" prop="propertyIds">
        <el-select v-model="formData.propertyIds" placeholder="请选择规格" class="!w-240px">
          <el-option
            v-for="property in propertyList"
            :key="property.value"
            :label="property.label"
            :value="String(property.value)"
          />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="物资类型图标" prop="materialsTypeIcon">
            <UploadImg v-model="formData.materialsTypeIcon" :limit="1" height="64px" width="64px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物资缩略图" prop="materialsTypePicture">
            <UploadImg
              v-model="formData.materialsTypePicture"
              :limit="1"
              height="64px"
              width="64px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="检查标准" prop="checkStandard">
        <el-input
          v-model="formData.checkStandard"
          type="textarea"
          :rows="10"
          placeholder="请输入检查标准"
          class="!w-420px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入内容"
          class="!w-420px"
        />
      </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 * as TypeApi from '@/api/material/type'
import * as PropertyApi from '@/api/material/standard/index'
// import { genCode } from '@/api/system/autocode/rule'
import { handleTree } from '@/utils/tree'
defineOptions({ name: 'MaterialTypeForm' })

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 shouldShowParentType = ref(false)
const formData = ref({
  ancestors: '0',
  materialsTypeId: undefined,
  parentId: 0,
  propertyIds:undefined,
  materialsTypeCode: '',
  materialsTypeName: '',
  propertyId: undefined,
  materialsTypeIcon: '',
  materialsTypePicture: '',
  checkStandard: '',
  remark: '',
  enableFlag: 'Y',
  status: 'y' // 默认为 "启用"
})

const formRules = reactive({
  // materialsTypeCode: [{ required: true, message: '物资类型编码不能为空', trigger: 'blur' }],
  materialsTypeName: [{ required: true, message: '物资类型名称不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
const typeOptions = ref([]) // 类型选项
const propertyList = ref([]) // 规格列表

/** 打开弹窗 */
const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 判断是否显示父类型
  if (row) {
    shouldShowParentType.value = true
  } else {
    shouldShowParentType.value = false
  }
  // 获取类型树和规格列表
  await Promise.all([getTypeTree(), getPropertyList()])
  if (row != null && row.id) {
    formData.value.parentId = row.id
    formData.value.ancestors = row.ancestors + ',' + row.id
  } else {
    formData.value.parentId = 0
    formData.value.ancestors = 0
  }
  // 修改时，设置数据
  if (row?.id&&type=='update') {
    formLoading.value = true
    try {
      formData.value = await TypeApi.getTypeInfo(row.id)
    } finally {
      formLoading.value = false
    }
  } else if (row) {
    formData.value.parentId = row.id
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取类型树 */
const getTypeTree = async () => {
  const data = await TypeApi.listType({ pageNo: 1, pageSize: -1 })
  typeOptions.value = handleTree(data.list)
}

/** 获取规格列表 */
const getPropertyList = async () => {
  const data = await PropertyApi.PropertyPage({ pageNo: 1, pageSize: -1 })
  console.log(data, 'aaa')
  propertyList.value = data.list.map((property) => {
    return {
      value: property.id,
      label: property.propertyName
    }
  })
}

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

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    materialsTypeId: undefined,
    parentId: undefined,
    materialsTypeCode: '',
    materialsTypeName: '',
    propertyIds: undefined,
    materialsTypeIcon: '',
    materialsTypePicture: '',
    checkStandard: '',
    remark: ''
  }
  formRef.value?.resetFields()
  autoGenFlag.value = false
}
</script>
