<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :before-close="handleClose"
  >
    <!-- 步骤导航 - 按照图片样式重新设计 -->
    <div class="steps-navigation">
      <div class="steps-container">
        <div class="step-item" :class="{ 'step-active': currentStep === 1, 'step-completed': currentStep > 1 }">
          <div class="step-number">1</div>
          <div class="step-title">新建任务</div>
          <div class="step-status">{{ currentStep === 1 ? '进行中' : currentStep > 1 ? '已完成' : '待进行' }}</div>
        </div>
        <div class="step-connector"></div>
        <div class="step-item" :class="{ 'step-active': currentStep === 2, 'step-completed': currentStep > 2 }">
          <div class="step-number">2</div>
          <div class="step-title">选择数据源</div>
          <div class="step-status">{{ currentStep === 2 ? '进行中' : currentStep > 2 ? '已完成' : '待进行' }}</div>
        </div>
        <div class="step-connector"></div>
        <div class="step-item" :class="{ 'step-active': currentStep === 3, 'step-completed': currentStep === 3 }">
          <div class="step-number">3</div>
          <div class="step-title">配置规则</div>
          <div class="step-status">{{ currentStep === 3 ? '进行中' : '待进行' }}</div>
        </div>
      </div>
    </div>

    <!-- 步骤1：新建任务 -->
    <div v-if="currentStep === 1" class="step-content">
      <el-form :model="formData" :rules="rules" ref="step1Form" label-width="120px">
        <el-form-item label="发现任务名称" prop="tname" required>
          <el-input
            v-model="formData.tname"
            placeholder="请输入发现任务名称"
            clearable
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 步骤2：选择数据源 -->
    <div v-else-if="currentStep === 2" class="step-content">
      <div class="data-source-section">
        <div class="data-source-header">
          <span class="label">数据源：</span>
          <el-select v-model="selectedDataSource" placeholder="请选择数据源">
            <el-option
              v-for="source in dataSources"
              :key="source.value"
              :label="source.label"
              :value="source.value"
            />
          </el-select>
        </div>

        <div class="selection-content">
          <!-- 左侧SCHEMA列表 -->
          <div class="schema-list">
            <div class="schema-header">
              <h4>SCHEMA列表</h4>
              <el-input
                v-model="schemaSearch"
                placeholder="搜索SCHEMA"
                size="small"
                prefix-icon="Search"
                clearable
                class="search-input"
              />
            </div>
            <div class="list-container">
              <div
                v-for="schema in filteredSchemaList"
                :key="schema.id"
                class="schema-item"
                :class="{ 'schema-selected': selectedSchema === schema.id }"
                @click="selectSchema(schema)"
              >
                <span class="schema-name">{{ schema.name }}</span>
              </div>
            </div>
          </div>

          <el-divider direction="vertical" />

          <!-- 右侧表列表 -->
          <div class="table-list">
            <div class="table-header">
              <div class="table-header-top">
                <h4>表列表</h4>
                <span class="selected-count">{{ selectedTables.length }}/{{ filteredTableList.length }}</span>
              </div>
              <div class="table-header-bottom">
                <el-checkbox v-model="selectAll" @change="handleSelectAll" class="select-all-checkbox">全选</el-checkbox>
                <el-input
                  v-model="tableSearch"
                  placeholder="搜索表"
                  size="small"
                  prefix-icon="Search"
                  clearable
                  class="search-input"
                />
              </div>
            </div>
            <div class="list-container">
              <el-checkbox-group v-model="selectedTables">
                <div
                  v-for="table in filteredTableList"
                  :key="table.id"
                  class="table-item"
                >
                  <el-checkbox :label="table.id">
                    <span class="table-name">{{ table.name }}</span>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤3：配置规则 -->
    <div v-else class="step-content">
      <el-form :model="ruleConfig" :rules="ruleRules" ref="step3Form" label-width="120px">
        <el-form-item label="采样方式" prop="samplingMethod" required>
          <el-radio-group v-model="ruleConfig.samplingMethod">
            <el-radio label="sequential">顺序</el-radio>
            <el-radio label="random">随机</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="最大采样数" prop="maxSamples" required>
          <el-input-number
            v-model="ruleConfig.maxSamples"
            :min="1"
            :max="10000"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="匹配率" prop="matchingRate" required>
          <div class="matching-rate-input">
            <el-input
              v-model="ruleConfig.matchingRate"
              placeholder="50"
              style="width: 100px"
            />
            <span class="percentage-suffix">百分比%</span>
          </div>
        </el-form-item>

        <el-form-item label="敏感类型" required>
          <div class="sensitive-types">
            <el-tag
              v-for="type in sensitiveTypes"
              :key="type"
              closable
              @close="removeSensitiveType(type)"
              class="sensitive-tag"
            >
              {{ type }}
            </el-tag>
            <el-button type="primary" text @click="openSensitiveTypeDialog" class="add-sensitive-btn">
              + 添加敏感类型
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        
        <el-button
          v-if="currentStep > 1"
          @click="handlePrevStep"
        >
          上一步
        </el-button>
        
        <el-button
          v-if="currentStep < 3"
          type="primary"
          @click="handleNextStep"
        >
          下一步
        </el-button>
        
        <el-button
          v-if="currentStep === 3"
          type="primary"
          @click="handleConfirm"
        >
          确定
        </el-button>
      </div>
    </template>

    <!-- 敏感类型选择弹窗 -->
    <!-- <SensitiveTypeDialog
      v-model="sensitiveTypeDialogVisible"
      @confirm="handleSensitiveTypeConfirm"
    /> -->
     <SensitiveTypeDialog
      ref="sensitiveDialogRef"
      v-model="sensitiveTypeDialogVisible"
      :selected-types="selectedRuleIds"
      @confirm="handleRuleConfirm"
    />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import SensitiveTypeDialog from './SensitiveTypeDialog.vue'

const emit = defineEmits(['confirm'])


const dialogVisible = ref(false)
const currentStep = ref(1)
const isEditMode = ref(false)
const currentEditId = ref(null)
const sensitiveTypeDialogVisible = ref(false)
const schemaSearch = ref('')
const tableSearch = ref('')

const sensitiveDialogRef = ref()
const selectedRuleIds = ref(['email', 'mixed_id']) // 已选规则的ID
const selectedRules = ref([
  { id: 'email', domain: '电子邮件', ruleName: '邮箱规则1', sample: '605396113@qq.com' },
  { id: 'mixed_id', domain: '混合证件号', ruleName: '混合证件号规则1', sample: '310000000100116, 9131000...' }
])
const sensitiveTypes = ref(['电子邮件', '混合证件号'])
// 步骤1数据
const formData = reactive({
  tname: '123',
  remark: ''
})

const rules = {
  tname: [
    { required: true, message: '请填写发现任务名称', trigger: 'blur' }
  ]
}

// 步骤2数据
const selectedDataSource = ref('system1')
const dataSources = ref([
  { value: 'system1', label: '若依测试系统1' }
])

const schemaList = ref([
  { id: 'ry', name: 'ry' }
])

const selectedSchema = ref('ry')
const tableList = ref([
  { id: 'gen_table', name: 'gen_table' },
  { id: 'gen_table_column', name: 'gen_table_column' },
  { id: 'sys_config', name: 'sys_config' },
  { id: 'sys_dept', name: 'sys_dept' },
  { id: 'sys_dict_data', name: 'sys_dict_data' },
  { id: 'sys_dict_type', name: 'sys_dict_type' },
  { id: 'sys_job', name: 'sys_job' },
  { id: 'sys_job_log', name: 'sys_job_log' },
  { id: 'sys_logininfor', name: 'sys_logininfor' },
  { id: 'sys_menu', name: 'sys_menu' },
  { id: 'sys_notice', name: 'sys_notice' },
  { id: 'sys_oper_log', name: 'sys_oper_log' },
  { id: 'sys_post', name: 'sys_post' },
  { id: 'sys_role', name: 'sys_role' },
  { id: 'sys_role_dept', name: 'sys_role_dept' },
  { id: 'sys_role_menu', name: 'sys_role_menu' },
  { id: 'sys_user', name: 'sys_user' },
  { id: 'sys_user_post', name: 'sys_user_post' },
  { id: 'sys_user_role', name: 'sys_user_role' }
])

const selectedTables = ref(tableList.value.map(table => table.id))
const selectAll = ref(true)

// 步骤3数据
const ruleConfig = reactive({
  samplingMethod: 'sequential',
  maxSamples: 1000,
  matchingRate: 50
})

const ruleRules = {
  samplingMethod: [
    { required: true, message: '请选择采样方式', trigger: 'change' }
  ],
  maxSamples: [
    { required: true, message: '请输入最大采样数', trigger: 'blur' }
  ],
  matchingRate: [
    { required: true, message: '请输入匹配率', trigger: 'blur' }
  ]
}



// 计算属性
const dialogTitle = computed(() => {
  return `新增发现任务 - 步骤${currentStep.value}/3`
})

const filteredSchemaList = computed(() => {
  if (!schemaSearch.value) return schemaList.value
  return schemaList.value.filter(schema => 
    schema.name.toLowerCase().includes(schemaSearch.value.toLowerCase())
  )
})

const filteredTableList = computed(() => {
  if (!tableSearch.value) return tableList.value
  return tableList.value.filter(table => 
    table.name.toLowerCase().includes(tableSearch.value.toLowerCase())
  )
})

// 修改openDialog方法
const openDialog = (row = null) => {
  dialogVisible.value = true
  currentStep.value = 1
  isEditMode.value = !!row
  
  if (row) {
    // 编辑模式
    currentEditId.value = row.id
    // 填充步骤1数据
    formData.tname = row.tname
    formData.remark = row.remark
    
    // 填充步骤2数据（根据实际业务数据调整）
    selectedDataSource.value = row.dataSource || 'system1'
    selectedSchema.value = row.schema || 'ry'
    selectedTables.value = row.tables || []
    
    // 填充步骤3数据
    if (row.ruleConfig) {
      ruleConfig.samplingMethod = row.ruleConfig.samplingMethod || 'sequential'
      ruleConfig.maxSamples = row.ruleConfig.maxSamples || 1000
      ruleConfig.matchingRate = row.ruleConfig.matchingRate || 50
    }
    
    // 设置敏感类型
    sensitiveTypes.value = row.sensitiveTypes || []
  } else {
    // 新增模式
    resetForm()
  }
}

const resetForm = () => {
  formData.tname = '123'
  formData.remark = ''
  selectedDataSource.value = 'system1'
  selectedSchema.value = 'ry'
  selectedTables.value = tableList.value.map(table => table.id)
  selectAll.value = true
  sensitiveTypes.value = ['电子邮件', '混合证件号']
  schemaSearch.value = ''
  tableSearch.value = ''
}

const handleClose = () => {
  dialogVisible.value = false
}

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

const handleNextStep = async () => {
  if (currentStep.value === 1) {
    if (!formData.tname.trim()) {
      ElMessage.error('请填写发现任务名称')
      return
    }
  } else if (currentStep.value === 2) {
    if (!selectedDataSource.value) {
      ElMessage.error('请选择数据源')
      return
    }
    if (!selectedSchema.value) {
      ElMessage.error('请选择SCHEMA')
      return
    }
    if (selectedTables.value.length === 0) {
      ElMessage.error('请至少选择一张表')
      return
    }
  }

  currentStep.value++
}

const handlePrevStep = () => {
  currentStep.value--
}

const selectSchema = (schema) => {
  selectedSchema.value = schema.id
}

const handleSelectAll = (value) => {
  if (value) {
    selectedTables.value = tableList.value.map(table => table.id)
  } else {
    selectedTables.value = []
  }
}

const openSensitiveTypeDialog = () => {
  sensitiveDialogRef.value.openDialog()
  // sensitiveTypeDialogVisible.value = true
}



const handleRuleConfirm = (rules) => {
  selectedRules.value = rules
  selectedRuleIds.value = rules.map(rule => rule.id)
  sensitiveTypes.value = rules.map(rule => rule.domain)
}

const removeRule = (ruleId) => {
  selectedRules.value = selectedRules.value.filter(rule => rule.id !== ruleId)
  selectedRuleIds.value = selectedRuleIds.value.filter(id => id !== ruleId)
}

const removeSensitiveType = (type) => {
  sensitiveTypes.value = sensitiveTypes.value.filter(t => t !== type)
}

const handleConfirm = () => {
  if (sensitiveTypes.value.length === 0) {
    ElMessage.error('请至少添加一个敏感类型')
    return
  }

  const submitData = {
    ...formData,
    dataSource: selectedDataSource.value,
    schema: selectedSchema.value,
    tables: selectedTables.value,
    ruleConfig: { ...ruleConfig },
    sensitiveTypes: [...sensitiveTypes.value]
  }

  // 如果是编辑模式，添加id
  if (isEditMode.value) {
    submitData.id = currentEditId.value
  }

  console.log('提交数据:', submitData)
  // ElMessage.success(isEditMode.value ? '发现任务更新成功' : '发现任务创建成功')
  dialogVisible.value = false
  
  // 触发父组件更新
  emit('confirm', submitData, isEditMode.value)
}

defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
.steps-navigation {
  margin-bottom: 24px;
  padding: 0 20px;
  
  .steps-container {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 100px;
    
    &.step-active {
      .step-number {
        background: #1890ff;
        color: white;
        border-color: #1890ff;
      }
      .step-title {
        color: #1890ff;
        font-weight: 600;
      }
      .step-status {
        color: #1890ff;
      }
    }
    
    &.step-completed {
      .step-number {
        background: #52c41a;
        color: white;
        border-color: #52c41a;
      }
      .step-title {
        color: #52c41a;
      }
      .step-status {
        color: #52c41a;
      }
    }
  }
  
  .step-number {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    border: 2px solid #d9d9d9;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-bottom: 8px;
  }
  
  .step-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
  }
  
  .step-status {
    font-size: 12px;
    color: #999;
  }
  
  .step-connector {
    width: 60px;
    height: 2px;
    background: #d9d9d9;
    margin: 0 10px;
    
    .step-completed + & {
      background: #52c41a;
    }
  }
}

.step-content {
  min-height: 300px;
  padding: 0 20px;
}

.data-source-section {
  .data-source-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    
    .label {
      width: 60px;
      font-weight: 500;
      margin-right: 12px;
      color: #606266;
    }
  }

  .selection-content {
    display: flex;
    height: 400px;
    gap: 20px;
  }

  .schema-list,
  .table-list {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .schema-list {
    width: 200px;
    
    .schema-header {
      margin-bottom: 12px;
      
      h4 {
        margin: 0 0 8px 0;
        font-size: 14px;
        font-weight: 600;
        color: #606266;
      }
    }
  }

  .table-list {
    .table-header {
      display: flex;
      flex-direction: column;
      gap: 8px;
      margin-bottom: 12px;
      
      .table-header-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        h4 {
          margin: 0;
          font-size: 14px;
          font-weight: 600;
          color: #606266;
        }
        
        .selected-count {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .table-header-bottom {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .select-all-checkbox {
          white-space: nowrap;
          margin-right: 8px;
        }
        
        .search-input {
          flex: 1;
          min-width: 120px;
        }
      }
    }
  }

  .list-container {
    flex: 1;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px;
  }

  .schema-item {
    padding: 10px 12px;
    cursor: pointer;
    border-radius: 4px;
    margin-bottom: 4px;
    transition: all 0.2s ease;
    font-size: 13px;
    color: #606266;

    &:hover {
      background-color: #f5f7fa;
    }

    &.schema-selected {
      background-color: #ffd6b3;
      color: #e67e22;
      font-weight: 500;
    }
  }

  .table-item {
    padding: 8px 0;
    
    :deep(.el-checkbox) {
      width: 100%;
      
      .el-checkbox__label {
        font-size: 13px;
        color: #606266;
      }
    }
  }
}

.matching-rate-input {
  display: flex;
  align-items: center;
  
  .percentage-suffix {
    margin-left: 8px;
    color: #606266;
  }
}

.sensitive-types {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  
  .sensitive-tag {
    background-color: #f0f7ff;
    border-color: #1890ff;
    color: #1890ff;
  }
  
  .add-sensitive-btn {
    margin-left: 8px;
  }
}

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

.el-divider {
  margin: 0 20px;
  height: 360px;
  background-color: #e0e0e0;
}

.search-input {
  :deep(.el-input__inner) {
    height: 32px;
    line-height: 32px;
    font-size: 12px;
  }
  
  :deep(.el-input__icon) {
    line-height: 32px;
  }
}
</style>