<script setup name="Classification">
import { ElMessageBox, ElMessage } from 'element-plus'
import { ref, toRefs, reactive, getCurrentInstance, proxyRefs, onMounted, watch, provide, nextTick } from 'vue'
import useAppStore from '@/store/modules/app'
import TreeFilter from './modules/TreeFilter.vue'
import BasicInfoTab from './modules/BasicInfoTab.vue'
import TableInfoTab from './modules/TableInfoTab.vue'
import StructureTab from './modules/StructureTab.vue'
import EncryptionTab from './modules/EncryptionTab.vue'
import { changeRoute } from '@/utils/switchRoute'
import { useRouter,useRoute } from 'vue-router'
import { query, getClassifyEnable, getGlobalOriginalConfig, changeGlobalOriginalConfig, queryDatasystemInfo, 
  queryShemas, queryTables, querytableInfo, getfield,
  save
} from '@/api/classification/classification.js'
const route = useRoute()
// const permissionStore = usePermissionStore()
const router = useRouter()
const appStore = useAppStore()
// 字段加密信息子组件列表
const encryptionTabRef = ref()
const projectId = ref('')
// 树形数据
const treeData = ref([])
// 基本信息数据(当前选中的数据源)
const basicInfoData = ref({})
// 当前激活的Tab
const activeTab = ref('basic')
// 当前选中的节点数据
const currentNodeData = ref(null)
provide('currentNodeData', currentNodeData)
const currentNodeLevel = computed(() => {
  if (!currentNodeData.value) return 1
  if (currentNodeData.value.type === 'system') return 1
  if (currentNodeData.value.type === 'database') return 2
  if (currentNodeData.value.type === 'category') return 3
  if (currentNodeData.value.type === 'table') return 4
  return 0
})

// 当前表结构数据 (匹配图片中的gen_table结构) 
const currentTableStructure = ref([])


// 监听 currentNodeLevel 和 currentNodeData，一级节点时自动查详情
watch([currentNodeLevel, currentNodeData, activeTab], async ([level, node, tab]) => {
  if (level === 1 && node && tab === 'basic') {
    const res = await queryDatasystemInfo({ dataSystemId: node.tid, projectId: projectId.value })
    if (res && res.data) {
      // 你可以将结果赋值到 basicInfoData 或其他变量
      basicInfoData.value = { ...basicInfoData.value, ...res.data }
    }
  }

  // 查询表基本信息
  if (level === 4 && node && tab === 'basic') {
    console.log('查询表基本信息', node)
    const res = await querytableInfo({
      tableName: node.label,
      dataSystemId: node.dataSystemId,
      schema: node.schema,
      flag: '1',
      projectId: projectId.value
    })
    if (res && res.data) {
      // 你可以将结果赋值到 basicInfoData 或其他变量
      basicInfoData.value = {...res.data }
    }
  }

  // 查询表字段信息
  if (level === 4 && node && tab === 'structure') {
    console.log('查询表字段信息', node)
    const res = await getfield({
      tablename: node.label,
      datasystemid: node.dataSystemId,
      schema: node.schema,
      taskid: ''
    })
    if (res && res.data) {
      // 你可以将结果赋值到 basicInfoData 或其他变量
      currentTableStructure.value = res.data || []
    }
  }

  //查询字段加密配置
  if (level === 4 && node && tab === 'encryption') {
    nextTick(() => {
      encryptionTabRef.value.getTableData()
    })
  }
})

onMounted(async () => {
  projectId.value = sessionStorage.getItem('projectId') || ''
  if (projectId.value) {
    // 1. 查询数据源列表
    const res = await query({ project_id: projectId.value })
    if (res && res.data) {
      treeData.value = res.data.map(item => ({
        ...item,
        label: item.sysname,
        type: 'system',
        icon: getNodeIcon(item.dbtype),
        children: [
        ]
      }))
      // 赋值触发监听，默认查询第一个数据源的基本信息
      currentNodeData.value = treeData.value[0]
    }
    // 查询解密插件配置
    const configRes = await getGlobalOriginalConfig({ projectId: projectId.value })
    console.log('解密插件配置', configRes)
    if (configRes) {
      enableDecryptionPlugin.value = configRes.data === 1
    }
  }
})

// 根据节点类型获取图标
const getNodeIcon = (type) => {
  return appStore.DATABASE_ICONS[type]
}


// 树节点点击处理
const handleNodeClick = async (data) => {
    currentNodeData.value = data
  // 点击一层系统数据，查 schemas
  if (data.type === 'system') {
      activeTab.value = 'basic'
      const res = await queryShemas({
        dataSystemId: data.tid,
        dataType: data.dbtype,
        projectid: projectId.value
      })
      if (res && res.data) {
        data.children = res.data.map(schema => ({
          id: uuid(),
          dataSystemId: data.tid,
          dbtype: data.dbtype,
          projectid: projectId.value,
          schema: schema.text,
          type: 'database',
          label: schema.text,
          parent: data,
          icon: getNodeIcon('DATABASE'),
          children: []
        }))
        treeData.value = [...treeData.value] // 触发视图更新
      }
  }

  // 点击二层数据库,构造一层
  if(data.type === 'database'){
   data.children = [
      {
        id: uuid(),
        label: '表',
        type: 'category',
        dataSystemId: data.dataSystemId,
        dbtype: data.dbtype,
        projectid: data.projectid,
        schema: data.schema,
       parent: data,
       icon: getNodeIcon('queryTables'),
        children: []
      }
   ]
  }


  // 点击三层 category，查表
  if (data.type === 'category') {
    const res = await queryTables({
      dataSystemId: data.dataSystemId,
      schema: data.schema
    })
    if (res && res.data) {
      data.children = res.data.map(table => ({
        dataSystemId: data.dataSystemId,
        dbtype: data.dbtype,
        projectid: data.projectid,
        schema: data.schema,
        realName: table.realName,
        showName: table.showName,
        id: uuid(),
        label: table.showName,
        type: 'table',
        icon: getNodeIcon('TABLE'),
        parent: data
      }))
      treeData.value = [...treeData.value]
    }
  }
}

// 是否启用解密插件
const enableDecryptionPlugin = ref(true)

// 解密插件变更处理
const handleDecryptChange = async (val) => {
  try {
    const res = await changeGlobalOriginalConfig({ projectId: projectId.value, status: val ? '1' : '0' })
    if (!res || res.code !== 'POP_00014' || !res.flag) {
      // 如果修改失败，回退到之前的值
      enableDecryptionPlugin.value = !val
      ElMessageBox.alert('修改解密插件配置失败，请重试', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    })  
    }
  } catch (e) {
    // 如果修改失败，回退到之前的值
    enableDecryptionPlugin.value = !val
    // 可根据需要添加错误提示
    ElMessageBox.alert('修改解密插件配置失败，请重试', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    })
  }
}

function pageProjectManage() {
  changeRoute()
  router.push({
    path: '/project/Project'
  })
}


const getBreadcrumb = () => {
  const result = []
  let node = currentNodeData.value
  while (node) {
    result.unshift({ label: node.label })
    node = node.parent
  }
  // 如果没有选中节点，默认显示系统
  if (result.length === 0) {
    result.push({ label: treeData.value.length > 0 ? treeData.value[0].label : '数据源' })
  }
  return result
}

// 生成唯一标识符
function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

</script>
<template>
  <div class="app-container scroller">
    <PageTitle :back="true" @back="pageProjectManage" >
      <template #title>
        返回项目管理
      </template>
    </PageTitle>

    <div class="app-container__body">
      <div class="flex-container content-container">
        <div class="left">
            <TreeFilter :tree-data="treeData" @node-click="handleNodeClick"/>
        </div>
        <div class="right flex1">
          <el-card class="image-card">
              <div class="header-section">
                <div class="breadcrumb flex-container justify-between align-center">
                  <el-breadcrumb separator="/">
                    <el-breadcrumb-item v-for="(item, $index) in getBreadcrumb()" :key="$index">
                      {{ item.label }}
                    </el-breadcrumb-item>
                  </el-breadcrumb>
                  <el-checkbox v-model="enableDecryptionPlugin" @change="handleDecryptChange">是否启用解密插件</el-checkbox>
                </div>
              </div>

              <!-- Tab区域 -->
              <div class="tab-section">
                <el-tabs v-model="activeTab">
                  <!-- 基本信息Tab -->
                  <el-tab-pane label="基本信息" name="basic">
                    <BasicInfoTab 
                      :node-data="basicInfoData"
                      v-if="activeTab === 'basic' &&  [1,2,3].includes(currentNodeLevel)"
                    />

                    <!-- 表信息Tab -->
                    <TableInfoTab 
                      :node-data="basicInfoData"
                      v-if="activeTab === 'basic' && currentNodeLevel === 4"
                    />
                  </el-tab-pane>

                  <!-- 数据结构Tab (仅4级节点显示) -->
                  <el-tab-pane label="数据结构" name="structure" v-if="currentNodeLevel === 4">
                    <StructureTab 
                      :table-data="currentTableStructure"
                      v-if="activeTab === 'structure'"
                    />
                  </el-tab-pane>

                  <!-- 字段加密配置Tab (仅4级节点显示) -->
                  <el-tab-pane label="字段加密配置" name="encryption" v-if="currentNodeLevel === 4">
                    <EncryptionTab 
                      ref="encryptionTabRef"
                      v-if="activeTab === 'encryption'"
                    />
                  </el-tab-pane>
                </el-tabs>
              </div>
          </el-card>   
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.flex-container { 
  display: flex;
}

.align-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.flex1 {
  flex: 1;
}
.content-container {
  .left {
    .tree-container {
      width: 300px;
      overflow-y: auto; // 内容超出滚动
    }
  }
  .right {
    margin-left: var(--container-pd);
    overflow: hidden;
  }
}
</style>

