<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出"
    width="500px"
    :before-close="handleClose"
  >
    <div class="export-dialog">
      <!-- 树形选择器 -->
      <el-tree
        ref="treeRef"
        :data="treeData"
        node-key="id"
        show-checkbox
        :props="defaultProps"
        :load="loadNode"
        lazy
        :default-expand-all="false"
        @check="handleNodeCheck"
      />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleBackup">加密规则备份</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getEncryptExcel,
  checkEncryptExcel,
  exportToExcel,
  tdatasourceQuery,
  queryShemasmodifysubsettask,
  rowsensitivelevelType
} from '@/api/project'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectId: {
    type: String,
    required: true
  },
  exportProjectName: {
    type: String,
    default: '导出'
  }
})

const emit = defineEmits(['update:visible', 'confirm', 'backup'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 树形数据
const treeData = ref([])
const treeRef = ref(null)
const checkedNodes = ref([])

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'name',
  isLeaf: 'isLeaf'
}

// 数据库图标映射
const DATABASE_ICONS = {
  MYSQL: 'icon-mysql',
  ORACLE: 'icon-oracle',
  SQLSERVER: 'icon-sqlserver',
  POSTGRESQL: 'icon-postgresql',
  DATABASE: 'icon-database',
  queryTables: 'icon-table',
  TABLE: 'icon-table'
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 生成备份文件名
const exportBackUpName = (fileType) => {
  return `${props.exportProjectName}_encrule_backup_${formatDate(new Date())}.${fileType}`
}

// 生成导出文件名
const exportFiledNameFormat = () => {
  return `${props.exportProjectName}_${formatDate(new Date())}.xlsx`
}

// 加密规则备份
const handleBackup = async () => {
  try {
    const params = {
      id: props.projectId,
      project: props.exportProjectName
    }

    // 获取加密Excel数据
    const res = await getEncryptExcel({ project: params })
    
    // 检查加密Excel类型
    const par = await checkEncryptExcel({ project: params })
    
    // 创建下载链接
    const blob = new Blob([res.data], {
      type: 'application/vnd.ms-excel,charset=utf-8'
    })
    const elink = document.createElement('a')
    elink.href = URL.createObjectURL(blob)
    elink.download = exportBackUpName(par.data.filetype)
    document.body.appendChild(elink)
    elink.click()
    document.body.removeChild(elink)
    
    ElMessage.success('导出成功！')
    emit('backup')
  } catch (error) {
    console.error('加密规则备份失败:', error)
    ElMessage.error('加密规则备份失败')
  }
}

// 节点选中处理
const handleNodeCheck = (node, checkedNodes) => {
  // 保存选中的节点
  checkedNodes.value = checkedNodes.checkedNodes
}

// 动态加载树节点
const loadNode = async (node, resolve) => {
  try {
    if (node.level === 0) {
      // 第一级：加载数据源
      const res = await tdatasourceQuery({ 
        project_id: props.projectId 
      })
      
      const dataSources = res.data.map(item => ({
        id: item.tid,
        name: item.sysname,
        type: 'datasource',
        dbtype: item.dbtype,
        tid: item.tid,
        icon: DATABASE_ICONS[item.dbtype] || DATABASE_ICONS.DATABASE,
        isLeaf: false,
        expand: false
      }))
      
      resolve(dataSources)
    } 
    else if (node.level === 1) {
      // 第二级：加载Schema
      const res = await queryShemasmodifysubsettask({
        dataType: node.data.dbtype,
        dataSystemId: node.data.tid,
        projectid: props.projectId
      })
      
      if (res.data && res.data.length > 0) {
        const schemas = res.data.map(item => ({
          id: `${node.data.tid}_${item.value}`,
          name: item.text,
          type: 'schema',
          dataSystemId: node.data.tid,
          value: item.value,
          icon: DATABASE_ICONS.DATABASE,
          isLeaf: false,
          expand: false,
          parent: node.data
        }))
        resolve(schemas)
      } else {
        resolve([])
      }
    } 
    else if (node.level === 2) {
      // 第三级：加载表分类
      resolve([{
        id: `${node.data.id}_tables`,
        name: '表',
        type: 'queryTables',
        dataSystemId: node.data.dataSystemId,
        schema: node.data.value,
        icon: DATABASE_ICONS.queryTables,
        isLeaf: false,
        expand: false,
        parent: node.data
      }])
    } 
    else if (node.level === 3) {
      // 第四级：加载具体表
      const res = await rowsensitivelevelType(`${node.data.type}`, {
        dataSystemId: node.data.dataSystemId,
        schema: node.data.schema
      })
      
      const tables = res.data.map(item => ({
        id: `${node.data.id}_${item.realName}`,
        name: item.showName,
        realName: item.realName,
        type: 'table',
        datasystem_id: node.data.dataSystemId,
        schema: node.data.schema,
        icon: DATABASE_ICONS.TABLE,
        isLeaf: true,
        parent: node.data
      }))
      
      resolve(tables)
    } 
    else {
      resolve([])
    }
  } catch (error) {
    console.error('加载树节点失败:', error)
    ElMessage.error('加载数据失败')
    resolve([])
  }
}

// 确认导出
const handleConfirm = async () => {


  try {
    const params = {
      id: props.projectId,
      project: props.exportProjectName
    }
    
    let dataSourceIdList = []
    let schemalist = []
    let tableList = []
    let currentSourceId = ''
    let currentSchema = ''
  

    checkedNodes.value = treeRef.value.getCheckedNodes()
      console.log('checkedNodes',checkedNodes.value)
    // return
    // 处理选中的节点
    checkedNodes.value.forEach(item => {
      switch (item.type) {
        case 'datasource':
          currentSourceId = item.id
          dataSourceIdList.push(item.tid)
          console.log('dataSourceIdList',dataSourceIdList)
          break
        case 'schema':
          currentSchema = item.value + item.dataSystemId
          if (item.dataSystemId !== currentSourceId) {
            schemalist.push({
              datasystemid: item.dataSystemId,
              schema: item.value
            })
          }
           console.log(2)
          break
        case 'table':
          if (currentSchema !== item.parent.value + item.datasystem_id) {
            tableList.push({
              datasystemid: item.datasystem_id,
              schema: item.parent.value,
              tablename: item.realName
            })
          }
          break
      }
    })


    // 调用导出API
    const res = await exportToExcel({
      project: params,
      dataSourceIdList,
      schemalist,
      tableList
    })

    // 创建下载链接
    const blob = new Blob([res], {
      type: 'application/vnd.ms-excel,charset=utf-8'
    })
    const elink = document.createElement('a')
    elink.href = URL.createObjectURL(blob)
    elink.download = exportFiledNameFormat()
    document.body.appendChild(elink)
    elink.click()
    document.body.removeChild(elink)

    ElMessage.success('导出成功！')
    emit('confirm')
    dialogVisible.value = false
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 关闭前处理
const handleClose = (done) => {
  done()
}

// 监听项目ID变化，初始化树形数据
watch(() => props.projectId, (newVal) => {
  if (newVal) {
    // 初始化树数据为空数组，由loadNode动态加载
    treeData.value = []
  }
}, { immediate: true })
</script>

<style scoped>
.export-dialog {
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tree) {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.el-tree-node__content) {
  height: 36px;
}
</style>