<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="basicInfoForm"
            :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">
              <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">
                <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
              </div>
              <el-scrollbar height="300px">
                <el-checkbox-group v-model="selectedDbs">
                  <div
                    v-for="db in filteredDatabases"
                    :key="db.id"
                    class="db-item"
                  >
                    <el-checkbox :label="db.tid">
                      {{ db.sysname }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </el-scrollbar>
            </div>

            <!-- 右侧已选数据库 -->
            <div class="db-list selected">
              <div class="db-list-header">
                <span>已选择数据源(数据库)</span>
                <el-button type="text" @click="handleClearSelected">清空</el-button>
              </div>
              <el-scrollbar height="300px">
                <div
                  v-for="db in selectedDbDetails"
                  :key="db.tid"
                  class="selected-db-item"
                >
                  <div class="db-name">{{ db.sysname }}</div>
                  <div class="db-ip">{{ db.dbip }}</div>
                  <div class="db-username">{{ db.username }}</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 in selectedDbDetails" 
                    :key="db.tid"
                    class="datasource-item"
                    :class="{ active: selectedDataSource === db.tid }"
                    @click="selectDataSource(db.tid)"
                  >
                  {{ 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">
                  <el-checkbox 
                    v-model="selectAllSchemas" 
                    @change="handleSelectAllSchemas"
                  >
                    全选
                  </el-checkbox>
                  <span class="schema-count">{{ selectedSchemas.length }}/{{ allSchemas.length }}</span>
                </div>
              </div>
              
              <el-scrollbar height="400px">
                <el-checkbox-group v-model="selectedSchemas">
                  <div 
                    v-for="schema in allSchemas" 
                    :key="schema"
                    class="schema-item"
                  >
                    <el-checkbox :label="schema">
                      {{ schema }}
                    </el-checkbox>
                  </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.name">
                <div class="group-header">
                  <el-checkbox 
                    v-model="group.selectedAll" 
                    @change="(val) => toggleGroupSelection(group, val)"
                  >
                    {{ group.name }}
                  </el-checkbox>
                </div>
                
                <el-scrollbar height="300px">
                  <el-checkbox-group v-model="selectedDomains">
                    <div 
                      v-for="domain in group.domains" 
                      :key="domain.id"
                      class="domain-item"
                    >
                      <el-checkbox :label="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>
              </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 } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {
  getdatascopeprojectlist,
  checkDatasystemName,
  checkDatasystem,
  queryByEditSort,
  selectProDataSource,
  queryShemas

} 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 initialized = ref(false)
// 监听对话框显示状态变化
watch(dialogVisible, (newVal) => {
  if (newVal && !initialized.value) {
    // 对话框打开且未初始化时执行
    console.log('初始化对话框数据')
    initDialog()
  } else if (!newVal) {
    console.log('重置对话框数据')
    // 对话框关闭时重置初始化标志
    initialized.value = false
  }
}, { deep: true })
// 当对话框显示时执行的函数
const initDialog = () => {
  console.log('对话框已打开，执行初始化操作')
  querySelectOrDic()
  initialized.value = true
}


const querySelectOrDic = () => { 
    selectProDataSource({
      systemstyle: 1
    }).then(res=>{
      console.log('selectProDataSourceRes',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 = []
  
}

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 allDatabases = ref([
  // { id: 1, name: '若依配测系统', ip: '172.19.1.166', username: 'root', type: 'mysql' },
  // { id: 2, name: '测试数据库1', ip: '192.168.1.100', username: 'admin', type: 'mysql' },
  // { id: 3, name: '生产数据库', ip: '10.0.0.1', username: 'dba', type: 'oracle' },
  // { id: 4, name: '开发数据库', ip: '172.16.1.50', username: 'dev', type: 'mysql' },
  // { id: 5, name: '备份数据库', ip: '172.16.1.51', username: 'backup', type: 'sqlserver' }
])

const selectedDbs = ref([])
const selectAll = ref(false)

// 第三步：Schema选择相关
const selectedDataSource = ref(null)
const allSchemas = ref([
  // 'information_schema',
  // 'mysql',
  // 'performance_schema',
  // 'ry',
  // 'sys'
])
const selectedSchemas = ref([])
const selectAllSchemas = ref(false)

// 第四步：数据域选择相关
const domainGroups = ref([
  {
    name: '混合数据域',
    selectedAll: false,
    domains: [
      { id: 'domain1', name: '566546', desc: '' },
      { id: 'domain2', name: '通用规则', desc: '' },
      { id: 'domain3', name: '解密数据', desc: '' },
      { id: 'domain4', name: '混合证件号', desc: '按混合证件号字段查询' }
    ]
  },
  {
    name: '智能数据域',
    selectedAll: false,
    domains: [
      { id: 'domain5', name: '智能推荐', desc: '' },
      { id: 'domain6', name: '电子邮件', desc: '按邮箱字段查找' },
      { id: 'domain7', name: '社保卡号', desc: '' }
    ]
  },
  {
    name: '测试数据域',
    selectedAll: false,
    domains: [
      { id: 'domain8', name: '发现规则1', desc: '' },
      { id: 'domain9', name: '营业执照', desc: '按营业执照字段查询' },
      { id: 'domain10', name: '邮政编码', desc: '邮政编码字段查找' }
    ]
  }
])

const selectedDomains = ref(['domain2', 'domain3', 'domain4', 'domain6', 'domain7', 'domain9', 'domain10'])

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

const selectedDbDetails = computed(() => {
  return allDatabases.value.filter(db => selectedDbs.value.includes(db.tid))
})

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

// 方法
const handleSelectAll = (val) => {
  if (val) {
    selectedDbs.value = filteredDatabases.value.map(db => db.tid)
  } else {
    selectedDbs.value = []
  }
}

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

const selectDataSource = (dbId) => {
  selectedDataSource.value = dbId
}

const handleSelectAllSchemas = (val) => {
  if (val) {
    selectedSchemas.value = [...allSchemas.value]
  } else {
    selectedSchemas.value = []
  }
}

const toggleGroupSelection = (group, selected) => {
  const groupDomainIds = group.domains.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 handleNextStep = async () => {
  if (activeStep.value === 1) {
    
    try {
      // 调用第一步的验证接口
      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=>{
                allDatabases.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 === 3) {
      // selectedDbDetails
    }
    // 其他步骤直接前进
    activeStep.value++
  
  } else {
    // 最后一步提交数据
    formData.value.databases = selectedDbDetails.value
    formData.value.schemas = selectedSchemas.value
    formData.value.domains = selectedDomainDetails.value
    emit('submit', formData.value)
    dialogVisible.value = false
  }
}
// 第一步验证接口函数
const validateStep1 = async () => {
  // 这里调用实际的API接口
  // 示例：return await api.validateStep1(formData)
  return await checkDatasystemName({
    name: formData.value.name,
    id: formData.value.id
  })
  // 模拟API调用
  // return new Promise((resolve) => {
  //   setTimeout(() => {
  //     // 模拟成功响应
  //     resolve({
  //       flag: true,
  //       msg: '验证成功'
  //     })
      
  //     // 模拟失败响应
  //     // resolve({
  //     //   flag: false,
  //     //   msg: '数据库连接失败，请检查连接信息'
  //     // })
  //   }, 1000)
  // })
}

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

// 关闭前处理
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(selectedSchemas, (newVal) => {
  selectAllSchemas.value = newVal.length === allSchemas.value.length
}, { deep: true })

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

// 初始化时自动选择第一个数据源
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
    }
  }

}, { immediate: true })



const fetchAllSchemas = async (databases) => {
  try {

   
    
    // 清空之前的数据
    allSchemas.value = []
    
    // 使用Promise.all保证顺序但并行请求（如需严格顺序请使用for循环）
    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)
    const errorResults = results.filter(r => r.error)
    
    // 合并成功的数据
    successResults.forEach(res => {
      if (res.data && Array.isArray(res.data)) {
        allSchemas.value = [...allSchemas.value, ...res.data]
      }
    })
    
    // 显示结果信息
    if (successResults.length > 0) {
      console.log(`成功获取 ${successResults.length} 个数据库的Schema数据`)
    }
    
    if (errorResults.length > 0) {
      console.log(`${errorResults.length} 个数据库的Schema获取失败`)
    }
    
  } catch (error) {
    console.error('获取Schema数据过程中出错:', error)
    ElMessage.error('获取Schema数据过程中出错')
  } finally {
    // isLoading.value = false
  }
}





// 监听传入的项目数据变化
watch(() => props.projectData, (newVal) => {
  if (props.mode === 'edit') {
    formData.value = { ...newVal }
    // 初始化选中状态
    selectedDbs.value = newVal.databases.map(db => db.id)
    selectedSchemas.value = [...newVal.schemas]
    selectedDomains.value = newVal.domains.map(domain => domain.id)
  }
}, { immediate: true, deep: true })
</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;
}

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

.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;
}

.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>