<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="t('bomList.superiorBOM')" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="bomTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          :placeholder="t('bomList.nameHolder')"
          value-key="bomId"
        />
      </el-form-item>
      <el-form-item :label="t('bomList.bomNode')" prop="name">
        <el-input v-model="formData.name" :placeholder="t('bomList.nodeHolder')" />
      </el-form-item>
      <el-form-item :label="t('bomList.superiorBOM')" 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="t('bomList.sort')" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" controls-position="right" />
      </el-form-item>
      <el-form-item :label="t('bomList.status')" prop="status">
        <el-select v-model="formData.status" clearable :placeholder="t('bomList.status')">
          <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">{{t('iotMaintain.ok')}}</el-button>
      <el-button @click="dialogVisible = false">{{t('iotMaintain.cancel')}}</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/devicebom'
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: 'BomFormDevice' })
const props = defineProps({
  deviceId: Number
})
// 从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,
  deviceId: props.deviceId,
  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,
  deviceId: undefined,
  deviceCategoryId: localCategoryId.value
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 获取store中的设备分类id

  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获得 设备分类树
  // await getDeviceCategoryTree()
  // 获得 bom 树
  await getTree()
  console.log('open方法执行了！')
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BomApi.IotDeviceBomApi.getIotDeviceBom(id)
    } 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
  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.IotDeviceBomVO
    if (formType.value === 'create') {
      data.deviceId = props.deviceId
      await BomApi.IotDeviceBomApi.createIotDeviceBom(data)
      message.success(t('common.createSuccess'))
    } else {
      await BomApi.IotDeviceBomApi.updateIotDeviceBom(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 device: Tree = { id: 0, name: '顶级设备分类', children: [] }
//   device.children = handleTree(res)
//   deviceCategoryTree.value.push(device)
// }

/** 获得 Bom 树 */
const getTree = async () => {
  bomTree.value = []
  queryParams.deviceId = props.deviceId
  const data = await BomApi.IotDeviceBomApi.getIotDeviceBomSimple(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>
