<template>
  <div class="crowd-task-edit">
    <el-card>
      <div slot="header" class="header">
        <span class="title">{{ pageTitle }}</span>
      </div>

      <el-steps :active="step" finish-status="success" align-center class="steps">
        <el-step title="基本信息" icon="el-icon-edit-outline" />
        <el-step title="规则组/奖励信息" icon="el-icon-set-up" />
      </el-steps>

      <!-- Step 1: 基本信息 -->
      <div v-show="step === 0" class="section">
        <el-form
          ref="baseForm"
          :model="form"
          :rules="rules"
          label-width="140px"
          style="max-width: 1000px; margin: 0 auto"
        >
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="客群名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" maxlength="40" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客群编号" prop="id">
                <el-input v-model="form.id" disabled placeholder="系统自动生成" suffix-icon="el-icon-circle-close" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客群描述" prop="description">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="客群任务开始日期" prop="startDate">
                <el-date-picker
                  v-model="form.startDate"
                  type="date"
                  placeholder="请选择日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客群任务结束日期" prop="endDate">
                <el-date-picker
                  v-model="form.endDate"
                  type="date"
                  placeholder="请选择日期"
                  value-format="yyyy-MM-dd"
                  :picker-options="endDateOptions"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- Step 2: 规则组信息 -->
      <div v-show="step === 1" class="section">
        <div class="section-title">规则组配置</div>
        <el-form label-width="140px" style="max-width: 1000px; margin: 0 auto 16px">
          <el-form-item label="规则组间运算逻辑" required>
            <el-select v-model="form.ruleGroupLogic" placeholder="请选择" style="width: 320px">
              <el-option label="and/且" value="AND" />
              <el-option label="or/或" value="OR" />
            </el-select>
          </el-form-item>
        </el-form>

        <el-table :data="form.ruleGroups" border style="width: 100%" empty-text="暂无规则组，请点击下方加号新增">
          <el-table-column prop="id" label="规则组编号" width="170" align="center" />
          <el-table-column prop="name" label="规则组名称" min-width="160" show-overflow-tooltip />
          <el-table-column prop="description" label="规则组描述" min-width="200" show-overflow-tooltip />
          <el-table-column label="规则组内逻辑" width="120" align="center">
            <template slot-scope="scope">{{ scope.row.logic === 'AND' ? 'and/且' : 'or/或' }}</template>
          </el-table-column>
          <el-table-column prop="ruleCount" label="规则个数" width="90" align="center" />
          <el-table-column label="操作" width="90" align="center">
            <template slot-scope="scope">
              <el-button
                type="danger" circle size="mini" icon="el-icon-delete" title="删除"
                @click="removeRuleGroup(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>

        <div class="add-row">
          <el-button type="primary" circle icon="el-icon-plus" @click="openAddDialog" />
        </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>

    <add-rule-group-dialog
      :visible.sync="dialogVisible"
      :exclude-ids="selectedRuleGroupIds"
      @save="onRuleGroupAdded"
    />
  </div>
</template>

<script>
import crowdTaskStore from '@/store/crowdTaskStore'
import AddRuleGroupDialog from '@/components/crowdTask/AddRuleGroupDialog.vue'

const emptyForm = () => ({
  name: '',
  id: '',
  description: '',
  startDate: '',
  endDate: '',
  ruleGroupLogic: '',
  ruleGroups: []
})

export default {
  name: 'CrowdTaskEdit',
  components: { AddRuleGroupDialog },
  data() {
    return {
      step: 0,
      form: emptyForm(),
      current: null,
      dialogVisible: false,
      rules: {
        name: [{ required: true, message: '请输入客群名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入客群描述', trigger: 'blur' }],
        startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
      }
    }
  },
  computed: {
    isEdit() {
      return this.$route.name === 'CrowdTaskEdit'
    },
    isCopy() {
      return this.$route.name === 'CrowdTaskCopy'
    },
    pageTitle() {
      if (this.isEdit) return '编辑客群任务'
      if (this.isCopy) return '复制客群任务'
      return '新建客群任务'
    },
    selectedRuleGroupIds() {
      return this.form.ruleGroups.map((r) => r.id)
    },
    endDateOptions() {
      const start = this.form.startDate
      return {
        disabledDate(d) {
          if (!start) return false
          return d.getTime() < new Date(start).getTime()
        }
      }
    }
  },
  created() {
    if (this.isEdit || this.isCopy) {
      const source = crowdTaskStore.getById(this.$route.params.id)
      if (!source) {
        this.$message.error('任务不存在')
        this.$router.replace('/customization/hsbc/crowd-tasks')
        return
      }
      this.current = source
      this.form = {
        name: this.isCopy ? source.name + '-副本' : source.name,
        id: this.isCopy ? '复制保存后生成' : source.id,
        description: source.description,
        startDate: source.startDate,
        endDate: source.endDate,
        ruleGroupLogic: source.ruleGroupLogic,
        ruleGroups: JSON.parse(JSON.stringify(source.ruleGroups || []))
      }
    } else {
      this.form.id = '保存后系统自动生成'
    }
  },
  methods: {
    handleNext() {
      this.$refs.baseForm.validate((ok) => {
        if (!ok) return
        if (this.form.startDate && this.form.endDate && this.form.endDate < this.form.startDate) {
          this.$message.error('结束日期不能早于开始日期')
          return
        }
        this.step = 1
      })
    },
    openAddDialog() {
      this.dialogVisible = true
    },
    onRuleGroupAdded(rg) {
      this.form.ruleGroups.push(rg)
      this.$message.success('已添加规则组')
    },
    removeRuleGroup(idx) {
      this.$confirm('确定移除该规则组吗？', '提示', {
        confirmButtonText: '移除', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.form.ruleGroups.splice(idx, 1)
      }).catch(() => {})
    },
    handleSave() {
      if (!this.form.ruleGroupLogic) {
        this.$message.error('请选择规则组间运算逻辑')
        return
      }
      if (this.form.ruleGroups.length === 0) {
        this.$message.error('请至少添加一条规则组')
        return
      }
      const payload = { ...this.form }
      if (this.isEdit) {
        // 校验状态下的编辑需回退到新建并重置运行信息
        const resetRun = this.current.status === 'verifying'
        crowdTaskStore.update(this.current.id, payload, { resetRun })
        this.$message.success(resetRun ? '保存成功，任务回退至新建状态，需重新运行' : '保存成功')
      } else {
        crowdTaskStore.create(payload)
        this.$message.success(this.isCopy ? '复制成功' : '创建成功')
      }
      this.$router.push('/customization/hsbc/crowd-tasks')
    },
    handleCancel() {
      this.$router.push('/customization/hsbc/crowd-tasks')
    }
  }
}
</script>

<style scoped>
.crowd-task-edit { padding: 0; }
.header { display: flex; align-items: center; justify-content: center; }
.title { font-size: 16px; font-weight: 600; color: #409EFF; }

.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;
}

.add-row { display: flex; padding: 16px 0; }

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