<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择规则"
    width="800px"
    :before-close="handleClose"
  >
    <div class="sensitive-type-dialog">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchText"
          placeholder="搜索规则"
          size="small"
          prefix-icon="Search"
          clearable
          class="search-input"
        />
      </div>

      <!-- 规则表格 -->
      <div class="rules-table-container">
        <el-table
          ref="tableRef"
          :data="filteredRules"
          style="width: 100%"
          :header-cell-style="{ background: '#f0f7ff', color: '#606266' }"
          :cell-style="{ padding: '8px 0' }"
          @selection-change="handleSelectionChange"
        >
          <!-- 选择列 -->
          <el-table-column type="selection" width="55" align="center" />
          
          <!-- 数据域列 -->
          <el-table-column prop="domain" label="数据域" width="120">
            <template #default="{ row }">
              <span class="domain-text">{{ row.domain }}</span>
            </template>
          </el-table-column>

          <!-- 规则名列 -->
          <el-table-column prop="ruleName" label="规则名" min-width="150">
            <template #default="{ row }">
              <el-select
                v-model="row.selectedRule"
                placeholder="请选择"
                size="small"
                style="width: 100%"
                :disabled="!isRowSelected(row)"
              >
                <el-option
                  v-for="option in row.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 样例列 -->
          <el-table-column prop="sample" label="样例" min-width="200">
            <template #default="{ row }">
              <div class="sample-content">
                <div class="sample-text">{{ row.sample }}</div>
                <div class="sample-description" v-if="row.description">
                  {{ row.description }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 底部按钮 -->
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  selectedTypes: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const searchText = ref('')
const tableRef = ref()
const selectedRules = ref([])

// 规则数据（根据图片内容）
const rulesData = ref([
  {
    id: 'mixed_data',
    domain: '混合数据域',
    options: [
      { value: '566546', label: '566546' },
      { value: '345', label: '345' }
    ],
    selectedRule: '566546',
    sample: '345',
    description: '按混合证件号字段查询'
  },
  {
    id: 'smart_data',
    domain: '智能数据域',
    options: [
      { value: 'option1', label: '请选择' },
      { value: 'option2', label: '智能规则1' },
      { value: 'option3', label: '智能规则2' }
    ],
    selectedRule: 'option1',
    sample: '',
    description: ''
  },
  {
    id: 'general_rule',
    domain: '通用规则',
    options: [
      { value: 'general1', label: '通用规则1' },
      { value: 'general2', label: '通用规则2' }
    ],
    selectedRule: 'general1',
    sample: '310000000100116, 9131000...',
    description: '按混合证件号字段查询'
  },
  {
    id: 'decrypt_data',
    domain: '解密数据',
    options: [
      { value: 'decrypt1', label: '解密规则1' },
      { value: 'decrypt2', label: '解密规则2' }
    ],
    selectedRule: 'decrypt1',
    sample: '',
    description: ''
  },
  {
    id: 'mixed_id',
    domain: '混合证件号',
    options: [
      { value: 'mixed_id1', label: '混合证件号规则1' },
      { value: 'mixed_id2', label: '混合证件号规则2' }
    ],
    selectedRule: 'mixed_id1',
    sample: '310000000100116, 9131000...',
    description: '按混合证件号字段查询'
  },
  {
    id: 'email',
    domain: '电子邮件',
    options: [
      { value: 'email1', label: '邮箱规则1' },
      { value: 'email2', label: '邮箱规则2' }
    ],
    selectedRule: 'email1',
    sample: '605396113@qq.com',
    description: '按邮箱字段查找'
  },
  {
    id: 'social_security',
    domain: '社保卡号',
    options: [
      { value: 'ss1', label: '社保规则1' },
      { value: 'ss2', label: '社保规则2' }
    ],
    selectedRule: 'ss1',
    sample: '11',
    description: '按邮箱字段查找'
  },
  {
    id: 'business_license',
    domain: '营业执照',
    options: [
      { value: 'bl1', label: '营业执照规则1' },
      { value: 'bl2', label: '营业执照规则2' }
    ],
    selectedRule: 'bl1',
    sample: '310000000100116, 9131000...',
    description: '按营业执照字段查询'
  },
  {
    id: 'postal_code',
    domain: '邮政编码',
    options: [
      { value: 'pc1', label: '邮编规则1' },
      { value: 'pc2', label: '邮编规则2' }
    ],
    selectedRule: 'pc1',
    sample: '321300, 322300, 316100',
    description: '邮政编码字段查找'
  },
  {
    id: 'chinese_address',
    domain: '中文地址',
    options: [
      { value: 'address1', label: '地址规则1' },
      { value: 'address2', label: '地址规则2' }
    ],
    selectedRule: 'address1',
    sample: '北京市朝阳区建国路93号万',
    description: '中文地址字段查找'
  }
])

// 过滤后的规则列表
const filteredRules = computed(() => {
  if (!searchText.value) return rulesData.value
  return rulesData.value.filter(rule =>
    rule.domain.toLowerCase().includes(searchText.value.toLowerCase()) ||
    rule.sample.toLowerCase().includes(searchText.value.toLowerCase()) ||
    rule.description.toLowerCase().includes(searchText.value.toLowerCase()) ||
    rule.options.some(option => 
      option.label.toLowerCase().includes(searchText.value.toLowerCase())
    )
  )
})

// 检查行是否被选中
const isRowSelected = (row) => {
  return selectedRules.value.some(selected => selected.id === row.id)
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRules.value = selection
}

// 初始化选中状态
const initSelectedRules = () => {
  console.log(123)
  nextTick(() => {
    if (tableRef.value) {
      // 清除所有选择
      tableRef.value.clearSelection()
      console.log('props.selectedTypes',props.selectedTypes)
      // 设置初始选中
      rulesData.value.forEach(rule => {
        console.log('props.selectedTypes',props.selectedTypes)
        if (props.selectedTypes.includes(rule.id)) {
          const row = rulesData.value.find(r => r.id === rule.id)
          if (row) {
            tableRef.value.toggleRowSelection(row, true)
          }
        }
      })
    }
  })
}

// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true
  initSelectedRules()
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

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

// 确认选择
const handleConfirm = () => {
  const validSelectedRules = selectedRules.value.filter(rule => 
    rule.selectedRule && rule.selectedRule !== 'option1' // 排除"请选择"
  )

  if (validSelectedRules.length === 0) {
    ElMessage.warning('请至少选择一个有效规则')
    return
  }

  const result = validSelectedRules.map(rule => ({
    id: rule.id,
    domain: rule.domain,
    ruleName: rule.selectedRule,
    sample: rule.sample,
    description: rule.description
  }))

  emit('confirm', result)
  dialogVisible.value = false
}

// 监听对话框显示状态
watch(dialogVisible, (newVal) => {
  if (newVal) {
    initSelectedRules()
  }
})

defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
.sensitive-type-dialog {
  .search-section {
    margin-bottom: 16px;
    
    .search-input {
      width: 100%;
      
      :deep(.el-input__inner) {
        height: 32px;
      }
    }
  }

  .rules-table-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 20px;
    max-height: 400px;
    overflow-y: auto;

    :deep(.el-table) {
      .el-table__header-wrapper {
        th {
          background: #f0f7ff !important;
          font-weight: 600;
          padding: 8px 0;
        }
      }

      .el-table__body-wrapper {
        .el-table__row {
          &.current-row {
            background-color: #f0f7ff !important;
          }
          
          &:hover {
            background-color: #f5f7fa !important;
          }
        }
      }
    }
  }

  .domain-text {
    font-weight: 500;
    color: #303133;
  }

  .sample-content {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .sample-text {
    font-size: 12px;
    color: #606266;
    word-break: break-all;
  }

  .sample-description {
    font-size: 11px;
    color: #909399;
    font-style: italic;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid #e0e0e0;
  }
}

// 选中行的样式
:deep(.el-table) {
  .current-row {
    td {
      background-color: #f0f7ff !important;
    }
  }
  
  .el-checkbox__input.is-disabled {
    .el-checkbox__inner {
      background-color: #f5f7fa;
      border-color: #dcdfe6;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .sensitive-type-dialog {
    .rules-table-container {
      :deep(.el-table) {
        .el-table__header {
          th {
            padding: 6px 0;
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>