<template>
  <el-dialog width="600px" append-to-body :title="title" v-model="open">
    <el-form label-width="100px" ref="formRef" :model="form" :rules="rules">
      <el-form-item label="分类名称" prop="contentName">
        <el-input
          placeholder="请输入分类名称"
          :disabled="disabled"
          v-model="form.contentName"
        />
      </el-form-item>
      <el-form-item label="上级分类" prop="suprContentOnum">
        <el-tree-select
          check-strictly
          value-key="contentOnum"
          placeholder="请选择上级分类"
          :default-expand-all="true"
          :disabled="disabled"
          :clearable="true"
          :data="localDirectoryTree"
          :props="{
            value: 'contentOnum',
            label: 'contentName',
            children: 'children',
          }"
          v-model="form.suprContentOnum"
        >
        </el-tree-select>
      </el-form-item>
      <el-form-item label="负责人" prop="contentPic">
        <el-input
          placeholder="请输入负责人"
          :disabled="disabled"
          v-model="form.contentPic"
        />
      </el-form-item>
      <el-form-item label="分类简介" prop="contentIntr">
        <el-input
          placeholder="请输入分类简介"
          type="textarea"
          :disabled="disabled"
          :rows="8"
          v-model="form.contentIntr"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" :disabled="disabled" @click="submitForm"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, nextTick } from 'vue'
import {
  getDirectory,
  addDirectory,
  updateDirectory,
  getDirectoryAsset,
} from '@/api/metadataConfig/directory'

const props = defineProps({
  directoryTree: {
    type: Array,
    required: true,
  },
})

const filterTree = (tree, conditionFn) => {
  return tree
    .map((node) => {
      // 递归处理每个节点的子节点
      const filteredChildren = node.children
        ? filterTree(node.children, conditionFn)
        : []
      // 根据条件判断是否保留当前节点
      if (conditionFn(node)) {
        // 返回新的节点结构，保留符合条件的子节点
        return {
          ...node,
          children: filteredChildren,
        }
      }
      // 如果不符合条件，返回 null，不加入到最终结果中
      return null
    })
    .filter(Boolean) // 移除值为 null 的项
}

const localDirectoryTree = computed(() => {
  const tree = props.directoryTree
  return filterTree(tree, (node) => node.contentOnum && !node.astOnum) // 过滤资产子节点
})

const title = ref('')
const open = ref(false)
const disabled = ref(false)
const { proxy } = getCurrentInstance()
const form = ref({})
const rules = ref({
  contentName: [
    { required: true, message: '分类名称不能为空', trigger: 'blur' },
  ],
  suprContentOnum: [
    { required: true, message: '上级分类不能为空', trigger: 'blur' },
  ],
})

const formRef = ref(null)
const openDialog = (row) => {
  open.value = true
  form.value = {
    contentName: undefined,
    suprContentOnum: undefined,
    contentPic: undefined,
    contentStat: '1', // 0-废弃，1-有效，2-停用
    contentIntr: undefined,
    children: [],
  }
  if (row.contentOnum || row.suprContentOnum) {
    form.value = {
      ...form.value,
      ...row,
      assets:
        row.children &&
        row.children.length &&
        row.children.find((i) => i.astOnum)
          ? [...row.children].map((i) => i.astOnum)
          : [], // 新增冗余字段来暂存资产编号
    }
  }
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

const addTreeNodeId = (tree) => {
  return tree.map((node, index) => {
    return {
      ...node,
      id: node.dataAssetCatalogAstno || index,
      children:
        node.children && node.children.length
          ? addTreeNodeId(node.children)
          : [],
    }
  })
}



const emit = defineEmits(['onSuccess'])
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const children = form.value.assets.reduce((arr, cur) => {
        const item = form.value.children.find((i) => i.astOnum === cur)
        if (!item) {
          arr.push({
            contentOnum: form.value.contentOnum,
            astOnum: cur,
          })
        } else {
          arr.push(item)
        }
        return arr
      }, [])
      form.value = {
        ...form.value,
        children,
      }
      const request = form.value.contentOnum ? updateDirectory : addDirectory
      request(form.value).then((response) => {
        proxy.$modal.msgSuccess(
          form.value.contentOnum ? '修改成功' : '新增成功'
        )
        open.value = false
        emit('onSuccess')
      })
    }
  })
}

const cancel = () => {
  open.value = false
}

defineExpose({ title, disabled, openDialog })
</script>
