<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
   
    :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="projectName" required>
              <el-input
                v-model="formData.projectName"
                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 label="全部" value="all" />
              <el-option label="MySQL" value="mysql" />
              <el-option label="Oracle" value="oracle" />
              <el-option label="SQL Server" value="sqlserver" />
            </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.id">
                      {{ db.name }}
                    </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.id"
                  class="selected-db-item"
                >
                  <div class="db-name">{{ db.name }}</div>
                  <div class="db-ip">{{ db.ip }}</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.id"
                    class="datasource-item"
                    :class="{ active: selectedDataSource === db.id }"
                    @click="selectDataSource(db.id)"
                  >
                    {{ db.id }} {{ db.name }}
                  </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 { Search } from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectData: {
    type: Object,
    default: () => ({
      projectName: '',
      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 formData = ref({
  projectName: '',
  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: 'all',
  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 = dbFilter.value.type === 'all' || db.type === dbFilter.value.type
    const keywordMatch = db.name.includes(dbFilter.value.keyword)
    return typeMatch && keywordMatch
  })
})

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

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.id)
  } 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 handleNextStep = async () => {
  if (activeStep.value < 4) {
    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 handleCancel = () => {
  dialogVisible.value = false
}

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

// 监听数据变化
watch(selectedDbs, (newVal) => {
  selectAll.value = newVal.length > 0 && newVal.length === filteredDatabases.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, (newVal) => {
  if (newVal.length > 0 && !selectedDataSource.value) {
    selectedDataSource.value = newVal[0].id
  }
}, { immediate: true })

// 监听传入的项目数据变化
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>