<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading">
      <el-form-item label="队伍" prop="deptId">
        <el-tree-select
          clearable
          v-model="formData.deptId"
          :data="deptList2"
          :props="defaultProps"
          :check-strictly="false"
          node-key="id"
          filterable
          placeholder="请选择所在队伍" />
      </el-form-item>

      <el-form-item label="观察日期" prop="observationDate">
        <el-date-picker
          v-model="formData.observationDate"
          type="date"
          value-format="x"
          placeholder="选择观察日期"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="soc类型" prop="socClass">
        <el-tree-select
          clearable
          v-model="formData.socClass"
          :data="socList"
          :props="defaultProps"
          :check-strictly="false"
          node-key="id"
          filterable
          multiple
          placeholder="请选择soc类型" />
      </el-form-item>

      <el-form-item label="姓名" prop="userName">
        <el-input v-model="formData.userName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="岗位" prop="post">
        <el-input v-model="formData.post" placeholder="请输入岗位" />
      </el-form-item>

      <el-form-item label="详细描述" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入详细描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { IotSocSummaryApi } from '@/api/pms/qhse/index'
import { IotSocApi } from '@/api/pms/qhse/index'
import { defaultProps } from '@/utils/tree'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
/** SOC卡汇总 表单 */
defineOptions({ name: 'IotSocSummaryForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList2 = ref<Tree[]>([]) // 树形结构
const socList = ref<Tree[]>([]) // soc类型列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  project: undefined,
  observationDate: undefined,

  socClass: [],
  userName: undefined,
  post: undefined,
  deptId: undefined,
  remark: undefined
})
const formRules = reactive({
  observationDate: [{ required: true, message: '观察日期不能为空', trigger: 'blur' }],

  socClass: [{ required: true, message: 'soc类型不能为空', trigger: 'blur' }],
  className: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '队伍不能为空', trigger: 'change' }],
  userName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  post: [{ required: true, message: '岗位不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (!socList.value.length) {
    const data = await IotSocApi.getSocList({})
    socList.value = handleTree(data)
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await IotSocSummaryApi.getIotSocSummary(id)
      formData.value = {
        ...data,

        socClass: normalizeSocClasses(data.socClass, socList.value)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,

      socClasses: formData.value.socClass,
      socClass: undefined
    }
    if (formType.value === 'create') {
      await IotSocSummaryApi.createIotSocSummary(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotSocSummaryApi.updateIotSocSummary(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// const handleNodeClick = (data: Tree) => {
//   if (data.type !== '3') {
//     ElMessage.warning('只能选择队伍')
//     return
//   }
// }

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    project: undefined,
    observationDate: undefined,

    socClass: [],
    className: undefined,
    userName: undefined,
    post: undefined,
    deptId: undefined,
    remark: undefined,
    deptName: undefined
  }
  formRef.value?.resetFields()
}

const normalizeSocClasses = (value: unknown, tree: Tree[] = []): (string | number)[] => {
  const values = Array.isArray(value)
    ? value
    : typeof value === 'string'
      ? value
          .split(',')
          .map((item) => item.trim())
          .filter(Boolean)
      : value === null || value === undefined || value === ''
        ? []
        : [value as string | number]

  const idMap = new Map<string, string | number>()
  const stack = [...tree]
  while (stack.length) {
    const node = stack.shift() as any
    if (!node) continue
    idMap.set(String(node.id), node.id)
    if (Array.isArray(node.children) && node.children.length) {
      stack.push(...node.children)
    }
  }

  return values.map((item) => idMap.get(String(item)) ?? item)
}

const serializeSocClasses = (value: unknown): string => {
  if (Array.isArray(value)) {
    return value
      .map((item) => String(item).trim())
      .filter(Boolean)
      .join(',')
  }
  if (typeof value === 'string') return value
  if (value === null || value === undefined) return ''
  return String(value)
}

onMounted(async () => {
  deptList2.value = handleTree(await DeptApi.getSimpleDeptList())

  const data = await IotSocApi.getSocList({})
  socList.value = handleTree(data)
})
</script>
