<template>
  <el-dialog
    style="padding: 0;"
    class="custom-dialog"
    v-model="dialogVisible"
    :show-close="false"
    destroy-on-close
    width="920px"
    :before-close="handleClose"
  >
    <template #header>
      <div class="custom-dialog-header">
        <div class="custom-dialog-title">
          {{ dialogTitle }}
        </div>
        <img class="custom-dialog-close" :src="dialogCloseLogo" alt="" @click="closeDialog">
      </div>
      
      
    </template>

    <!-- <el-divider class="dialog-divider"></el-divider> -->

    <div class="dialog-content">
      <!-- 左侧表单 -->
      <div class="form-container">
        <ItemTitle title="基本信息" />
        <!-- 第一步：基本信息 -->
        <div class="item-form-container">
          <el-form
            ref="basicInfoFormRef"
            :model="formData"
            :rules="formRules"
            label-width="90px"
            label-position="left"
            :inline="true"
          >
            <el-form-item label="项目名称" prop="name" required>
              <el-input
                v-model="formData.name"
                placeholder="请输入项目名称"
              />
            </el-form-item>

            <el-form-item label="项目备注" prop="remark">
              <el-input
                v-model="formData.remark"
                placeholder="请输入项目备注信息"
              />
            </el-form-item>

            <!-- <el-form-item label="项目类型" prop="projectType">
              <el-radio-group v-model="formData.projectType">
                <el-radio label="normal">普通项目</el-radio>
                <el-radio label="udf">UDF项目</el-radio>
              </el-radio-group>
            </el-form-item> -->
          </el-form>
        </div>

        <ItemTitle title="数据源配置" style="margin-top: 20px;" />

        <!-- 第二步：数据库配置 -->
        <div class="item-form-container">
          
          
          <!-- TreeSelect 组件 -->
           <div class="tree-select-container flex-container align-center" style="flex-wrap: nowrap;">
            <div class="step-title master" style="width: 90px;">数据库</div>
            <el-tree-select
              ref="treeSelectRef"
              v-model="selectedDbNodes"
              :data="treeData"
              :props="treeProps"
              :render-after-expand="false"
              show-checkbox
              node-key="tid"
              :filter-node-method="filterNode"
              placeholder="请选择数据源"
              multiple
              @check="handleTreeSelectCheck"
              @node-click="handleNodeExpand"
              :default-expand-all="false"

            >
              <template #default="{ node, data }">
                <span class="tree-node-label">
                  {{ data.sysname || data.text }}
                  <span v-if="data.dbtype" class="tree-node-type">({{ data.dbtype }})</span>
                </span>
              </template>
            </el-tree-select>
          </div>
        </div>

        <ItemTitle title="Schema选择" style="margin-top: 20px;"/>
        <!-- 第三步：Schema选择 -->
        <div class="item-form-container">
          <div v-if="selectedDbDetails.length === 0" class="flex-container align-center">
            请先选择数据库
          </div>
          <div class="flex-container align-center wrap" v-else>
            <div 
              v-for="(db, dbIndex) in selectedDbDetails" 
              :key="db.tid"
              class="datasource-item flex-container align-center"
            >
              <div style="width: 90px;">{{ db.sysname }}</div> 
              <el-select
                v-model="selectedSchemas[dbIndex]"
                multiple
                placeholder="请选择"
                style="width: 278px"
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                @change="selectChangeSchema"
              >
                <el-option
                  v-for="schema in allSchemas[dbIndex]"
                  :key="schema.value"
                  :label="schema.text"
                  :value="schema.value"
                />
              </el-select>
            </div>
          </div>
          
        </div>

        <!-- 其他步骤内容保持不变 -->
       <ItemTitle title="规则选择" style="margin-top: 20px;"/>
       <!-- 第四步：数据域选择 -->
        <div class="item-form-container">
          <div class="tree-select-container flex-container align-center" style="flex-wrap: nowrap;">
            <div class="step-title master" style="width: 90px;">规则</div>
            <el-tree-select
              ref="treeSelectRuleRef"
              v-model="selectedRuleNode"
              node-key="id"
              :data="transformedDomainGroups"
              :props="treeRuleProps"
              placeholder="请选择规则"
              multiple
              :render-after-expand="false"
              show-checkbox
            >
              <template #default="{ node, data }">
                <span class="tree-node-label">
                  {{ data.dataarea || data.name }}
                </span>
              </template>
            </el-tree-select>
          </div>
        </div>
      </div>

      <!-- 右侧步骤条 -->
      <!-- <div class="steps-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step :title="stepTitles[0]" />
          <el-step :title="stepTitles[1]" />
          <el-step :title="stepTitles[2]" />
          <el-step :title="stepTitles[3]" />
        </el-steps>
      </div> -->
    </div>

    <template #footer>

        <el-button type="primary" color="rgba(33, 103, 217, 1)" @click="handleSubmit">确认</el-button>
        <el-button type="primary"  plain>取消</el-button>
      <!-- <span class="dialog-footer">
        <el-button @click="handlePrevStep">上一步</el-button>
        <el-button type="primary" @click="handleNextStep">
          {{ activeStep === 4 ? '完成' : '下一步' }}
        </el-button>
      </span> -->
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import dialogCloseLogo from '@/assets/images/dialogCloseLogo.png'

import {
  getdatascopeprojectlist,
  checkDatasystemName,
  checkDatasystem,
  queryByEditSort,
  selectProDataSource,
  queryShemas,
  getAllDataAreaAndRule,
  getDataProjectDetail
} from '@/api/project'

import useAppStore from '@/store/modules/app'

const appStore = useAppStore()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectData: {
    type: Object,
    default: () => ({
      name: '',
      remark: '',
      projectType: 'normal',
      databases: [],
      schemas: [],
      domains: []
    })
  },
  mode: {
    type: String,
    default: 'add',
    validator: (value) => ['add', 'edit'].includes(value)
  }
})

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

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})
const formRules = ref({
 name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
})
// 初始化标志
const initialized = ref(false)

// 监听对话框显示状态变化
watch(dialogVisible, (newVal) => {
  if (newVal && !initialized.value) {
    // initDialog()
     fetchFirstLevelNodes()
     fetchRules()
  } else if (!newVal) {
    initialized.value = false
  }
}, { deep: true })

const fetchRules = () => {
        getAllDataAreaAndRule().then(res => {
        domainGroups.value = res.data
        // 如果是编辑模式，需要处理已选择的规则
        if (props.mode === 'edit' && areaAndRuleListRead.value.length > 0) {
          processAreaAndRuleListForEdit(areaAndRuleListRead.value)
        }
      })
}
const treeRuleProps = reactive({
  label: 'dataarea',
  children: 'children'
});
const selectedRuleNode = ref([])
// 转换数据格式以适应el-tree-select
const transformedDomainGroups = computed(() => {
  return domainGroups.value.map(group => {
    // 复制组的基本信息
    const transformedGroup = {
      id: group.id,
      dataarea: group.dataarea,
      children: []
    };
    
    // 将list转换为children
    if (group.list && Array.isArray(group.list)) {
      transformedGroup.children = group.list.map(rule => ({
        ...rule,
        id: rule.id,
        name: rule.name,
        dataarea: rule.type, // 使用type作为数据域名称
        ruleexample: rule.ruleexample,
        isRule: true // 标记为规则节点
      }));
    }
    
    return transformedGroup;
  });
});
// 当对话框显示时执行的函数
const initDialog = () => {
  querySelectOrDic()
  initialized.value = true
}

const querySelectOrDic = () => { 
  selectProDataSource({
    systemstyle: 1
  }).then(res => {
    sourceTypeList.value = res.data
    dbFilter.value.type = res.data.length > 0 ? res.data[res.data.length - 1].text : '' 
  })
}
const treeData = ref([])
const selectedDbNodes = ref([])
const treeProps = ref({

  
  label: 'sysname',        // 显示文本的字段名
  children: 'children',  
  // disabled: (data) => !data.tid // 只有二级节点可以选择
})
// 获取树形数据
const fetchFirstLevelNodes = async () => {
  try {
    const typeRes = await selectProDataSource({
      systemstyle: 1
    })
    
    if (typeRes.flag && typeRes.data) {
      treeData.value = typeRes.data.map(item => ({
        id: item.value,
        tid:item.value,
        text: item.text,
        value: item.value,
        sysname: item.text,
        isFirstLevel: true,
        children: [] // 初始化空children，用于懒加载
      })).filter(item => item.value !== '0')
    }
  } catch (error) {
    console.error('获取一级节点数据失败:', error)
    ElMessage.error('获取数据源类型失败')
  }
}
// 处理节点展开事件（懒加载二级节点）
// 处理节点展开事件（懒加载二级节点）
const handleNodeExpand = async (nodeData) => {
  console.log('节点展开:', nodeData)
  
  // 只有一级节点需要懒加载，且没有子节点或子节点为空
  if (nodeData.isFirstLevel && (!nodeData.children || nodeData.children.length === 0)) {
    try {
      // 设置加载状态
      nodeData.loading = true;
      
      const secondRes = await queryByEditSort({
        projectId: formData.value.id || '',
        dbtype: nodeData.text,
        loginUser: loginUser,
        flag: 1
      })
      
      if (secondRes.flag && secondRes.data) {
        // 使用 Vue.set 或创建新对象来确保响应式更新
        const newChildren = secondRes.data.map(db => ({
          ...db,
          parentName: nodeData.text,
          parentId: nodeData.id,
          text: db.sysname,
          isFirstLevel: false
        }))
        
        // 关键：使用 Vue.set 或创建新数组来触发响应式更新
        if (!nodeData.children) {
          nodeData.children = newChildren;
        } else {
          nodeData.children.splice(0, nodeData.children.length, ...newChildren);
        }
        
        // 强制更新树数据（创建新数组引用）
        treeData.value = [...treeData.value]
        
        // 手动触发节点展开
        nextTick(() => {
          const treeInstance = treeSelectRef.value;
          if (treeInstance && treeInstance.expandNode) {
            treeInstance.expandNode(nodeData, true);
          }
        });
      }
    } catch (error) {
      console.error(`获取 ${nodeData.text} 的二级节点失败:`, error)
      ElMessage.error(`获取 ${nodeData.text} 的数据源失败`)
    } finally {
      nodeData.loading = false;
    }
  }
}
const treeSelectRef = ref(null)
// 处理树选择变化
const handleTreeSelectCheck = (checkedNode, { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }) => {

  
  // 完全排除一级节点的选择，只保留有tid的二级节点
  const secondaryNodes = checkedNodes.filter(node => node.tid && !node.isFirstLevel);
  // selectedDbDetails.value = secondaryNodes;
  
  // 更新选中节点的keys（只包含二级节点）
  selectedDbNodes.value = secondaryNodes.map(node => node.tid);
  
  // console.log('更新后的 selectedDbNodes:', selectedDbNodes.value);

};
watch(selectedDbNodes, (newVal) => {
  console.log('getCheckedNodes',treeSelectRef.value.getCheckedNodes())
  console.log('节点监听器',selectedDbNodes.value)
  if(newVal) {
    selectedDbDetails.value = treeSelectRef.value.getCheckedNodes()

    fetchAllSchemas(selectedDbDetails.value)
  }
}, { deep: true })
// // 移除已选数据源
// const removeSelectedDb = (db) => {
//   const index = selectedDbDetails.value.findIndex(item => item.tid === db.tid)
//   if (index > -1) {
//     selectedDbDetails.value.splice(index, 1)
//     selectedDbNodes.value = selectedDbDetails.value.map(db => db.tid)
    
//     // 从树选择器中移除
//     const treeSelectRef = document.querySelector('.el-tree-select')
//     if (treeSelectRef) {
//       const selectedValues = selectedDbNodes.value
//       // 这里需要根据实际情况更新树选择器的值
//     }
//   }
// }
// 过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return data.sysname?.toLowerCase().includes(value.toLowerCase()) || 
         data.text?.toLowerCase().includes(value.toLowerCase())
}


// 获取显示名称（一级节点/二级节点）
const getDbDisplayName = (db) => {
  return `${db.parentName} / ${db.sysname}`
}

// 自定义节点样式 - 隐藏一级节点的checkbox
const customNodeClass = (data) => {
  return data.isFirstLevel ? 'first-level-node' : 'second-level-node'
}

// // 在对话框显示时加载数据
// watch(dialogVisible, (newVal) => {
//   if (newVal) {
//     setTimeout(() => {
//        fetchTreeData()
//     }, 1000);
   
//   }
// })










const reset = () => { 
  sourceTypeList.value = []
  formData.value = {}
  activeStep.value = 1
  dbFilter.value.type = ''
  dbFilter.value.keyword = ''
  // allDatabases.value = []
  selectedDbs.value = []
  allSchemasIndex.value = 0
}

const sourceTypeList = ref([])
// 表单数据
const formData = ref({
  id: '',
  name: '',
  remark: '',
  projectType: 'normal',
  databases: [],
  schemas: [],
  domains: [],
})

// 步骤条相关
const activeStep = ref(1)
const stepTitles = ref([
  '基本信息',
  '数据源配置',
  'Schema选择',
  '数据域选择'
])

// 弹窗标题
const dialogTitle = computed(() => {
  return props.mode === 'add' ? '新增项目' : '编辑项目'
})

// 第二步：数据库配置相关
const dbFilter = ref({
  type: '',
  keyword: ''
})
const selectedDbDetails = ref([])
// 定义数据源相关变量
const availableDatabases = ref([]) // queryByEditSort返回的未选择数据源
const selectedDbs = ref([]) // 当前选择的数据库ID列表
const selectAll = ref(false)



// 计算属性：过滤后的可选数据库（排除已选择的）
const filteredAvailableDatabases = computed(() => {
  return availableDatabases.value.filter(db => 
    !selectedDbs.value.includes(db.tid) && 
    db.sysname.toLowerCase().includes(dbFilter.value.keyword.toLowerCase())
  )
})
// 计算属性：已选择的数据源详情
// const selectedDbDetails = computed(() => {
//   // 从所有数据源中找出已选择的
//   return availableDatabases.value.filter(db => 
//     selectedDbs.value.includes(db.tid)
//   )
// })
// 检查数据库是否已选择
const isDatabaseSelected = (dbId) => {
  return selectedDbs.value.includes(dbId)
}
// 选择数据库（点击左侧）
const selectDatabase = (item) => {
  if (!selectedDbs.value.includes(item.tid)) {
    let index = availableDatabases.value.findIndex(x => x.tid === item.tid)
    availableDatabases.value.splice(index,1)
    selectedDbs.value.push(item.tid)
    selectedDbDetails.value.push(item)
  

  }
}
// 取消选择数据库（点击右侧）
const deselectDatabase = (db) => {
  const index = selectedDbs.value.indexOf(db.tid)
  if (index > -1) {
    selectedDbs.value.splice(index, 1)
    selectedDbDetails.value.splice(index, 1)
    availableDatabases.value.push(db)

  }
}


// 清空选择
const handleClearSelected = () => {
  availableDatabases.value = [...availableDatabases.value,...selectedDbDetails.value] 
  selectedDbDetails.value = []
  selectedDbs.value = []
  selectAll.value = false
}


// 第三步：Schema选择相关
const selectedDataSource = ref(null)
const allSchemas = ref([])
const selectedSchemas = ref([])
const selectAllSchemas = ref(false)

// 第四步：数据域选择相关
const domainGroups = ref([])
const selectedDomains = ref([])

// 计算属性
// const filteredDatabases = computed(() => {
//   return allDatabases.value.filter(db => {
//     const keywordMatch = db.sysname.includes(dbFilter.value.keyword)
//     return keywordMatch
//   })
// })




const selectedDomainDetails = computed(() => {
  const allDomains = domainGroups.value.flatMap(group => group.list)
  return allDomains.filter(domain => selectedDomains.value.includes(domain.id))
})


// const handleClearSelected = () => {
//   selectedDbs.value = []
//   selectAll.value = false
// }

const allSchemasCompute = computed(() => {
  return allSchemas.value[allSchemasIndex.value]
})

const allSchemasIndex = ref(0)

// 修改选择数据源的方法
const selectDataSource = (dbId, index) => {
  selectedDataSource.value = dbId
  allSchemasIndex.value = index
  
  // 如果是编辑模式，从原始数据中恢复选中的schema
  if (props.mode === 'edit' && originalSchemalist.value.length > 0) {
    const dbSchemas = originalSchemalist.value
      .filter(item => item.osdsid === dbId)
      .map(item => item.schemaname)
    
    // 更新选中状态，但避免重复添加
    dbSchemas.forEach(schema => {
      if (!selectedSchemas.value.includes(schema)) {
        selectedSchemas.value.push(schema)
      }
    })
  }
}

const schemalist = ref([])

const schemaChange = () => {
  selectedSchemas.value.forEach(element => {
    let data = {
      schemaname: element,
      dbtype: selectedDbDetails.value[allSchemasIndex.value].dbtype,
      osdsid: selectedDbDetails.value[allSchemasIndex.value].tid,
    }
    schemalist.value.push(data)
  })
}



// 上一步
const handlePrevStep = () => {
  if (activeStep.value > 1) {
    activeStep.value--
  }
}

const loginUser = {
  tsysUser: {
    id: appStore.userInfo.user.id,
    username: appStore.userInfo.user.username
  }
} 
// 修改数据库类型变化时的处理
const selectChangeSql = () => {
  queryByEditSort({
    projectId: formData.value.id || '',
    dbtype: dbFilter.value.type,
    loginUser: loginUser,
    flag: 1
  }).then(res => {
    availableDatabases.value = res.data
  })
}

const basicInfoFormRef = ref(null)
const handleNextStep = async () => {
  if (activeStep.value === 1) {
    try {
      if(!formData.value.name || formData.value.name === ''){
        ElMessage({
          message: '请填写项目名称',
          type: 'warning',
        })
        return
      }
    
      const response = await validateStep1()
      if (response.flag === true) {
        checkDatasystem().then(res => {
          if (res.flag === true) {
            activeStep.value++
            if(activeStep.value === 2) {
              queryByEditSort({
                projectId: formData.value.id || '',
                dbtype: dbFilter.value.type,
                loginUser: loginUser,
                flag: 1
              }).then(res => {
                availableDatabases.value = res.data
              })
            }
          } else {
            ElMessage.error(res.msg)
          }
        }).catch(err => {
          ElMessage.error(err.msg)
        })
      } else {
        ElMessage.error(response.msg || '第一步验证失败')
        return
      }
    } catch (error) {
      // console.error('第一步验证接口调用失败:', error)
      // ElMessage.error('网络错误，请稍后重试')
      return
    }
  } else if (activeStep.value < 4) {
    if(activeStep.value === 2){
      console.log('selectedDbs.value',selectedDbs.value)
      if(selectedDbs.value.length === 0 || selectedDbDetails.value.length === 0){
        ElMessage({
          message: '请选择数据源',
          type: 'warning',
        })
        return
      }
      
    }


    if(activeStep.value === 3){
      if(selectedSchemas.value.length === 0) {
        ElMessage({
          message: '请选择SCHEMA',
          type: 'warning',
        })
        return
      }
    }


    activeStep.value++
    
    if (activeStep.value === 4) {
      // 在第四步加载数据域和规则
      getAllDataAreaAndRule().then(res => {
        domainGroups.value = res.data
        // 如果是编辑模式，需要处理已选择的规则
        if (props.mode === 'edit' && areaAndRuleListRead.value.length > 0) {
          processAreaAndRuleListForEdit(areaAndRuleListRead.value)
        }
      })


      
    }
  } else {
    if(selectedDomains.value.length === 0){
         ElMessage({
          message: '请选择规则',
          type: 'warning',
        })
        return
      }
    // 最后一步提交数据
    formData.value.databases = selectedDbDetails.value
    formData.value.schemas = schemalist.value
    formData.value.domains = selectedDomainDetails.value.map(item => ({
      dataarea_id: item.dataarea_id,
      rule_id: item.id
    }))
    emit('submit', formData.value)

    setTimeout(() => {
      reset()
      dialogVisible.value = false
    }, 300)
  }
}

// 第一步验证接口函数
const validateStep1 = async () => {
  return await checkDatasystemName({
    name: formData.value.name,
    id: formData.value.id
  })
}
const handleSubmit = async ()=> {
  if(!formData.value.name || formData.value.name === ''){
    ElMessage.warning('请输入项目名称')
    return
  }

  
  const response = await validateStep1()
  if (response.flag !== true){
    ElMessage.error(response.msg || '第一步验证失败')
    return
  }


  if(!selectedDbNodes.value || selectedDbNodes.value.length === 0) {
    ElMessage.warning('请选择数据库')
    return
  }

  if(!selectedSchemas.value || selectedSchemas.value.length === 0) {
    ElMessage.warning('请选择Schema')
    return
  }
  if(!selectedRuleNode.value || selectedRuleNode.value.length === 0) {
    ElMessage.warning('请选择规则')
    return
  }



  // console.log('项目名称',formData.value.name)
  // console.log('项目备注',formData.value.remark)
  // console.log('项目数据源',selectedDbDetails.value)
  // console.log('Schema',schemalist.value)
  // console.log('rule',selectedRuleNode.value)

  // console.log('transformedDomainGroups',transformedDomainGroups)

    let list = []
    for (let index = 0; index < selectedRuleNode.value.length; index++) {
      const item = selectedRuleNode.value[index];

       transformedDomainGroups.value.forEach(element => {
        let data = element.children.find(x =>x.id === item)
        if(data){
          list.push(data)
        }
       });
      
    }

    formData.value.databases = selectedDbDetails.value
    formData.value.schemas = schemalist.value
    formData.value.domains = list.map(item =>({
      dataarea_id:item.dataarea_id,
      rule_id: item.id
    }))

    emit('submit', formData.value)

    setTimeout(() => {
      reset()
      dialogVisible.value = false
    }, 300)
}
const closeDialog = () => {
  ElMessageBox.confirm('确定要关闭吗？未保存的更改将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    dialogVisible.value = false
    reset()
    done()
  }).catch(() => {
    // 取消关闭
  })

}
// 关闭前处理
const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？未保存的更改将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    reset()
    done()
  }).catch(() => {
    // 取消关闭
  })
}

// // 监听数据变化
// watch(selectedDbs, (newVal) => {
//   selectAll.value = newVal.length > 0 && newVal.length === allDatabases.value.length
// })

watch(selectedDomains, (newVal) => {
  if(domainGroups.value.length > 0) {
    domainGroups.value.forEach(group => {
      const groupDomainIds = group.list.map(d => d.id)
      group.selectedAll = groupDomainIds.every(id => newVal.includes(id))
    })
  }
}, { deep: true })

// // 修改数据源监听器，确保编辑模式下正确显示schema
// watch(selectedDbDetails.value, async (newVal, oldVal) => {
//   console.log('数据源监听器')
//   if(newVal.length > 0) {
//       console.log('数据源监听器2')
//       console.log(newVal)
//       console.log(oldVal)
//     if(JSON.stringify(newVal)) {
//       console.log('数据源监听器3')
//       await fetchAllSchemas(newVal)
//     }
    
//     if(!selectedDataSource.value) {
//       selectedDataSource.value = newVal[0].tid
//     }
    
//     // 如果是编辑模式且有schema数据，确保正确回显
//     if (props.mode === 'edit' && originalSchemalist.value.length > 0) {
//       processSchemalistForEdit(originalSchemalist.value)
//     }
//   }
// }, { immediate: true })


// 在第三步激活时确保数据正确加载
watch(activeStep, (newVal) => {
  if (newVal === 3) {
    // 第三步激活时，确保schema数据正确加载
    if (props.mode === 'edit' && originalSchemalist.value.length > 0) {
      setTimeout(() => {
        processSchemalistForEdit(originalSchemalist.value)
      }, 300)
    }
  }
})



const fetchAllSchemas = async (databases) => {
  try {
    allSchemas.value = []
    
    const results = await Promise.all(
      databases.map(db => 
        queryShemas({
          dbType: db.dbtype,
          dataSystemId: db.tid
        }).catch(error => {
          console.error(`获取数据库 ${db.sysname} 的Schema失败:`, error)
          return { 
            dataSystemId: db.tid,
            error: true,
            message: `获取数据库 ${db.sysname} 的Schema失败`
          }
        })
      )
    )
    
    const successResults = results.filter(r => !r.error)
    
    successResults.forEach(res => {
      if (res.data && Array.isArray(res.data)) {
        allSchemas.value.push(res.data)
      }
    })
    
    console.log('allSchemas', allSchemas.value)
  } catch (error) {
    console.error('获取Schema数据过程中出错:', error)
    ElMessage.error('获取Schema数据过程中出错')
  }
}

const selectChangeSchema = async () => { 
  console.log('selectedSchemas',selectedSchemas.value)
  let list = []
  selectedSchemas.value.forEach((element,elementIndex) => {
    element.forEach(item => {
      list.push({
        schemaname: item,
        dbtype: selectedDbDetails.value[elementIndex].dbtype,
        osdsid: selectedDbDetails.value[elementIndex].tid,
      })
    });
  });
  console.log(list)
  schemalist.value = list
}

// 修改处理数据域和规则的方法
const processAreaAndRuleListForEdit = (areaAndRuleList) => {
  if (!areaAndRuleList || !Array.isArray(areaAndRuleList)) {
    console.warn('areaAndRuleList为空或不是数组')
    selectedDomains.value = []
    return
  }
  
  console.log('接口返回的areaAndRuleList:', areaAndRuleList)
  
  // 提取所有规则ID
  const selectedRuleIds = areaAndRuleList
    .filter(item => item && item.rule_id)
    .map(item => item.rule_id)
  
  console.log('已选择的规则ID:', selectedRuleIds)
  
  // 设置已选择的规则
  selectedDomains.value = selectedRuleIds
  
  // 更新分组全选状态
  updateGroupSelectionStates()
}
// 更新分组选择状态
const updateGroupSelectionStates = () => {
  if (domainGroups.value.length === 0) return
  
  domainGroups.value.forEach(group => {
    const groupRuleIds = group.list.map(rule => rule.id).filter(Boolean)
    const selectedInGroup = selectedDomains.value.filter(id => 
      groupRuleIds.includes(id)
    )
    group.selectedAll = selectedInGroup.length === groupRuleIds.length && groupRuleIds.length > 0
  })
}
// 在脚本部分添加这个函数
const isDomainSelected = (domainId) => {
  return selectedDomains.value.includes(domainId)
}
// 监听数据域分组变化，当分组加载完成后更新选择状态
watch(domainGroups, (newGroups) => {
  if (newGroups.length > 0 && props.mode === 'edit' && areaAndRuleListRead.value.length > 0) {
    // 延迟处理以确保DOM已渲染
    setTimeout(() => {
      processAreaAndRuleListForEdit(areaAndRuleListRead.value)
    }, 100)
  }
})
watch(selectedDomains, () => {
  updateGroupSelectionStates()
}, { deep: true })
// 查找规则所属分组名称
const findDomainGroupName = (domainId) => {
  for (const group of domainGroups.value) {
    const found = group.list.find(domain => domain.id === domainId)
    if (found) return group.dataarea
  }
  return null
}
// 处理Schema数据
const processSchemaList = (schemaList) => {
  if (!schemaList || !Array.isArray(schemaList)) return
  
  fetchAllSchemas(selectedDbDetails.value).then(() => {
    selectedSchemas.value = schemaList.map(item => item.schemaname)
    
    schemalist.value = schemaList.map(item => ({
      schemaname: item.schemaname,
      dbtype: item.dbtype,
      osdsid: item.osdsid
    }))
  })
}
const handlechangeSelectDomains = (val)=>{
  console.log('selectedDomains.value',selectedDomains.value)
}

const originalSchemalist = ref([])
const areaAndRuleListRead = ref([])
// 监听传入的项目数据变化
// 修改监听项目数据变化的逻辑
watch(() => props.projectData, (newVal) => {
  if (props.mode === 'edit' && newVal.id) {
    formData.value = { ...newVal }
    
    getDataProjectDetail({projectId: newVal.id}).then(res => { 
      if(res.flag) {
        let data = res.data
        if(!data) return

        formData.value.name = data.project.project
        formData.value.remark = data.project.note
        
        // 设置已选择的数据源详情
        
        // 设置当前选择的数据库ID
        selectedDbs.value = data.dataSourceIdList.map(item => item.systemsource_id)
        // 保存原始schemalist数据
        originalSchemalist.value = data.schemalist || []
        areaAndRuleListRead.value = data.areaAndRuleList || []



        if(data.dataSourceIdList && data.dataSourceIdList.length > 0){
          selectedDbDetails.value = data.dataSourceIdList.map(item =>(({
            ...item,
            tid: item.systemsource_id,
            dbtype: item.dbtype,
            sysname:item.sysname
          })))
        }
        
       /// 加载可选数据源
        queryByEditSort({
          projectId: formData.value.id || '',
          dbtype: dbFilter.value.type,
          loginUser: loginUser,
          flag: 1
        }).then(res => {
          availableDatabases.value = res.data
        })
        
        // 处理数据域和规则数据
        if (data.areaAndRuleList && data.areaAndRuleList.length > 0) {
          formData.value.areaAndRuleList = data.areaAndRuleList
          getAllDataAreaAndRule().then(domainRes => {
            domainGroups.value = domainRes.data
            processAreaAndRuleListForEdit(data.areaAndRuleList)
          })
        }
        
        // 处理已选择的schema
        if (props.mode === 'edit' && originalSchemalist.value.length > 0) {
          processSchemalistForEdit(originalSchemalist.value)
        }
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      ElMessage.error(err.msg)
    })
  }
}, { immediate: true, deep: true })
// 添加处理编辑模式schema的方法
const processSchemalistForEdit = (schemalist) => {
  if (!schemalist || !Array.isArray(schemalist)) return
  
  // 延迟处理以确保DOM已更新
  setTimeout(() => {
    // 清空当前选中的schema
    selectedSchemas.value = []
    schemalist.value = []
    
    // 根据原始数据设置选中的schema
    schemalist.forEach(item => {
      if (item.schemaname && !selectedSchemas.value.includes(item.schemaname)) {
        selectedSchemas.value.push(item.schemaname)
        
        // 找到对应的数据源
        const db = selectedDbDetails.value.find(db => db.tid === item.osdsid)
        if (db) {
          schemalist.value.push({
            schemaname: item.schemaname,
            dbtype: item.dbtype,
            osdsid: item.osdsid
          })
        }
      }
    })
    
    console.log('编辑模式Schema处理完成:', selectedSchemas.value)
  }, 500)
}
// 添加检查schema是否选中的方法
const isSchemaSelected = (schemaValue) => {
  return selectedSchemas.value.includes(schemaValue)
}








</script>
<style scoped lang="scss">
.dialog-content {
  display: flex;
  // min-height: 500px;
}

.form-container {
  flex: 1;
  .el-form-item--default{
    margin-bottom: 0px;
  }
  // padding-right: 30px;
}

.steps-container {
  width: 150px;
  padding-left: 30px;
  border-left: 1px solid #eee;
}

.step-title {
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 22px;
  color: rgba(148, 148, 148, 1);
}

/* 第二步样式 */
.filter-container {
  display: flex;
  margin-bottom: 15px;
  gap: 10px;
}

.filter-select {
  width: 120px;
}

.filter-input {
  flex: 1;
}

.db-select-container {
  display: flex;
  gap: 20px;
}

.db-list {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.db-list.selected {
  flex: 1;
}

.db-list-header {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.db-item {
  padding: 10px 15px;
  border-bottom: 1px solid #f5f5f5;
  &:hover{
    background-color: #aed8ff;
    cursor: pointer;
  }
}

.selected-db-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f5f5f5;
  &:hover{
    background-color: #aed8ff;
    cursor: pointer;
  }
}

.db-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.db-ip {
  color: #666;
  font-size: 13px;
  margin-bottom: 3px;
}

.db-username {
  color: #999;
  font-size: 12px;
}

/* 第三步样式 */
.schema-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.datasource-section, .schema-section {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f8f8;
}

.section-title {
  padding: 10px 15px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f5f5;
}

.datasource-list {
  padding: 5px 0;
}

.datasource-item {
  padding: 10px 15px;
  cursor: pointer;
  // border-bottom: 1px solid #f0f0f0;
}

.datasource-item:hover {
  // background-color: #f0f7ff;
}

.datasource-item.active {
  // background-color: #e6f7ff;
  color: #1890ff;
}

.schema-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px;
}

.schema-select-all {
  display: flex;
  align-items: center;
  gap: 10px;
}

.schema-count {
  color: #999;
  font-size: 13px;
}

.schema-item {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

/* 第四步样式 */
.domain-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.available-domains, .selected-domains {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px; 
  background-color: #f8f8f8;
  height: 500px;
  overflow-y: auto;
}

.section-header {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-weight: bold;
}

.selection-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.count {
  color: #1890ff;
  font-weight: bold;
}

.domain-group {
  margin-bottom: 20px;
}

.group-header {
  padding: 10px 15px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #e8e8e8;
}

.domain-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.domain-content {
  margin-left: 8px;
}

.domain-name {
  font-weight: 500;
}

.domain-desc {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.selected-domain-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.selected-domain-item .domain-name {
  font-weight: bold;
}

.selected-domain-item .domain-desc {
  color: #666;
  font-size: 13px;
  margin-top: 4px;
}

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

:deep(.el-step__title) {
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  padding-bottom: 8px;
}
.item-form-container {
  margin-top: 14px;
  border-radius: 5px;
  background: rgba(247, 248, 250, 1);
  padding-top: 25px;
  padding-bottom: 27px;
  padding-left: 15px;
  padding-right: 15px;
  :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 0px;
    color: rgba(148, 148, 148, 1);
  }
  :deep(.el-input__wrapper){
    width: 278px;
  }
}

/* 一级节点隐藏checkbox */
:deep(.first-level-node .el-checkbox) {
  display: none !important;
}

/* 确保一级节点仍然可以点击展开 */
:deep(.first-level-node .el-tree-node__expand-icon) {
  display: inline-block !important;
}

/* 二级节点正常显示checkbox */
:deep(.second-level-node .el-checkbox) {
  display: inline-block !important;
}
.flex-container { 
  display: flex;

}
.wrap {
  flex-wrap: wrap;
}
.align-center{
  align-items: center;
}
.justify-center {
  justify-content: center;
}
.master {
  &::before{
    color: var(--el-color-danger);
    content: "*";
    margin-right: 4px;
  }
     
}
</style>
