<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="name">
<!--            <el-input v-model="formData.name" placeholder="请输入物料名称" />-->
            <lang-input v-model="formData.name" placeholder="请输入物料名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属物料组" prop="materialGroupId">
            <el-tree-select
              filterable
              v-model="formData.materialGroupId"
              :data="materialGroupTree"
              :props="defaultProps"
              :default-expanded-keys="firstLevelKeys"
              check-strictly
              clearable
              node-key="id"
              value-key="id"
              placeholder="请选择所属物料组"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="物料编码" prop="code">
            <el-input v-model="formData.code" maxlength="32" placeholder="请输入物料编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格型号" prop="model">
            <el-input v-model="formData.model" maxlength="50" placeholder="请输入规格型号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-select v-model="formData.unit" filterable clearable placeholder="请选择单位" class="w-1/1">
              <el-option
                v-for="(item, index) in getStrDictOptions(DICT_TYPE.IOT_THING_MODEL_UNIT)"
                :key="index"
                :label="item.label + '-' + item.value"
                :value="item.label + '-' + item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="formData.sort" :min="0" controls-position="right" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </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 { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as MaterialGroupApi from '@/api/pms/materialgroup'
import * as MaterialApi from '@/api/pms/material'
import { FormRules } from 'element-plus'
import { useTreeStore } from '@/store/modules/materialGroupTreeStore'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";

defineOptions({ name: 'MaterialForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const treeStore = useTreeStore();
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const storedMaterialGroupId = ref(null);  // 通过store存储的物料组id 由父组件传递过来
const materialGroupTree = ref<Tree[]>([])   // 物料组分类树

const formData = ref({
  name: '',
  materialGroupId: storedMaterialGroupId.value,
  code: '',
  model: '',
  id: undefined,
  unit: '',
  sort: 0,
  remark: '',
  status: CommonStatusEnum.ENABLE,
})
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '物料名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
  materialGroupId: [{ required: true, message: '所属物料组不能为空', trigger: 'blur' }],

})
const formRef = ref() // 表单 Ref
const firstLevelKeys = ref<Tree[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 获取store中的设备分类id
  storedMaterialGroupId.value = treeStore.selectedId;
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MaterialApi.getMaterial(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载 物料组 树
  // materialGroupList.value = handleTree(await MaterialGroupApi.getSimpleMaterialGroupList())
  await getMaterialGroupTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获得 物料组分类 树 **/
const getMaterialGroupTree = async () => {
  materialGroupTree.value = []
  const res = await MaterialGroupApi.getSimpleMaterialGroupList()
  let categoryTree: Tree = { id: 0, name: '物料组分类', children: [] }
  categoryTree.children = handleTree(res)
  materialGroupTree.value.push(categoryTree)
  firstLevelKeys.value = materialGroupTree.value.map(node => node.id);
}

/** 提交表单 */
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 as unknown as MaterialApi.MaterialVO
    if (formType.value === 'create') {
      await MaterialApi.createMaterial(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialApi.updateMaterial(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: '',
    materialGroupId: storedMaterialGroupId.value,
    code: '',
    model: '',
    id: undefined,
    unit: '',
    sort: 0,
    remark: '',
    status: CommonStatusEnum.ENABLE,
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(() => {
  formData.value.sort = 0
})

</script>
