<template>
  <el-dialog
    v-model="dialogVisible"
    title="设置脱敏规则"
    width="800px"
    destroy-on-close
    :before-close="handleClose"
    class="desensitization-rule-dialog"
  >
    <div class="rule-dialog-content">
      <div class="selection-container">
        <!-- 左侧：选择数据域 -->
        <div class="selection-section left-section">
          <div class="section-header">
            <div class="section-title">选择数据域</div>
          </div>
          <div class="section-content">
            <div
              v-for="(item,index) in dataAreaList"
              :key="item.id"
              class="selection-item"
              :class="{ selected: selectedDataArea && (selectedDataArea.id === item.id) }"
              @click="handleSelectDataArea(item)"
            >
              <div class="selection-indicator">
                <div class="indicator-dot" v-if="selectedDataArea && (selectedDataArea.id === item.id)"></div>
              </div>
              <div class="selection-text">{{ item.dataarea }}</div>
            </div>
          </div>
        </div>

        <!-- 右侧：选择字段脱敏规则 -->
        <div class="selection-section right-section">
          <div class="section-header">
            <div class="section-title">选择字段脱敏规则</div>
          </div>
          <div class="section-content" v-if="selectedDataArea && selectedDataArea.ruleList.length > 0">
            <div
              v-for="(item,index) in selectedDataArea.ruleList"
              :key="item.id"
              class="selection-item"
              :class="{ selected:selectedRule && (selectedRule.id === item.id) }"
              @click="selectRule(item)"
            >
              <div class="selection-indicator">
                <div class="indicator-dot" v-if="selectedRule && (selectedRule.id === item.id)"></div>
              </div>
              <div class="selection-text">{{ item.rulename }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleReset" :disabled="!selectedRule">重置规则</el-button>
        <el-button type="primary" @click="handleConfirm">确定规则</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  desensitizationruleQuery,
  // queryDesensitizationRules
} from '@/api/desensitizationStrategy'

const emit = defineEmits(['confirm'])

const props = defineProps({
  // 数据
  tschemas: {
    type: String,
    default: '',
  },
  // 当前的值
  dataTableLabel: [Number, String, Array],
  // 当未找到匹配的数据时，显示value
  table_field_id: {
    type: String,
    default: '',
  },
  dataSystemid: {
    type: String,
    default: '',
  }
})







// 控制弹窗显示
const dialogVisible = ref(false)

// 当前字段数据
const currentFieldData = ref({})

// 数据域列表（根据图片中的选项）
const dataAreaList = ref([

])

// // 脱敏规则列表（根据图片中的选项）
// const desensitizationRules = ref([
//   { id: '1', name: '测试算法' },
//   { id: '2', name: '测试算法1' }
// ])

// 选中的数据域
const selectedDataArea = ref(null) // 默认选中第一个

// 选中的脱敏规则
const selectedRule = ref(null) // 默认选中第一个


// 组件挂载时加载数据
onMounted(() => {

})



// 选择数据域
const handleSelectDataArea = (val) => {
  selectedDataArea.value = val
}

// 选择脱敏规则
const selectRule = (val) => {
  console.log(val)
  selectedRule.value = val
  console.log('selectedRule.value',selectedRule.value)
}

// 打开弹窗
const open = (fieldData = {}) => {
  console.log('open',fieldData)

  currentFieldData.value = fieldData
  console.log('currentFieldData.value',currentFieldData.value)
  initData(currentFieldData.value)
  dialogVisible.value = true
}

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

// 初始化数据
const initData = (val) => {


  desensitizationruleQuery().then(res=>{
    dataAreaList.value = res.data


     // 如果有传入的字段数据，可以预设选择
    if (val.dataareanameId) {
    
      selectedDataArea.value = dataAreaList.value.find(item => item.id === val.dataareanameId)
      console.log('123123',selectedDataArea.value)
      // selectedDataArea.value = val.dataarea_id
    }
    if (val.rulenameId && selectedDataArea.value) {
       selectedRule.value = selectedDataArea.value.ruleList.find(item => item.id === val.rulenameId)
     
    }
  })


 
  
  // 如果没有传入数据，重置表单
  // if (!fieldData || Object.keys(fieldData).length === 0) {
  //   resetForm()
  // }
}

// 重置规则
const handleReset = () => {
  selectedRule.value = ''
  ElMessage.info('规则已重置')
}

// 确认规则
const handleConfirm = () => {

  if (!selectedDataArea.value) {
    ElMessage.warning('请选择数据域')
    return
  }
  
  if (!selectedRule.value) {
    ElMessage.warning('请选择脱敏规则')
    return
  }



  let data = {
    dataSystemid:props.dataSystemid,
    dataareaid: selectedDataArea.value.id,
    dataareaname: selectedDataArea.value.dataarea,
    ruleId: selectedRule.value.id,
    rulename: selectedRule.value.rulename,
    table_field_id:props.table_field_id,
    tschemas:props.tschemas,
    names:props.dataTableLabel
  } 
  let str = `${props.tschemas}.${props.dataTableLabel}.${props.table_field_id}`


  emit('confirm',str,data)
  
  close()
  // ElMessage.success('脱敏规则设置成功')
}

// 关闭弹窗
const handleClose = (done) => {
  // 如果有未保存的更改，可以提示用户
  if (selectedDataArea.value || selectedRule.value) {
    ElMessageBox.confirm('确定要关闭吗？未保存的更改将会丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      resetForm()
      done()
    }).catch(() => {
      // 取消关闭
    })
  } else {
    resetForm()
    done()
  }
}

// 重置表单
const resetForm = () => {
  dataAreaList.value = []
  selectedDataArea.value = null
  selectedRule.value = null
  currentFieldData.value = {}
}

// 暴露方法给父组件
defineExpose({
  open,
  close
})
</script>

<style scoped>
.desensitization-rule-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.rule-dialog-content {
  padding: 10px;
}

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

.selection-section {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.section-header {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f5f5;
}

.section-title {
  font-weight: bold;
  color: #303133;
  font-size: 14px;
  text-align: center;
}

.section-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.selection-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 4px;
  margin-bottom: 4px;
}

.selection-item:hover {
  background-color: #f5f7fa;
}

.selection-item.selected {
  background-color: #ecf5ff;
  border-color: #409EFF;
}

.selection-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.selection-indicator {
  width: 16px;
  height: 16px;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.selection-item.selected .selection-indicator {
  border-color: #409EFF;
}

.indicator-dot {
  width: 8px;
  height: 8px;
  background-color: #409EFF;
  border-radius: 50%;
}

.selection-text {
  font-size: 13px;
  color: #606266;
  flex: 1;
}

.selection-item.selected .selection-text {
  color: #409EFF;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.left-section {
  border-right: 2px solid #e4e7ed;
}

.right-section {
  border-left: 2px solid #e4e7ed;
}
</style>