<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="640px" :close-on-click-modal="false">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      size="default"
      class="bom-form">
      <el-form-item label="设备分类" prop="deviceCategoryId">
        <el-tree-select
          v-model="formData.deviceCategoryId"
          :data="deviceCategoryTree"
          :props="defaultProps"
          check-strictly
          :default-expanded-keys="deviceCategoryExpandedKeys"
          placeholder="请选择设备分类"
          value-key="id"
          filterable
          clearable
          size="default"
          class="w-full"
          @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
          filterable
          clearable
          placeholder="请选择上级BOM"
          value-key="bomId"
          size="default"
          class="w-full" />
      </el-form-item>
      <el-form-item label="BOM节点名称" prop="name">
        <lang-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"
          size="default"
          class="w-full" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="formData.status"
          clearable
          placeholder="请选择状态"
          size="default"
          class="w-full">
          <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" size="default" :loading="formLoading" @click="submitForm">
        确 定
      </el-button>
      <el-button size="default" :disabled="formLoading" @click="dialogVisible = false">
        取 消
      </el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, findPath, 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<number | undefined>() // 通过store存储的设备分类id 由父组件传递过来
const selfDeviceCategoryId = ref<number | undefined>() // 当前页面定义的 设备分类id
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref<'create' | 'update' | ''>('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceCategoryId: localCategoryId.value,
  title: '',
  parentId: 0,
  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: 'change' }],
  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<Tree[]>([]) // 设备分类树
const deviceCategoryExpandedKeys = ref<Array<number | string>>([])

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

/** 打开弹窗 */
const open = async (type: string, id?: number, parentId?: number, deviceCategoryId?: number) => {
  dialogVisible.value = true
  // 获取store中的设备分类id
  // 优先使用传入的设备分类ID
  const targetCategoryId = deviceCategoryId || treeStore.selectedId
  // localCategoryId.value = treeStore.selectedId;
  // selfDeviceCategoryId.value = treeStore.selectedId;
  localCategoryId.value = targetCategoryId || localCategoryId.value
  selfDeviceCategoryId.value = targetCategoryId || selfDeviceCategoryId.value

  dialogTitle.value = t('action.' + type)
  formType.value = type as 'create' | 'update'
  resetForm()
  // 获得 设备分类树
  await getDeviceCategoryTree()
  // 获得 bom 树
  await getTree()
  if (type === 'create') {
    formData.value.parentId = parentId ?? 0
    formData.value.deviceCategoryId = selfDeviceCategoryId.value
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BomApi.getBom(id)
      selfDeviceCategoryId.value = formData.value.deviceCategoryId
      deviceCategoryExpandedKeys.value = getDeviceCategoryExpandedKeys(
        formData.value.deviceCategoryId
      )
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 处理 设备分类 树 被点击 */
const handleDeviceCategoryTreeNodeClick = async (row: { [key: string]: any }) => {
  emit('node-click', row)
  // 清空设备分类bom树的选择，重新查询筛选bom树
  selfDeviceCategoryId.value = row.id
  formData.value.deviceCategoryId = row.id
  formData.value.parentId = 0
  deviceCategoryExpandedKeys.value = getDeviceCategoryExpandedKeys(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: selfDeviceCategoryId.value,
    title: '',
    parentId: 0,
    name: undefined,
    sort: 0,
    type: undefined,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}

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

const getDeviceCategoryExpandedKeys = (deviceCategoryId?: number | string | null) => {
  if (deviceCategoryId === undefined || deviceCategoryId === null) {
    return deviceCategoryTree.value.map((node) => node.id)
  }

  const path = findPath<Tree>(deviceCategoryTree.value, (node) => node.id === deviceCategoryId)
  if (Array.isArray(path)) {
    return path.map((node) => node.id)
  }

  return deviceCategoryTree.value.map((node) => node.id)
}

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

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

<style lang="scss" scoped>
.bom-form {
  padding: 8px 8px 0;
}
</style>
