<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    destroy-on-close
    :before-close="handleClose"
  >
    <div class="dialog-content">
      <!-- 左侧表单 -->
      <div class="form-container">
        <!-- 第一步：基本信息 -->
        <div v-if="activeStep === 1">
          <el-form
            ref="basicInfoFormRef"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            label-position="top"
          >
            <el-form-item label="项目名称" prop="name" required>
              <el-input
                v-model="formData.name"
                placeholder="请输入项目名称"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="项目备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入项目备注信息"
                maxlength="200"
                show-word-limit
              />
            </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>

        <!-- 第二步：数据库配置 -->
        <div v-if="activeStep === 2">
          <div class="step-title">数据库</div>
          <div class="filter-container">
            <el-select v-model="dbFilter.type" placeholder="请选择" class="filter-select" @change="selectChangeSql">
              <el-option v-for="(item,index) in sourceTypeList" :key="index" :label="item.text" :value="item.text" />
            </el-select>
            
            <el-input
              v-model="dbFilter.keyword"
              placeholder="输入数据源名称搜索"
              class="filter-input"
              clearable
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="db-select-container">
            <!-- 左侧可选数据库 -->
            <div class="db-list">
              <div class="db-list-header">
                <span>可选择数据源(数据库)</span>
              </div>
              <el-scrollbar height="300px">
                <div
                  v-for="db in availableDatabases"
                  :key="db.tid"
                  class="db-item"
                  @click="selectDatabase(db)"
                >
                  <!-- <div class="db-checkbox">
                    <el-checkbox :model-value="isDatabaseSelected(db.tid)" @click.stop />
                  </div> -->
                  <div class="db-info">
                    <div class="db-name">{{ db.sysname }}</div>
                    <div class="db-type">{{ db.dbtype }}</div>
                  </div>
                </div>
              </el-scrollbar>
            </div>

            <!-- 右侧已选数据库 -->
            <div class="db-list selected">
              <div class="db-list-header">
                <span>已选择数据源(数据库)</span>
                <span style="color: #2d8cf0;cursor: pointer;" @click="handleClearSelected">清空</span>
               
              </div>
              <el-scrollbar height="300px">
                <div
                  v-for="db in selectedDbDetails"
                  :key="db.tid"
                  class="selected-db-item"
                  @click="deselectDatabase(db)"
                >
                  <div class="db-name">{{ db.sysname }}</div>
                  <!-- <div class="db-ip">{{ db.dbip }}</div> -->
                  <div class="db-type">{{ db.dbtype }}</div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </div>

        <!-- 第三步：Schema选择 -->
        <div v-if="activeStep === 3">
          <div class="step-title">Schema选择</div>
          
          <div class="schema-container">
            <!-- 左侧数据源 -->
            <div class="datasource-section">
              <div class="section-title">数据源</div>
              <el-scrollbar height="400px">
                <div class="datasource-list">
                  <div 
                    v-for="(db, dbIndex) in selectedDbDetails" 
                    :key="db.tid"
                    class="datasource-item"
                    :class="{ active: selectedDataSource === db.tid }"
                    @click="selectDataSource(db.tid, dbIndex)"
                  >
                    {{ db.sysname }}
                  </div>
                </div>
              </el-scrollbar>
            </div>

            <!-- 右侧Schema选择 -->
            <div class="schema-section">
              <div class="schema-header">
                <div class="section-title">SCHEMA</div>
                <div class="schema-select-all">
                  <span class="schema-count">{{ selectedSchemas.length }}/{{ allSchemasCompute.length }}</span>
                </div>
              </div>
              
              <el-scrollbar height="400px">
                <el-checkbox-group v-model="selectedSchemas" @change="schemaChange">
                  <div 
                    v-for="schema in allSchemasCompute" 
                    :key="schema.value"
                    class="schema-item"
                  >
                    <el-checkbox 
                      :value="schema.value" 
                      :label="schema.text"
                      :checked="isSchemaSelected(schema.value)"
                    />
                  </div>
                </el-checkbox-group>
              </el-scrollbar>
            </div>
          </div>
        </div>

        <!-- 其他步骤内容保持不变 -->

        <!-- 第四步：数据域选择 -->
       <!-- 第四步：数据域选择 -->
        <div v-if="activeStep === 4">
          <div class="step-title">规则选择</div>
          
          <div class="domain-container">
            <!-- 左侧可选择规则 -->
            <div class="available-domains">
              <div class="section-header">
                <div class="section-title">可选择规则</div>
              </div>
              
              <div class="domain-group" v-for="group in domainGroups" :key="group.id">
                <div class="group-header">
                  <el-checkbox 
                    v-model="group.selectedAll" 
                    @change="(val) => toggleGroupSelection(group, val)"
                  >
                    {{ group.dataarea }}
                  </el-checkbox>
                </div>
                
                <el-scrollbar height="150px">
                  <el-checkbox-group v-model="selectedDomains" @change="handleDomainSelectionChange">
                    <div 
                      v-for="domain in group.list" 
                      :key="domain.id"
                      class="domain-item"
                    >
                      <el-checkbox :value="domain.id" :checked="isDomainSelected(domain.id)">
                        <div class="domain-content">
                          <div class="domain-name">{{ domain.name }}</div>
                          <div v-if="domain.desc" class="domain-desc">{{ domain.desc }}</div>
                        </div>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </el-scrollbar>
              </div>
            </div>

            <!-- 已选择规则 -->
            <div class="selected-domains">
              <div class="section-header">
                <div class="section-title">已选择规则</div>
                <div class="selection-info">
                  <span class="count">{{ selectedDomains.length }}</span>
                  <el-button type="text" @click="clearSelectedDomains">清空</el-button>
                </div>
              </div>
              
              <el-scrollbar height="400px">
                <div 
                  v-for="domain in selectedDomainDetails" 
                  :key="domain.id"
                  class="selected-domain-item"
                >
                  <div class="domain-name">{{ domain.name }}</div>
                  <div v-if="domain.desc" class="domain-desc">{{ domain.desc }}</div>
                  <div class="domain-group-name" v-if="findDomainGroupName(domain.id)">
                    所属分组: {{ findDomainGroupName(domain.id) }}
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </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>
      <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 {
  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()
  } else if (!newVal) {
    initialized.value = false
  }
}, { deep: true })

// 当对话框显示时执行的函数
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 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)
  )
})
// 计算属性：已选择的数据源详情
// 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 toggleGroupSelection = (group, selected) => {
  const groupDomainIds = group.list.map(d => d.id)
  
  if (selected) {
    const newSelected = [...new Set([...selectedDomains.value, ...groupDomainIds])]
    selectedDomains.value = newSelected
  } else {
    selectedDomains.value = selectedDomains.value.filter(id => !groupDomainIds.includes(id))
  }
}

const clearSelectedDomains = () => {
  selectedDomains.value = []
  domainGroups.value.forEach(group => {
    group.selectedAll = false
  })
}

// 上一步
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 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, async (newVal, oldVal) => {
  if(newVal.length > 0) {
    if(JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
      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 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>
.dialog-content {
  display: flex;
  min-height: 500px;
}

.form-container {
  flex: 1;
  padding-right: 30px;
}

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

.step-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

/* 第二步样式 */
.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;
}
</style>