<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="设备分类" prop="deviceCategoryId">
        <el-tree-select
          v-model="formData.deviceCategoryId"
          :data="deviceCategoryTree"
          :props="defaultProps"
          check-strictly
          :default-expanded-keys="firstLevelKeys"
          placeholder="请选择设备分类"
          value-key="id"
          @node-click="handleDeviceCategoryTreeNodeClick"
        />
      </el-form-item>
      <el-form-item label="上级BOM" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="bomTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择上级BOM"
          value-key="bomId"
        />
      </el-form-item>
      <el-form-item label="BOM节点名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入BOM节点名称" />
      </el-form-item>
      <el-form-item label="BOM节点属性" prop="type">
        <el-checkbox-group v-model="formData.type" class="w-80">
          <el-checkbox
            v-for="dict in getIntDictOptions(DICT_TYPE.PMS_BOM_NODE_EXT_ATTR)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" controls-position="right" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as BomApi from '@/api/pms/bom'
import { CommonStatusEnum } from '@/utils/constants'
import { useTreeStore } from '@/store/modules/treeStore';
import * as DeviceCategoryApi from '@/api/pms/productclassify'
import { FormRules } from 'element-plus'
import { defineEmits, ref } from 'vue';

defineOptions({ name: 'BomForm' })

// 从store中共享设备分类id
const treeStore = useTreeStore();
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const localCategoryId = ref(null);  // 通过store存储的设备分类id 由父组件传递过来
const selfDeviceCategoryId = ref(null);  // 当前页面定义的 设备分类id
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceCategoryId: localCategoryId.value,
  title: '',
  parentId: undefined,
  name: undefined,
  sort: 0,
  type: undefined,
  status: CommonStatusEnum.ENABLE
})
const formRules = reactive<FormRules>({
  deviceCategoryId: [{ required: true, message: '设备分类不能为空', trigger: 'blur' }],
  parentId: [{ required: true, message: '上级Bom不能为空', trigger: 'blur' }],
  name: [{ required: true, message: 'Bom节点名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const bomTree = ref() // BOM 树形结构
const deviceCategoryTree = ref()  // 设备分类树
const firstLevelKeys = ref([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
  deviceCategoryId: localCategoryId.value,
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 获取store中的设备分类id
  localCategoryId.value = treeStore.selectedId;
  selfDeviceCategoryId.value = treeStore.selectedId;
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BomApi.getBom(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得 设备分类树
  await getDeviceCategoryTree()
  // 获得 bom 树
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success', 'node-click']) // 定义 success 树点击 事件，用于操作成功后的回调

/** 处理 设备分类 树 被点击 */
const handleDeviceCategoryTreeNodeClick = async (row: { [key: string]: any }) => {
  emit('node-click', row)
  // treeStore.setSelectedId(row.id);
  // 清空设备分类bom树的选择，重新查询筛选bom树
  selfDeviceCategoryId.value = row.id
  await getTree()
}

/** 提交表单 */

const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    // 赋值设备分类id
    formData.value.deviceCategoryId = selfDeviceCategoryId.value
    const data = formData.value as unknown as BomApi.BomVO
    if (formType.value === 'create') {
      await BomApi.createBomNode(data)
      message.success(t('common.createSuccess'))
    } else {
      await BomApi.updateBomNode(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceCategoryId: localCategoryId.value,
    title: '',
    parentId: undefined,
    name: undefined,
    sort: 0,
    type: undefined,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}

/** 获得 设备分类 树 **/
const getDeviceCategoryTree = async () => {
  deviceCategoryTree.value = []
  const res = await DeviceCategoryApi.IotProductClassifyApi.getSimpleProductClassifyList()
  let bom: Tree = { id: 0, name: '顶级Bom', children: [] }
  bom.children = handleTree(res)
  deviceCategoryTree.value.push(bom)
}

/** 获得 Bom 树 */
const getTree = async () => {
  bomTree.value = []
  queryParams.deviceCategoryId = selfDeviceCategoryId.value;
  const data = await BomApi.getSimpleBomList(queryParams)
  let bom: Tree = { id: 0, name: '顶级Bom', children: [] }
  bom.children = handleTree(data)
  bomTree.value.push(bom)
  firstLevelKeys.value = bomTree.value.map(node => node.id);
}

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