<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 :value="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,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">
                  <!-- <el-checkbox 
                    v-model="selectAllSchemas" 
                    @change="handleSelectAllSchemas"
                  >
                    全选
                  </el-checkbox> -->
                  <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"
                    class="schema-item"
                  >
                    <el-checkbox :value="schema.value" :label=" schema.text" />
                   
                  </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="handlechangeSelectDomains">
                    <div 
                      v-for="domain in group.list" 
                      :key="domain.id"
                      class="domain-item"
                    >
                      <el-checkbox :value="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,
  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 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 = []
}

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([])
const selectedDbs = ref([])
const selectAll = ref(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 selectedDbDetails = computed(() => {
  return allDatabases.value.filter(db => selectedDbs.value.includes(db.tid))
})

const selectedDomainDetails = computed(() => {
  const allDomains = domainGroups.value.flatMap(group => group.list)
  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 allSchemasCompute = computed(() => {
  return allSchemas.value[allSchemasIndex.value]
})

const allSchemasIndex = ref(0)

const selectDataSource = (dbId, index) => {
  selectedDataSource.value = dbId
  allSchemasIndex.value = index
  selectedSchemas.value = []
  
  allSchemasCompute.value.forEach(element => {
    if(schemalist.value.find(item => item.schemaname === element.value && (item.osdsid == selectedDbDetails.value[allSchemasIndex.value].tid))){
      selectedSchemas.value.push(element.value)
    }
  })
}

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 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) {
    activeStep.value++
    
    if (activeStep.value === 4) {
      // 在第四步加载数据域和规则
      getAllDataAreaAndRule().then(res => {
        domainGroups.value = res.data
        // 如果是编辑模式，需要处理已选择的规则
        if (props.mode === 'edit' && formData.value.id) {
          processAreaAndRuleListForEdit()
        }
      })
    }
  } else {
    // 最后一步提交数据
    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 })

// 初始化时自动选择第一个数据源
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 = []
    
    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
  // 假设我们已经有了 areaAndRuleList 数据
  const areaAndRuleList = [
    {
      "id": "2c9381a198cab6e40198e05cba5803bc",
      "dataarea_id": "40287481777f245501777f27e6fe0000",
      "rule_id": "402874817780b607017780b823be0004"
    }
  ]
  
  if (!areaAndRuleList || !Array.isArray(areaAndRuleList)) {
    console.warn('areaAndRuleList为空或不是数组')
    selectedDomains.value = []
    return
  }
  
  console.log('接口返回的areaAndRuleList:', areaAndRuleList)
  
  // 处理已选择的规则
  const selectedRuleIds = []
  
  // 遍历所有数据域分组和规则，找到匹配的规则
  domainGroups.value.forEach(group => {
    group.list.forEach(rule => {
      // 检查这个规则是否在已选择的列表中
      const isSelected = areaAndRuleList.some(item => 
        item && item.dataarea_id === group.dataarea_id && item.rule_id === rule.id
      )
      
      if (isSelected && rule.id) {
        selectedRuleIds.push(rule.id)
      }
    })
    
    // 检查是否全选
    const groupRuleIds = group.list.map(rule => rule.id).filter(Boolean)
    const selectedInGroup = selectedRuleIds.filter(id => groupRuleIds.includes(id))
    group.selectedAll = selectedInGroup.length === groupRuleIds.length && groupRuleIds.length > 0
  })
  
  // 设置已选择的规则
  selectedDomains.value = selectedRuleIds.filter(Boolean)
  console.log('已选择的规则ID:', selectedDomains.value)
  
  if (selectedDomains.value.length === 0) {
    console.warn('没有找到任何已选择的规则')
  }
}

// 处理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)
}
// 监听传入的项目数据变化
watch(() => props.projectData, (newVal) => {
  if (props.mode === 'edit') {
    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
        selectedDbs.value = data.dataSourceIdList.map(item => item.systemsource_id)
        selectedDomains.value = data.areaAndRuleList.map(item=> item.rule_id)
        console.log('selectedDomains.value',selectedDomains.value)
        // 处理Schema数据
        // processSchemaList(data.schemalist)
        
        // 处理数据域和规则数据 - 关键修复
        if (data.areaAndRuleList && data.areaAndRuleList.length > 0) {
          // 保存areaAndRuleList供后续使用
        
          
          // 在第四步加载时处理规则选择
          if (activeStep.value === 4) {
            // processAreaAndRuleListForEdit()
              formData.value.areaAndRuleList = data.areaAndRuleList
          }
        }
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      ElMessage.error(err.msg)
    })
  }
}, { 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;
  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>