<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
     class="custom-dialog"
    width="900px"
    destroy-on-close
    :before-close="handleClose"
  >
    <div class="domain-rule-dialog">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchText"
          placeholder="请输入数据域名称"
          size="small"
          prefix-icon="Search"
          clearable
          class="search-input"
        />
      </div>

      <div class="content-container">
        <!-- 左侧：选择数据域 -->
        <div class="left-panel">
          <div class="panel-header">
            <h4>选择数据域</h4>
          </div>
          <div class="list-container">
            <div
              v-for="item in filteredDataAreaList"
              :key="item.dataarea.id"
              class="list-item"
              :class="{ 'item-selected': selectedDataArea === item.dataarea.id }"
              @click="selectDataArea(item)"
            >
              <div class="item-content">
                <span class="item-text">{{ item.dataarea.dataarea }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：选择字段发现规则 -->
        <div class="right-panel">
          <div class="panel-header">
            <h4>选择字段发现规则</h4>
          </div>
          <div class="list-container">
            <div
              v-for="rule in combinedRuleList"
              :key="rule.ruleid"
              class="list-item"
              :class="{ 'item-selected': selectedRule === rule.ruleid }"
              @click="selectRule(rule)"
            >
              <div class="item-content">
                <span class="item-text">{{ rule.name }}</span>
                <span class="item-desc" v-if="rule.note">
                  {{ rule.note }}
                </span>
              </div>
            </div>
            <div v-if="combinedRuleList.length === 0" class="empty-tip">
              <el-empty description="暂无数据" />
            </极速>
          </div>
        </div>
      </div>
    </div>
      <!-- 底部按钮 -->
     
    </div>
     <template #footer>
        <!-- <el-button @click="handleReset">重置规则</el-button>
        <el-button type="primary" @click="handleConfirm">确定规则</el-button> -->


         <el-button type="primary" color="rgba(33, 103, 217, 1)" @click="handleReset">确定规则</el-button>
            <el-button type="primary" plain @click="handleConfirm">重置规则</el-button>
      </template>
  </el-dialog>
</template>

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

const props = defineProps({
    modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '设置数据域与字段发现规则'
  },
  dataAreaList: {
    type: Array,
    default: () => []
  },
  ruleList: {
    type: Array,
    default: () => []
  },
  selectedDataArea: {
    type: String,
    default: ''
  },
  selectedRule: {
    type: String, // 明确为字符串类型
    default: ''
  }
})


const emit = defineEmits(['update:modelValue', 'confirm', 'update:selectedDataArea', 'update:selectedRule','closeDialog','handleReset'])

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

const searchText = ref('')
const localSelectedDataArea = ref(props.selectedDataArea)
const localSelectedRule = ref(props.selectedRule)
const internalRuleList = ref([])
// 合并的规则列表：优先使用父组件传入的 ruleList，如果没有则使用内部生成的规则列表
const combinedRuleList = computed(() => {
  return props.ruleList.length > 0 ? props.ruleList : internalRuleList.value
})

// 过滤后的数据域列表
const filteredDataAreaList = computed(() => {
  if (!searchText.value) return props.dataAreaList
  return props.dataAreaList.filter(item =>
    item.dataarea.dataarea.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 选择数据域
const selectDataArea = (item) => {
  localSelectedDataArea.value = item.dataarea.id
  localSelectedRule.value = ''
  
  // 更新内部规则列表（如果父组件没有传入 ruleList）
  internalRuleList.value = item.data || []
  emit('update:selectedDataArea', item.dataarea.id)
  emit('update:selectedRule', '')
}

// 选择规则
const selectRule = (rule) => {
 localSelectedRule.value = rule.ruleid // 存储完整规则对象
  emit('update:selectedRule', rule.ruleid)
}

// 重置规则
const handleReset = () => {
  localSelectedDataArea.value = ''
  localSelectedRule.value = ''
  internalRuleList.value = []
  emit('update:selectedDataArea', '')
  emit('update:selectedRule', '')
  emit('handleReset')
  // ElMessage.info('规则已重置')
}

// 确认规则
const handleConfirm = () => {
  if (!localSelectedDataArea.value) {
    ElMessage.warning('请选择数据域')
    return
  }
  
  if (!localSelectedRule.value) {
    ElMessage.warning('请选择字段发现规则')
    return
  }

  const selectedDataArea = props.dataAreaList.find(
    item => item.dataarea.id === localSelectedDataArea.value
  )
// 从合并的规则列表中查找选中的规则
  const selectedRule = combinedRuleList.value.find(
    rule => rule.ruleid === localSelectedRule.value
  )
  console.log('selectedRule',selectedRule)
  emit('confirm', {
    domain: selectedDataArea.dataarea,
    domainValue: selectedDataArea.dataarea.id,
    rule: selectedRule.name,
    ruleValue: selectedRule.ruleid
  })
  
  dialogVisible.value = false
}

// 关闭弹窗
const handleClose = () => {
  console.log('关闭')
  internalRuleList.value = []
  dialogVisible.value = false
  emit('closeDialog')
}

// 监听外部传入的选中值变化
watch(() => props.selectedDataArea, (newVal) => {
  localSelectedDataArea.value = newVal
})

watch(() => props.selectedRule, (newVal) => {
  localSelectedRule.value = newVal
})

// 监听数据域列表变化，初始化选中状态
watch(() => props.dataAreaList, (newList) => {
  console.log('传入子组件的 左侧数组',newList)
  if (newList.length > 0 && localSelectedDataArea.value) {
    const selectedItem = newList.find(
      item => item.dataarea.id === localSelectedDataArea.value
    )
    if (selectedItem) {
      internalRuleList.value = selectedItem.data || []
    }
  }
}, { immediate: true })
// 监听父组件传入的 ruleList 变化
watch(() => props.ruleList, (newRuleList) => {
  console.log('父组件传入的 ruleList:', newRuleList)
}, { immediate: true })
</script>

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

  .content-container {
    display: flex;
    gap: 20px;
    height: 400px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }

  .left-panel,
  .right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
  }

  .panel-header {
    padding: 12px 16px;
    background: #f0f7ff;
    border-bottom: 1px solid #dcdfe6;
    
    h4 {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }
  }

  .list-container {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
  }

  .list-item {
    padding: 10px 12px;
    margin-bottom: 4px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
    border: 1px solid transparent;

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

    &.item-selected {
      background-color: #e6f7ff;
      border-color: #1890ff;
      
      .item-text {
        color: #1890ff;
        font-weight: 500;
      }
    }
  }

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

  .item-text {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
  }

  .item-count {
    font-size: 12px;
    color: #909399;
  }

  .item-desc {
    font-size: 12px;
    color: #909399;
    font-style: italic;
  }

  .empty-tip {
    padding: 20px;
    text-align: center;
    color: #909399;
    font-size: 13px;
  }

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

// 响应式设计
@media (max-width: 768px) {
  .domain-rule-dialog {
    .content-container {
      flex-direction: column;
      height: 500px;
    }
    
    .left-panel,
    .right-panel {
      flex: none;
      height: 200px;
    }
  }
}
</style>