<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="80%"
    :before-close="handleClose"
    class="strategy-add-dialog"
  >
    <!-- 步骤指示器 -->
    <div class="steps-container">
      <el-steps :active="activeStep" align-center>
        <el-step title="基本信息" />
        <el-step title="规则配置" />
      </el-steps>
    </div>

    <!-- 第一步：基本信息 -->
    <div v-if="activeStep === 1" class="step-content">
      <el-form
        ref="step1FormRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="策略名称" prop="strategyName" required>
          <el-input
            :disabled="dialogType === 'detail'"
            v-model="formData.strategyName"
            placeholder="请输入策略名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input
            :disabled="dialogType === 'detail'"
            v-model="formData.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入策略备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 第二步：规则配置 -->
    <div v-if="activeStep === 2" class="step-content">
      <div class="version-select">
        <span class="label">根据发现版本设置脱敏:</span>
         <span class="label" style="margin-left: 60px;">选择发现版本:</span>
        <el-tree-select
          v-model="selectedVersion"
          :data="editionList"
          :props="treeSelectProps"
          :load="loadCascader"
          lazy
          placeholder="选择发现版本"
          clearable
          style="width: 200px; margin-left: 10px;"
        />

 
      </div>

      <div class="config-container">
        <!-- 左侧树形结构 -->
        <div class="tree-panel">
          <TreeFilter :tree-data="treeData" @node-click="handleNodeClick"/>
        </div>

        <!-- 右侧表格 -->
        <div class="table-panel">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            height="100%"
            v-loading="tableLoading"
          >
            <el-table-column prop="id" label="主键" width="80" align="center" />
            <el-table-column prop="fieldName" label="字段名" min-width="120" />
            <el-table-column prop="comment" label="注释" min-width="150" show-overflow-tooltip />
            <el-table-column prop="dataareaname" label="数据域" min-width="120" />
            <el-table-column prop="rulename" label="脱敏算法" min-width="150" />
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="editField(row)">
                  设置
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="tableData.length === 0 && !tableLoading" class="empty-table">
            <el-empty description="暂无数据" />
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="activeStep === 2" @click="activeStep = 1">上一步</el-button>
        <el-button 
          type="primary" 
          v-if="activeStep === 1"
          @click="handleNextStep"
        >
         下一步
        </el-button>
        <el-button 
          v-if="activeStep === 2"
          type="primary" 
          :loading="saveLoading"
          @click="handleNextStep"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>


  <DesensitizationRuleDialog
    :dataSystemid="dataSystemid"
    :tschemas="schema"
    :dataTableLabel="dataTableLabel"
    :table_field_id="currentFieldData?.columnname"
    ref="desensitizationRuleDialogRef"
    @confirm="handleRuleConfirm"
  />
</template>

<script setup>
import { ref, reactive, watch, computed, nextTick } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'

import DesensitizationRuleDialog from './DesensitizationRuleDialog.vue'

import {
desensitizationruleQuery,
queryversion,
queryShemas,
queryOriginalList,

queryTask,
queryProVersion,
queryTaskVersion,
desensitizationStrategyDetails,
save,
queryDesensitizationTables
} from '@/api/desensitizationStrategy'
import { queryTables,query } from '@/api/classification/classification.js'

import TreeFilter from './TreeFilter.vue'
const props = defineProps({
  title: {
    type: String,
    default: '添加策略'
  },
  strategyId: {
    type: String,
    default: ''
  }
})

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

const dialogVisible = ref(false)
const activeStep = ref(1)
const selectedVersion = ref('')
const tableLoading = ref(false)

// 表单数据
const formData = reactive({
  strategyName: '',
  remarks: ''
})
const step1FormRef = ref()
// 表单验证规则
const formRules = {
  strategyName: [
    { required: true, message: '请填写策略名称', trigger: 'blur' }
  ]
}
const treeSelectProps = {
  // value: 'value',
  // label: 'text',
  // children: 'children',
  // isLeaf: 'leaf'
}
// 版本选项
const editionList = ref([
  {
    value: 'none',
    label: '无版本'
  },
  {
    value: 'v1',
    label: '版本1.0'
  },
  {
    value: 'v2',
    label: '版本2.0'
  }
])
/**
 * 发现版本懒加载
 * @param node 
 * @param resolve 
 */
const loadCascader = async (node, resolve) => {
  try {
    const { value, level } = node
    
    if (level === 0) {
      // 第一级节点已经加载完成，直接返回
      resolve(editionList.value)
      return
    }
    
    let children = []
    
    if (value === 'TaskVersion') {
      // 加载任务列表
      const res = await queryTask({ projectid: sessionStorage.getItem('projectId') })
      children = res.data.map(item => ({
        label: item.text,
        value: item.value,
        loading: false,
        children: [],
        leaf: false
      }))
    } else if (value === 'ProjectVersion') {
      // 加载项目版本
      const res = await queryProVersion({
        projectid: sessionStorage.getItem('projectId'),
        versiontype: 'project'
      })
      if (res.data.versionname && res.data.filename) {
        children = [{
          label: res.data.versionname,
          value: res.data.filename,
          leaf: true
        }]
      }
    } else {
      // 加载任务版本
      const res = await queryTaskVersion({ taskid: value })
      children = res.data.map(item => ({
        label: item.versionname,
        value: item.filename,
        leaf: true
      }))
    }
    
    resolve(children)
  } catch (error) {
    console.error('加载版本数据失败:', error)
    ElMessage.error('加载版本数据失败')
    resolve([])
  }
}
// 树形数据
const treeData = ref([
  // {
  //   id: '1',
  //   label: '若依配测2',
  //   type: 'project',
  //   children: [
  //     {
  //       id: '1-1',
  //       label: 'ry',
  //       children: [
  //         { id: '1-1-1', label: 'gen_table', type: 'table' },
  //         { id: '1-1-2', label: 'gen_table_column', type: 'table' },
  //         { id: '1-1-3', label: 'sys_config', type: 'table' }
  //       ]
  //     }
  //   ]
  // },
  // {
  //   id: '2',
  //   label: '若依测试库2',
  //   type: 'project',
  //   children: [
  //     {
  //       id: '2-1',
  //       label: 'ry_test',
  //       type: 'database',
  //       tableCount: 15,
  //       children: [
  //         { id: '2-1-1', label: 'sys_dept', type: 'table' },
  //         { id: '2-1-2', label: 'sys_dict_data', type: 'table' },
  //         { id: '2-1-3', label: 'sys_dict_type', type: 'table' }
  //       ]
  //     }
  //   ]
  // }
])

// 当前选中的节点数据
const currentNodeData = ref(null)
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
})

const datasystem_id = ref('')
const schema = ref('')



const dataBaseLabel = ref('')
const dataTableLabel = ref('')
const dataTableColumnsLabel = ref('')
const dataSystemid = ref('')
const mapData = ref({})

// 监听 currentNodeLevel 和 currentNodeData，一级节点时自动查详情
watch([currentNodeLevel, currentNodeData], async ([level, node]) => {
  // 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 === 1 && node ) {
    console.log('level1',node)
    datasystem_id.value = node.tid
    dataSystemid.value = node.tid
  }
  if (level === 2 && node ) {
    console.log('level2',node)
    schema.value = node.value
    dataBaseLabel.value = node.label
  }
  if (level === 3 && node ) {
    console.log('level3',node)
  }
  // 查询表基本信息
  if (level === 4 && node ) {
   console.log('level4',node)
    dataTableLabel.value = node.label
    schema.value = node.parent.parent.value
    datasystem_id.value = node.parent.parent.parent.tid
    dataSystemid.value = node.parent.parent.parent.tid
    tableLoading.value = true
    queryOriginalList({
      table_name: node.label,
      projectId: sessionStorage.getItem('projectId'),
      datasystem_id: datasystem_id.value,
      schema: schema.value
    }).then(res=>{
      if(res.flag){
        tableData.value = res.data.map(item=>(({
          ...item,
          id: item.primarykey,
          fieldName: item.columnname,
          comment: item.remarks,
          dataareaname:'',
          dataareanameId: '',
          rulename: '',
          rulenameId: ''
          // dataDomain: item.
        })))
        tableLoading.value = false


        if(mapData.value && dialogType.value === 'addtactics'){
          for (const key in mapData.value) {
              const item = mapData.value[key];
              console.log(`字段键名: ${key}`);
              console.log(`数据系统ID: ${item.dataSystemid}`);
              console.log(`数据域ID: ${item.dataareaid}`);
              console.log(`数据域名称: ${item.dataareaname}`);
              console.log(`规则ID: ${item.ruleId}`);
              console.log(`规则名称: ${item.rulename}`);
              console.log(`表字段ID: ${item.table_field_id}`);
              console.log(`模式: ${item.tschemas}`);
              console.log(`表名: ${item.names}`);
              console.log('----------------------');

              console.log('tableData.value',tableData.value)

            let index = tableData.value.findIndex(x =>x.fieldName === item.table_field_id)
            console.log(index)
            if(index !== -1 && datasystem_id.value === item.dataSystemid && schema.value === item.tschemas && dataTableLabel.value === item.names){
                tableData.value[index].dataareaname = item.dataareaname
                console.log('tableData.value',tableData.value)
                tableData.value[index].rulename= item.rulename
                tableData.value[index].dataareanameId = item.dataareaid
                tableData.value[index].rulenameId = item.ruleId
            }
            
          }
        }
        console.log(123123)
        if(dialogType.value === 'edit'){
          console.log('infoTable.value',infoTable.value)

          infoTable.value.forEach(item => {
            let str =  `${item.tschemas}.${item.names}.${item.table_field_id}`
            let data = {
                dataSystemid:item.datasystem_id,
                dataareaid: item.dataareaid,
                dataareaname: item.dataareaname,
                ruleId: item.ruleid,
                rulename: item.rulename,
                table_field_id: item.table_field_id,
                tschemas: item.tschemas,
                names: item.names
            }
            mapData.value[`${str}`] = data

          });


          for (const key in mapData.value) {
              const item = mapData.value[key];
              console.log(`字段键名: ${key}`);
              console.log(`数据系统ID: ${item.dataSystemid}`);
              console.log(`数据域ID: ${item.dataareaid}`);
              console.log(`数据域名称: ${item.dataareaname}`);
              console.log(`规则ID: ${item.ruleId}`);
              console.log(`规则名称: ${item.rulename}`);
              console.log(`表字段ID: ${item.table_field_id}`);
              console.log(`模式: ${item.tschemas}`);
              console.log(`表名: ${item.names}`);
              console.log('----------------------');

              console.log('tableData.value',tableData.value)

            let index = tableData.value.findIndex(x =>x.fieldName === item.table_field_id)
            console.log(index)
            if(index !== -1 && datasystem_id.value === item.dataSystemid && schema.value === item.tschemas && dataTableLabel.value === item.names){
                tableData.value[index].dataareaname = item.dataareaname
                console.log('tableData.value',tableData.value)
                tableData.value[index].rulename= item.rulename
                tableData.value[index].dataareanameId = item.dataareaid
                tableData.value[index].rulenameId = item.ruleId
            }
            
          }
          

//           {
//     "strategyName": "111",
//     "remarks": "",
//     "roleGroup": "2222,1,系统管理员,项目管理",
//     "state": "0",
//     "strategyId": "e848c8be263f417992afe1a1aa44c680",
//     "datasystem_id": "2c90e4d798c5650f0198c58937920003",
//     "tschemas": "nse_encryption_ry_test",
//     "names": "gen_table",
//     "table_field_id": "business_name",
//     "projectid": "df345570-d044-47b3-a2c6-0ff265f89b80",
//     "dataareaid": "402882057e4c6440017e4d3b6f46005f",
//     "dataareaname": "通用规则",
//     "ruleid": "2c90e4cb98d9e3220198daae53850028",
//     "rulename": "测试2",
//     "createuser": "admin",
//     "createtime": "2025-08-27 09:24:19",
//     "pageno": 0,
//     "pagesize": 0
// }
        }






      }else{
        ElMessage.error(res.msg)
         tableLoading.value = false
         tableData.value = []
      }
    }).catch(err=>{
      console.log(err)
      ElMessage.error(err.msg)
       tableLoading.value = false
       tableData.value = []
    })
  }

  console.log('mapData',mapData)










})



const selectedDataArea = ref(null)
const selectedRule = ref(null)





const handleRuleConfirm = (str,data) =>{
  console.log('mapData000',mapData.value)
  console.log('str',str)

  console.log('data',data)

  mapData.value[`${str}`] = data

  console.log('mapData11111',mapData.value)

  


      for (const key in mapData.value) {
        const item = mapData.value[key];


       let index = tableData.value.findIndex(x =>x.fieldName === item.table_field_id)
       console.log(index)
       if(index !== -1){
        tableData.value[index].names = item.names
        tableData.value[index].dataareaname = item.dataareaname
        console.log('tableData.value',tableData.value)
        tableData.value[index].rulename= item.rulename
        tableData.value[index].dataareanameId = item.dataareaid
        tableData.value[index].rulenameId = item.ruleId
       }
        
    }




}




// 生成唯一标识符
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);
  });
}
// 树节点点击处理
const handleNodeClick = async (data) => {
  currentNodeData.value = data
  // 2. 点击一层系统数据，查 schemas
  if (data.type === 'system') {
    const res = await queryShemas({
      dataSystemId: data.tid,
      dataType: data.dbtype,
      projectid: sessionStorage.getItem('projectId')
    })
    if (res && res.data) {
      data.children = res.data.map(schema => ({
        id: uuid(),
        ...schema,
        type: 'database',
        label: schema.text,
        parent: data,
        children: [
          {
            id: uuid(),
            label: '表',
            type: 'category',
            parent: {
              ...schema,
              type: 'database',
              label: schema.text,
              parent: data,
              tid: data.tid,
              dbservername: schema.text
            },
            children: []
          }
        ]
      }))
      treeData.value = [...treeData.value] // 触发视图更新
    }
  }
  // 3. 点击三层 category，查表
  if (data.type === 'category' && data.parent) {
    const parentDb = data.parent
    const res = await queryTables({
      dataSystemId: parentDb.tid,
      schema: parentDb.dbservername
    })
    if (res && res.data) {
      data.children = res.data.map(table => ({
        ...table,
        id: uuid(), 
        label: table.showName,
        type: 'table',
        parent: data
      }))
      treeData.value = [...treeData.value]
    }
  }
}
// 表格数据
const tableData = ref([])




const infoTable = ref([])

const dialogType = ref('')
// 打开对话框
const openDialog = async (mode, strategyData = null) => {
  dialogType.value = mode
  dialogVisible.value = true
  activeStep.value = 1
  selectedVersion.value = ''


  desensitizationStrategyDetails({
    strategyId: strategyData ? strategyData.strategyId : '', 
    projectid: sessionStorage.getItem('projectId')
  }).then(res =>{
    if(res.flag){
      infoTable.value = res.data
    }
  })



  queryversion({
    projectid: sessionStorage.getItem('projectId')
  }).then(res=>{
    // editionList.value = res.data
     editionList.value = res.data.map(item => {
          let res = {
            label: item.text,
            value: item.value,
            children: [],
            leaf: item.value === 'null' || item.value === 'AllVersion'
          }
          !res.leaf && (res.loading = false)
          return res
        })
        editionList.value.splice(1, 2)
         console.log(editionList.value)
 
  })


  
  // 重置表单数据
  if (mode === 'addtactics') {
    formData.strategyName = ''
    formData.remarks = ''
  } else if (strategyData) {
    // 填充编辑数据
    formData.strategyName = strategyData.strategyName || ''
    formData.remarks = strategyData.remarks || ''
  }



  
  // 清空表格数据
  tableData.value = []

  const res = await query({ project_id: sessionStorage.getItem('projectId') })
  if (res && res.data) {
    treeData.value = res.data.map(item => ({
      ...item,
      label: item.sysname,
      type: 'system',
      children: [
      ]
    }))

    // 赋值触发监听，默认查询第一个数据源的基本信息
    currentNodeData.value = treeData.value[0]
  }


}   

// 关闭对话框
const handleClose = (done) => {
  // 如果有未保存的数据，提示用户
  if ((formData.strategyName || formData.remarks) && dialogType.value !=='detail') {
    ElMessageBox.confirm('确定要关闭吗？未保存的数据将会丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      resetForm()
      done()
    }).catch(() => {
      // 取消关闭
    })
  } else {
    resetForm()
    done()
  }
}

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  mapData.value = ref({})
  formData.strategyName = ''
  formData.remarks = ''
  activeStep.value = 1
  selectedVersion.value = ''
  tableData.value = []
}

// 下一步操作
const handleNextStep = async () => {
  if (activeStep.value === 1) {
    // 验证第一步表单

    if (step1FormRef.value) {
      const formInstance = step1FormRef.value
      if (formInstance) {
        try {
          await formInstance.validate()
          activeStep.value = 2
        } catch (error) {
          ElMessage.error('请填写策略名称')
        }
      }
    }
  } else {
    // 第二步：保存策略
    await saveStrategy()
  }
}
const saveLoading = ref(false)
// 保存策略
const saveStrategy = async () => {
  saveLoading.value = true
  try {
    // 动态生成 mapStr 并构建完整对象
    const mapStr = `${dataBaseLabel.value}.${dataTableLabel.value}.${dataTableColumnsLabel.value}`;
    
    const params = {
      strategyName: formData.strategyName,
      remarks: formData.remarks,
      state: "0",
      strategyId: props.strategyId || '',
      projectId: sessionStorage.getItem('projectId'),
      roleGroup: '',
      map: mapData.value
    };

    const res = await save(params);
    
    if (res.flag) {
      ElMessage.success(props.strategyId ? '编辑成功' : '新增成功');
      saveLoading.value = false
      dialogVisible.value = false;
      emit('refresh');
      resetForm();

    } else {
      ElMessage.error(res.msg);
      saveLoading.value = false
    }
  } catch (error) {
    console.log(error);
    saveLoading.value = false
    ElMessage.error('保存失败');
  }
}




const desensitizationRuleDialogRef = ref(null)
// 编辑字段
const currentFieldData = ref(null)
const editField = (row) => {
  // ElMessage.info('编辑字段功能待实现')
  currentFieldData.value = row
  desensitizationRuleDialogRef.value.open(row)
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

<style scoped>
.strategy-add-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.steps-container {
  margin-bottom: 30px;
  padding: 0 50px;
}

.step-content {
  min-height: 400px;
}

.version-select {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  
  .label {
    font-weight: bold;
    color: #606266;
  }
}

.config-container {
  display: flex;
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.tree-panel {
  width: 300px;
  border-right: 1px solid #e4e7ed;
  padding: 10px;
  overflow-y: auto;
}

.table-panel {
  flex: 1;
  position: relative;
  padding: 10px;
}

.empty-table {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.tree-node {
  display: flex;
  align-items: center;
  
  .node-label {
    flex: 1;
  }
  
  .node-count {
    color: #909399;
    font-size: 12px;
    margin-left: 8px;
  }
}

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

:deep(.el-form-item__label) {
  font-weight: bold;
}
</style>