<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%"
          :row-key="(row) => row.dataarea.id"
          :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.dataarea.dataarea}}</span>
            </template>
          </el-table-column>


          <el-table-column prop="ruleName" label="规则名" min-width="150">
            <template #default="{ row }">
              <el-select
                v-model="row.selectedRuleId"
                placeholder="请选择"
                size="small"
                style="width: 100%"
                :disabled="!isRowSelected(row)"
              >
                <el-option
                  v-for="option in row.data"
                  :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.data.find(item =>item.ruleid === row.selectedRuleId).ruleexample}}</div>
                <div class="sample-description" v-if="row.data.find(item =>item.ruleid === row.selectedRuleId) && row.data.find(item =>item.ruleid === row.selectedRuleId).remark">
                  {{ row.data.find(item =>item.ruleid === row.selectedRuleId).remark }}
                </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'

import {
  querybyprojectid,
} from '@/api/discover/index'
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 isSettingDefaults = ref(false)

// 规则数据（根据图片内容）
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: ''
  // }
])

// 过滤后的规则列表
const filteredRules = computed(() => {
  if (!searchText.value) return rulesData.value
  return rulesData.value.filter(item =>
    item.dataarea.dataarea.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

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

// 处理选择变化
const handleSelectionChange = (selection) => {
  if(isSettingDefaults.value === true) return
  console.log(selection)
  selectedRules.value = selection
  console.log('选择的规则：',selectedRules.value)
}

// 初始化选中状态
const initSelectedRules = async () => {
 try {
    isSettingDefaults.value = true
    rulesData.value = []
    const res = await querybyprojectid({dataarea: "",projectid: sessionStorage.getItem('projectId'),rulename: ""})
    rulesData.value = res.data.map(item =>(({
      ...item,
      status:'part',
      selectedRuleId: item.data.length === 0 ? '' : item.data.length === 1 ? item.data[0].ruleid : ( item.data.findIndex(x => x.defaulttype === '1').ruleid || ''),
      data: item.data.map(rule => (({
        ...rule,
        value :rule.ruleid,
        label: rule.name
      })))
    })))
    if(props.selectedTypes.length > 0) {
      nextTick(()=>{
        console.log('props.selectedTypes',props.selectedTypes)
        console.log('rulesData.value',rulesData.value)
        tableRef.value.clearSelection();
        props.selectedTypes.forEach(rule => {
          const targetRow = rulesData.value.find(r => r.selectedRuleId === rule.selectedRuleId);
          if (targetRow) {
            tableRef.value.toggleRowSelection(targetRow, true);
          }
        });
        selectedRules.value = [...props.selectedTypes];
      });

    }

  } finally {
    isSettingDefaults.value = false;
  }
  // nextTick(() => {
    // if (tableRef.value) {
    //   // 清除所有选择
    //   tableRef.value.clearSelection()
      // console.log('props.selectedTypes',props.selectedTypes)
        
      //   querybyprojectid({
      //     dataarea: "",
      //     projectid: sessionStorage.getItem('projectId'),
      //     rulename: ""
      //   }).then(res =>{ 

      //     rulesData.value = res.data.map(item =>(({
      //       ...item,
      //       status:'part',
      //       selectedRuleId: item.data.length === 0 ? '' : item.data.length === 1 ? item.data[0].ruleid : ( item.data.findIndex(x => x.defaulttype === '1').ruleid || ''),
      //       data: item.data.map(rule => (({
      //         ...rule,
      //         value :rule.ruleid,
      //         label: rule.name
      //       })))
      //     })))


      //     if(props.selectedTypes.length > 0){
      //       isSettingDefaults.value = true
      //       nextTick(()=>{
      //         tableRef.value.clearSelection()
              

      //         // tableRef.value.clearSelection()

      //         props.selectedTypes.forEach(rule => {
      //           tableRef.value.toggleRowSelection(rule, true)
      //           console.log('rule',rule)
      //         })

      //         isSettingDefaults.value = false

      //         selectedRules.value = [...props.selectedTypes]
      //       })



      //       // isSettingDefaults.value = false
      //     }

      //   })
}
  // })
// }

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

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

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

// 确认选择
const handleConfirm = () => {


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



  emit('confirm', selectedRules.value)
  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>