<template>
  <div class="dictiontary-list-detail child-router">
    <!-- 上方一整块：筛选和操作按钮 -->
    <el-row class="main-content">
      <el-col :span="24">
        <TableHeader>
          <template #select>
            <el-form-item label="">
              <el-page-header @back="$emit('close')">
                <template #content>
                  <span class="text-large font-600 mr-3">报告字典管理</span>
                </template>
              </el-page-header>
            </el-form-item>
            <el-form-item label="筛选数据">
              <el-input
                style="width: 240px"
                v-model="tableStore.table.params.searchValue"
                clearable
                placeholder="请输入关键字筛选"
                maxlength="32"
                show-word-limit
              />
            </el-form-item>
          </template>
          <template #operation>
            <el-button :icon="Plus" type="primary" @click="addTemplate">新增配置项</el-button>
          </template>
        </TableHeader>
      </el-col>
    </el-row>

    <!-- 下方左右两块：左侧树 + 右侧表格 -->
    <el-row :gutter="20" class="main-content mt20">
      <!-- 左侧树 -->
      <el-col :span="6">
        <div class="tree-container">
          <el-tree
            @node-click="(node, data, event) => handleNodeClick(node, data)"
            :expand-on-click-node="false"
            :highlight-current="true"
            :data="TreeData"
            node-key="id"
            :default-expanded-keys="treeExpandData"
            :props="defaultProps"
            ref="tree"
          ></el-tree>
        </div>
      </el-col>

      <!-- 右侧表格 -->
      <el-col :span="18">
        <Table ref="tableRef" />
      </el-col>
    </el-row>

    <!-- 新增弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="30%"
      @close="closeDialog"
    >
      <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="父节点:" prop="pid">
          <el-tree-select
            v-model="form.pid"
            style="width: 100%"
            placeholder="请选择父节点"
            :data="TreeData"
            node-key="id"
            :props="defaultProps"
            clearable
            :disabled="isEditMode"
             check-strictly
          />
        </el-form-item>
        <el-form-item label="名称:" prop="name" class="top">
          <el-input v-model.trim="form.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="描述:" prop="reportDescribe" class="top">
          <el-input
            type="textarea"
            placeholder="请输入描述"
            v-model.trim="form.reportDescribe"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addFn">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted, provide } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { ElMessage } from 'element-plus'
import {
  updateDict,
  addDict,
  deleteDict,
  getDictTree
} from '@/api/system-boot/ReportTemplate'

// 弹出框是否可见
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref('新增配置项')
const formRef = ref()
const props = defineProps({
  type: {
    type: Number,
    default: undefined
  },
  treeData: {
    type: Array,
    default: () => []
  }
})
const TreeData = computed(() => props.treeData)
const treeExpandData = ref([])
const tree = ref(null)

// Administration.vue
const emit = defineEmits(['refreshTree'])

// 刷新左侧树数据
const refreshTreeData = () => {
  emit('refreshTree') // 触发父组件刷新树数据
}

const formData = reactive({
  searchValue: '',
  id: 0,
  type: props.type
})

const form = reactive({
  id: 0,
  name: '',
  reportDescribe: '',
  pid: '',
  sort: 0,
  type: props.type
})

const defaultProps = {
  children: 'children',
  label: 'reportDescribe',
  value: 'id' // 指定节点的值字段
}

const rules = {
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  reportDescribe: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
  pid: [{ required: true, message: '请选择父节点', trigger: 'change' }]
}

// 判断是否为编辑模式
const isEditMode = computed(() => dialogTitle.value === '编辑配置项')

const tableStore = new TableStore({
  url: '/system-boot/reportDict/getReportDictList',
  method: 'POST',
  showPage: false,
  column: [
    { title: '配置项名称', field: 'name' },
    { title: '配置项描述', field: 'reportDescribe' },
    { title: '上级节点', field: 'pidName' },
    {
      title: '操作',
      fixed: 'right',
      width: '180',
      render: 'buttons',
      buttons: [
        {
          title: '编辑',
          type: 'primary',
          icon: 'el-icon-EditPen',
          render: 'basicButton',
          click: row => {
            dialogTitle.value = '编辑配置项'
            dialogVisible.value = true
            Object.assign(form, {
              id: row.id,
              name: row.name,
              reportDescribe: row.reportDescribe,
              pid: row.pid,
              sort: row.sort,
              type: props.type
            })
          }
        },
        {
          title: '删除',
          type: 'danger',
          icon: 'el-icon-Delete',
          render: 'confirmButton',
          popconfirm: {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            confirmButtonType: 'danger',
            title: '确定删除该字典类型吗？'
          },
          click: row => {
            let data = {
              id: row.id
            }
            deleteDict(data).then(() => {
              ElMessage.success('删除成功')
              tableStore.index()
              refreshTreeData()
            })
          }
        }
      ]
    }
  ],
  resetCallback: () => {
    tableStore.table.params.id = formData.id
  }
})

tableStore.table.params.id = 0
tableStore.table.params.searchValue = ''
tableStore.table.params.type = props.type
provide('tableStore', tableStore)

const setDefaultExpandedKeys = (treeData: any[]) => {
  const firstLevelIds = treeData.map(item => item.id)
  treeExpandData.value = firstLevelIds
}

// 默认选中第一个节点并触发事件
const selectFirstNode = () => {
  if (props.treeData.length > 0 && tree.value) {
    const firstNodeId = props.treeData[0].id
    tree.value.setCurrentKey(firstNodeId)
    formData.id = firstNodeId
    const firstNode = props.treeData[0]
    handleNodeClick(firstNode)
  }
}

// 监听 treeData 变化，自动设置默认展开
watch(
  () => props.treeData,
  (newVal) => {
    if (newVal.length > 0) {
      setDefaultExpandedKeys(newVal)
      nextTick(() => {
        selectFirstNode()
      })
    }
  },
  { immediate: true }
)

// 处理节点点击事件
const handleNodeClick = (node: any) => {
  formData.id = node.id
  tableStore.table.params.id = node.id
  tableStore.table.params.type = props.type
  tableStore.index()
}

const addTemplate = () => {
  dialogTitle.value = '新增配置项'
  dialogVisible.value = true
  Object.assign(form, {
    id: 0,
    name: '',
    reportDescribe: '',
    pid: '',
    sort: 0,
    type: props.type
  })
}

const addFn = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (dialogTitle.value === '编辑配置项') {
          await updateDict(form)
          ElMessage.success('编辑成功')
        } else {
          await addDict(form)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        tableStore.index()
        refreshTreeData()
      } catch (error) {
        ElMessage.error(dialogTitle.value === '编辑配置项' ? '编辑失败' : '新增失败')
      }
    }
  })
}

const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

onMounted(() => {
  selectFirstNode()
})
</script>

<style scoped>
.dictiontary-list-detail {
  padding: 10px;
  background-color: #ffffff;
  overflow: hidden;
}

.main-content {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}



.tree-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  height: 100%;
}

:deep(.el-tree) {
  height: 100%;
  overflow-y: auto;
}
</style>