<template>
  <el-dialog
    v-model="dialogVisible"
    :title="currentStep === 1 ? '添加策略 - 步骤1/2' : '添加策略 - 步骤2/2'"
    width="80%"
    :before-close="handleClose"
  >
    <!-- 步骤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="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入策略名称"
            clearable
          />
        </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 class="step-content">
      <div class="version-select">
        <span>根据发现版本设置脱敏:</span>
        <div class="flex-container align-center">
          <div>
            选择发现版本
          </div>
          <el-select  class="version-select-content flex1" v-model="selectedVersion" placeholder="选择发现版本">
            <el-option label="无版本" value="" />
            <el-option
              v-for="version in versions"
              :key="version"
              :label="version"
              :value="version"
            />
          </el-select>
        </div>
        
      </div>

      <div class="field-selection">
        <div class="tree-container">
          <el-tree
            :data="treeData"
            :props="treeProps"
            @node-click="handleNodeClick"
            highlight-current
          />
        </div>
        <el-divider direction="vertical" />
        <div class="table-container">
          <el-table :data="tableFields" border style="width: 100%" height="400px">
            <el-table-column prop="isPk" label="主键" width="80" align="center" fixed>
              <template #default="{ row }">
                <span v-if="row.isPk">PK</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="字段名" min-widthwidth="150" />
            <el-table-column prop="comment" label="注释" min-width="150" />
            <el-table-column prop="dataType" label="数据域" min-width="120" />
            <el-table-column prop="algorithm" label="脱敏算法"  min-width="180" />
            <el-table-column label="操作" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="handleSet(row)"
                  >设置</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

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

   <!-- 脱敏规则设置弹窗 -->
    <DesensitizationRuleDialog
      v-model="desensitizationDialogVisible"
      :current-field="currentField"
      @confirm="handleRuleConfirm"
    />
</template>

<script setup>
import DesensitizationRuleDialog from './DesensitizationRuleDialog.vue';

import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

const dialogVisible = ref(false);
const currentStep = ref(1);
const desensitizationDialogVisible = ref(false);
const currentField = ref({});

// 表单数据
const formData = reactive({
  name: '',
  remark: '',
});

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请填写策略名称', trigger: 'blur' },
  ],
});

// 步骤2数据
const selectedVersion = ref('');
const versions = ref(['v1.0', 'v2.0']);
const treeData = ref([
  {
    id: 'system1',
    label: '若依测试系统1',
    children: [
      {
        id: 'ry',
        label: 'ry',
        children: [
          {
            id: 'tables',
            label: '表',
            children: [
              {
                id: 'gen_table',
                label: 'gen_table',
                type: 'table'
              },
              {
                id: 'gen_table_column',
                label: 'gen_table_column',
                type: 'table'
              },
              {
                id: 'sys_config',
                label: 'sys_config',
                type: 'table'
              },
              {
                id: 'sys_dept',
                label: 'sys_dept',
                type: 'table'
              },
              {
                id: 'sys_dict_data',
                label: 'sys_dict_data',
                type: 'table'
              },
              {
                id: 'sys_dict_type',
                label: 'sys_dict_type',
                type: 'table'
              },
              {
                id: 'sys_job',
                label: 'sys_job',
                type: 'table'
              },
              {
                id: 'sys_job_log',
                label: 'sys_job_log',
                type: 'table'
              },
              {
                id: 'sys_logininfor',
                label: 'sys_logininfor',
                type: 'table'
              },
              {
                id: 'sys_menu',
                label: 'sys_menu',
                type: 'table'
              },
              {
                id: 'sys_notice',
                label: 'sys_notice',
                type: 'table'
              },
              {
                id: 'sys_oper_log',
                label: 'sys_oper_log',
                type: 'table'
              }
            ]
          }
        ]
      }
    ]
  }
]);
const treeProps = {
  children: 'children',
  label: 'label',
};
const tableFields = ref([]);
const algorithms = ref([
  { value: 'mask', label: '掩码处理' },
  { value: 'encrypt', label: '加密处理' },
  { value: 'hash', label: '哈希处理' },
]);

// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true;
  currentStep.value = 1;
  resetForm();
};

// 重置表单
const resetForm = () => {
  formData.name = '';
  formData.remark = '';
  selectedVersion.value = '';
  tableFields.value = [];
};

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

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

// 下一步
const handleNextStep = () => {
  if (!formData.name) {
    ElMessage.error('请填写策略名称');
    return;
  }
  currentStep.value = 2;
};

// 上一步
const handlePrevStep = () => {
  currentStep.value = 1;
};

// 确定
const handleConfirm = () => {
  // 这里调用API提交数据
  console.log('提交数据:', {
    ...formData,
    version: selectedVersion.value,
    fields: tableFields.value,
  });
  dialogVisible.value = false;
  ElMessage.success('策略添加成功');
};

// 树节点点击
const handleNodeClick = (node) => {
  if (node.type === 'table') {
    // 模拟根据表名获取字段
    fetchTableFields(node.label);
  }
};

// 获取表字段
const fetchTableFields = (tableName) => {
  // 这里应该是API调用，根据表名获取字段
  // 模拟数据
  if (tableName === 'gen_table_column') {
    tableFields.value = [
      {
        isPk: true,
        name: 'column_id',
        comment: '编号',
        dataType: 'bigint',
        algorithm: '',
      },
      {
        isPk: false,
        name: 'table_id',
        comment: '归属表编号',
        dataType: 'bigint',
        algorithm: '',
      },
      // 其他字段...
    ];
  } else {
    tableFields.value = [];
  }
};

// 设置字段
const handleSet = (row) => {
 currentField.value = row;
  desensitizationDialogVisible.value = true;
};

// 处理规则确认
const handleRuleConfirm = (ruleData) => {
  // 更新表格中的算法字段
  const fieldIndex = tableFields.value.findIndex(field => field.name === ruleData.fieldName);
  if (fieldIndex !== -1) {
    tableFields.value[fieldIndex].algorithm = ruleData.algorithm;
    ElMessage.success(`字段 ${ruleData.fieldName} 的脱敏规则已更新`);
  }
};

defineExpose({
  openDialog,
});
</script>

<style scoped lang="scss">
.step-content {
  min-height: 400px;
}

.version-select {
  margin-bottom: 20px;
}

.field-selection {
  display: flex;
  height: 400px;
}

.tree-container {
  width: 250px;
  height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}

.table-container {
  flex: 1;
  height: 100%;
  overflow-y: auto;
}

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

.el-divider {
  height: 100%;
  margin: 0 10px;
}

.flex-container { 
  display: flex;
}

.align-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.flex1 {
  flex: 1;
}
.version-select-content {
  margin-left: 15px;
}
</style>