<template>
  <div class="rule-group-edit">
    <el-card>
      <template #header>
        <div class="header">
          <span class="title">{{ isEdit ? '编辑客群规则任务' : '新增客群规则任务' }}</span>
          <span v-if="isEdit && current" class="rg-id">编号：{{ current.id }}</span>
        </div>
      </template>

      <!-- 步骤指示 -->
      <el-steps :active="step" finish-status="success" align-center class="steps">
        <el-step title="基本信息">
          <template #icon><el-icon><EditPen /></el-icon></template>
        </el-step>
        <el-step title="规则配置">
          <template #icon><el-icon><SetUp /></el-icon></template>
        </el-step>
      </el-steps>

      <!-- Step 1: 基本信息 -->
      <div v-show="step === 0" class="section">
        <div class="section-title">基本信息</div>
        <el-form
          ref="baseForm"
          :model="form"
          :rules="rules"
          label-width="120px"
          style="max-width: 760px; margin: 0 auto"
        >
          <el-form-item label="规则组名称" prop="name">
            <el-input v-model="form.name" placeholder="最长 40 字符" maxlength="40" show-word-limit />
          </el-form-item>
          <el-form-item label="规则组类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="opt in groupTypes"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规则逻辑" prop="logic">
            <el-radio-group v-model="form.logic">
              <el-radio label="AND">且（AND，全部满足）</el-radio>
              <el-radio label="OR">或（OR，任一满足）</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注说明">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="2"
              placeholder="规则组用途、命中场景等，最长 200 字符"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- Step 2: 规则配置 -->
      <div v-show="step === 1" class="section">
        <div class="section-title">
          规则组配置
          <span class="section-tip">规则之间使用「{{ form.logic === 'AND' ? '且' : '或' }}」逻辑组合</span>
        </div>

        <el-table :data="form.rules" border style="width: 100%" :empty-text="'暂无规则，请点击下方加号新增'">
          <el-table-column prop="metaCode" label="元规则编号" width="110" align="center" />
          <el-table-column label="元规则名称" min-width="180">
            <template #default="scope">{{ metaName(scope.row.metaCode) }}</template>
          </el-table-column>
          <el-table-column prop="ruleName" label="规则名称" min-width="160" show-overflow-tooltip />
          <el-table-column label="规则描述" min-width="240" show-overflow-tooltip>
            <template #default="scope">{{ buildDesc(scope.row) }}</template>
          </el-table-column>
          <el-table-column label="规则参数" min-width="220" show-overflow-tooltip>
            <template #default="scope">
              <span class="params-text">{{ buildParam(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                circle
                size="small"
                title="编辑"
                @click="openRuleDialog('edit', scope.row, scope.$index)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="warning"
                circle
                size="small"
                title="查看"
                @click="openRuleDialog('view', scope.row)"
              >
                <el-icon><View /></el-icon>
              </el-button>
              <el-button
                type="danger"
                circle
                size="small"
                title="删除"
                @click="removeRule(scope.$index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="add-rule-row">
          <el-button
            type="primary"
            circle
            @click="openRuleDialog('add')"
          >
            <el-icon><Plus /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="footer">
        <el-button v-if="step === 0" @click="handleCancel">取消</el-button>
        <el-button v-if="step === 1" @click="step = 0">上一步</el-button>
        <el-button v-if="step === 0" type="primary" @click="handleNext">下一步</el-button>
        <el-button v-if="step === 1" type="primary" @click="handleSave">完成</el-button>
      </div>
    </el-card>

    <rule-edit-dialog
      v-model="dialog.visible"
      :rule="dialog.rule"
      :mode="dialog.mode"
      @save="onRuleSave"
    />
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import ruleGroupStore from '@/store/ruleGroupStore'
import {
  GROUP_TYPES,
  getMetaRule,
  buildRuleDescription,
  buildRuleParams
} from '@/config/metaRules'
import RuleEditDialog from '@/components/ruleGroup/RuleEditDialog.vue'

export default {
  name: 'RuleGroupEdit',
  components: { RuleEditDialog },
  data() {
    return {
      step: 0,
      form: {
        name: '',
        type: '',
        logic: 'AND',
        description: '',
        rules: []
      },
      rules: {
        name: [
          { required: true, message: '请输入规则组名称', trigger: 'blur' },
          { max: 40, message: '最长 40 字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择规则组类型', trigger: 'change' }],
        logic: [{ required: true, message: '请选择规则逻辑', trigger: 'change' }]
      },
      groupTypes: GROUP_TYPES,
      current: null,
      dialog: { visible: false, mode: 'add', rule: null, editIndex: -1 }
    }
  },
  computed: {
    isEdit() {
      return !!this.$route.params.id
    }
  },
  created() {
    if (this.isEdit) {
      const target = ruleGroupStore.getById(this.$route.params.id)
      if (!target) {
        ElMessage.error('规则组不存在')
        this.$router.replace('/customization/hsbc/rule-groups')
        return
      }
      if (target.status === 'online') {
        ElMessage.warning('已上线规则组不可编辑')
        this.$router.replace(`/customization/hsbc/rule-groups/view/${target.id}`)
        return
      }
      this.current = target
      this.form = {
        name: target.name,
        type: target.type,
        logic: target.logic,
        description: target.description,
        rules: JSON.parse(JSON.stringify(target.rules || []))
      }
    }
  },
  methods: {
    metaName(code) {
      const m = getMetaRule(code)
      return m ? m.name : code
    },
    buildDesc(rule) {
      return buildRuleDescription(rule.metaCode, rule.config) || '-'
    },
    buildParam(rule) {
      return buildRuleParams(rule.metaCode, rule.config) || '-'
    },
    handleNext() {
      this.$refs.baseForm.validate((ok) => {
        if (ok) this.step = 1
      })
    },
    openRuleDialog(mode, rule = null, index = -1) {
      this.dialog = {
        visible: true,
        mode,
        rule: rule ? JSON.parse(JSON.stringify(rule)) : null,
        editIndex: index
      }
    },
    onRuleSave(rule) {
      if (this.dialog.mode === 'edit' && this.dialog.editIndex >= 0) {
        this.form.rules[this.dialog.editIndex] = rule
        ElMessage.success('已更新规则')
      } else {
        this.form.rules.push(rule)
        ElMessage.success('已添加规则')
      }
    },
    removeRule(idx) {
      ElMessageBox.confirm('确定要删除该条规则吗？', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.rules.splice(idx, 1)
      }).catch(() => {})
    },
    handleSave() {
      if (this.form.rules.length === 0) {
        ElMessage.error('请至少添加一条规则')
        return
      }
      if (this.isEdit) {
        ruleGroupStore.update(this.current.id, this.form)
        ElMessage.success('保存成功')
      } else {
        ruleGroupStore.create(this.form)
        ElMessage.success('创建成功')
      }
      this.$router.push('/customization/hsbc/rule-groups')
    },
    handleCancel() {
      this.$router.push('/customization/hsbc/rule-groups')
    }
  }
}
</script>

<style scoped>
.rule-group-edit { padding: 0; }
.header { display: flex; align-items: center; justify-content: space-between; }
.title { font-size: 16px; font-weight: 600; color: #409EFF; }
.rg-id { color: #909399; font-size: 13px; }

.steps { margin: 16px 0 32px; }

.section { margin-bottom: 24px; }
.section-title {
  font-size: 14px; font-weight: 600; color: #303133;
  background: #f5f7fa; padding: 10px 14px; border-radius: 4px;
  margin-bottom: 16px;
}
.section-tip { font-weight: normal; color: #909399; margin-left: 12px; font-size: 12px; }

.add-rule-row {
  display: flex; align-items: center;
  padding: 16px 0;
}

.params-text {
  font-family: 'Menlo', 'Consolas', monospace;
  color: #606266; font-size: 12px;
}

.footer { text-align: center; margin-top: 24px; padding-top: 16px; border-top: 1px solid #ebeef5; }
.footer .el-button { min-width: 100px; }
</style>
