<template>
  <div class="equity-grant-campaign-edit">
    <el-card>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        style="max-width: 920px; margin: 0 auto"
      >
        <el-form-item v-if="isEdit" label="发放计划 ID">
          <el-input :value="form.id" disabled style="width:320px" />
        </el-form-item>
        <el-form-item label="发放计划名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入发放计划名称"
            maxlength="50"
            show-word-limit
            style="width:420px"
          />
        </el-form-item>
        <el-form-item label="发放计划开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:320px"
          />
        </el-form-item>
        <el-form-item label="发放计划结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:320px"
          />
        </el-form-item>
        <el-form-item label="选择客群" prop="crowdList">
          <el-select
            v-model="form.crowdList"
            multiple
            filterable
            collapse-tags
            placeholder="请选择客群（可多选，支持搜索）"
            style="width:420px"
          >
            <el-option
              v-for="item in crowdOptions"
              :key="item.id"
              :label="`${item.name} (${item.id})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否自动发放" prop="isAutoGrant" required>
          <el-radio-group v-model="form.isAutoGrant">
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="获取方式" prop="grantMode" required>
          <el-radio-group v-model="form.grantMode" @change="handleGrantModeChange">
            <el-radio label="claim">用户领取</el-radio>
            <el-radio label="direct">直接发放</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择权益" prop="equityList" required>
          <el-select
            v-if="isClaimMode"
            v-model="form.equityList"
            multiple
            filterable
            collapse-tags
            placeholder="请选择借记卡权益（可多选）"
            style="width:420px"
          >
            <el-option
              v-for="item in equityOptions"
              :key="item.productId"
              :label="`${item.equityName} (${item.productId})`"
              :value="item.productId"
            />
          </el-select>
          <el-select
            v-else
            v-model="singleEquityId"
            filterable
            placeholder="请选择借记卡权益（仅可单选）"
            style="width:420px"
          >
            <el-option
              v-for="item in equityOptions"
              :key="item.productId"
              :label="`${item.equityName} (${item.productId})`"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单客户权益数量" required>
          <div class="grant-row">
            <el-select v-model="form.grantCycle" placeholder="类型" style="width:140px">
              <el-option label="整个周期" value="total" />
              <el-option label="每月" value="monthly" />
              <el-option label="每季度" value="quarterly" />
              <el-option label="每年" value="yearly" />
            </el-select>
            <el-input-number
              v-model="form.grantQuantity"
              :min="1"
              :max="9999"
              :controls-position="'right'"
              style="width:200px;margin-left:12px"
            />
            <span class="grant-suffix">个</span>
          </div>
        </el-form-item>
        <el-form-item label="短信通知" prop="smsTemplateId" required>
          <el-select
            v-model="form.smsTemplateId"
            placeholder="请选择短信模板"
            style="width:420px"
            @change="handleSmsTemplateChange"
          >
            <el-option
              v-for="item in smsTemplateOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <div v-if="form.smsTemplate" class="sms-template-preview">{{ form.smsTemplate }}</div>
        </el-form-item>
      </el-form>

      <div class="footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import crowdTaskStore from '@/store/crowdTaskStore'

function emptyForm() {
  return {
    id: '',
    name: '',
    startTime: '',
    endTime: '',
    crowdList: [],
    isAutoGrant: '是',
    grantMode: 'claim',
    equityList: [],
    grantCycle: 'total',
    grantQuantity: 1,
    validity: { type: 'fixed', fixedRange: [], relativeDays: 30 },
    smsTemplateId: '',
    smsTemplate: ''
  }
}

const SMS_TEMPLATE_OPTIONS = [
  { id: 'GRANT_SMS_001', name: '发放成功通用模板', content: '【银行】尊敬的${customerName}，您已获得${productName}权益，发放时间：${grantTime}，请于${expireDate}前使用。' },
  { id: 'GRANT_SMS_002', name: '发放成功-含查看入口', content: '【银行】尊敬的${customerName}，您已获得${productName}权益，有效期至${expireDate}，请登录APP查看详情。' },
  { id: 'GRANT_SMS_003', name: '发放成功-简洁版', content: '【银行】${customerName}您好，${productName}已为您发放成功，有效期至${expireDate}。' }
]

export default {
  name: 'EquityGrantCampaignEdit',
  data() {
    return {
      form: emptyForm(),
      equityOptions: [],
      smsTemplateOptions: SMS_TEMPLATE_OPTIONS,
      rules: {
        name: [{ required: true, message: '请输入发放计划名称', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        crowdList: [
          { type: 'array', required: true, message: '请至少选择一个客群', trigger: 'change' }
        ],
        grantMode: [
          { required: true, message: '请选择获取方式', trigger: 'change' }
        ],
        equityList: [
          {
            validator: (rule, value, cb) => {
              if (!value || value.length === 0) {
                return cb(new Error(this.isClaimMode ? '请至少选择一个权益' : '请选择一个权益'))
              }
              cb()
            },
            trigger: 'change'
          }
        ],
        smsTemplateId: [
          { required: true, message: '请选择短信模板', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    isEdit() {
      return this.$route.name === 'EquityGrantCampaignEdit'
    },
    isCopy() {
      return this.$route.name === 'EquityGrantCampaignCopy'
    },
    crowdOptions() {
      return crowdTaskStore.list
    },
    isClaimMode() {
      return this.form.grantMode === 'claim'
    },
    singleEquityId: {
      get() {
        return (this.form.equityList && this.form.equityList[0]) || ''
      },
      set(val) {
        this.form.equityList = val ? [val] : []
      }
    }
  },
  async created() {
    await this.fetchEquityOptions()
    if (this.isEdit || this.isCopy) await this.loadDetail()
  },
  methods: {
    async fetchEquityOptions() {
      const res = await request.get('/api/equity/list', { params: { shelfStatus: '已上架' } })
      this.equityOptions = res.data || []
    },
    async loadDetail() {
      const id = this.$route.params.id
      const res = await request.get('/api/equity-grant-campaign/detail', { params: { id } })
      const row = res.data
      if (!row) {
        ElMessage.error('发放计划不存在')
        this.$router.replace('/customization/hsbc/equity-grant-campaign')
        return
      }
      if (this.isEdit) {
        const now = Date.now()
        const s = new Date(row.startTime).getTime()
        const e = new Date(row.endTime).getTime()
        if (now >= s && now <= e) {
          ElMessage.warning('进行中的发放计划不可编辑')
          this.$router.replace('/customization/hsbc/equity-grant-campaign')
          return
        }
      }
      const v = row.validity || { type: 'fixed', fixedRange: [], relativeDays: 30 }
      this.form = {
        id: this.isCopy ? '' : row.id,
        name: this.isCopy ? row.name + '-副本' : row.name,
        startTime: row.startTime,
        endTime: row.endTime,
        crowdList: [...(row.crowdList || [])],
        grantMode: row.grantMode || 'claim',
        equityList: [...(row.equityList || [])],
        grantCycle: row.grantCycle || 'total',
        grantQuantity: row.grantQuantity || 1,
        validity: {
          type: v.type || 'fixed',
          fixedRange: Array.isArray(v.fixedRange) ? [...v.fixedRange] : [],
          relativeDays: v.relativeDays || 30
        },
        smsTemplateId: row.smsTemplateId || '',
        smsTemplate: row.smsTemplate || ''
      }
    },
    handleGrantModeChange(mode) {
      if (mode === 'direct' && this.form.equityList.length > 1) {
        this.form.equityList = [this.form.equityList[0]]
      }
    },
    handleSmsTemplateChange(id) {
      const tpl = this.smsTemplateOptions.find(i => i.id === id)
      this.form.smsTemplate = tpl ? tpl.content : ''
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.form.startTime && this.form.endTime && this.form.startTime >= this.form.endTime) {
          ElMessage.warning('结束时间必须晚于开始时间')
          return
        }
        if (!this.form.grantQuantity || this.form.grantQuantity < 1) {
          ElMessage.warning('请输入单客户权益数量')
          return
        }
        if (!this.isClaimMode && this.form.equityList.length !== 1) {
          ElMessage.warning('直接发放仅支持选择一个权益')
          return
        }
        if (!this.form.smsTemplateId) {
          ElMessage.warning('请选择短信模板')
          return
        }
        await request.post('/api/equity-grant-campaign/save', this.form)
        ElMessage.success(this.isEdit ? '保存成功' : this.isCopy ? '复制成功' : '新建成功')
        this.$router.push('/customization/hsbc/equity-grant-campaign')
      })
    },
    handleCancel() {
      this.$router.push('/customization/hsbc/equity-grant-campaign')
    }
  }
}
</script>

<style scoped>
.equity-grant-campaign-edit { padding: 0; }
.grant-row { display: flex; align-items: center; }
.grant-suffix { margin-left: 8px; color: #606266; }
.validity-row { margin-top: 8px; display: flex; align-items: center; }
.equity-grant-campaign-edit >>> .el-form-item__content { display: block; }
.footer {
  text-align: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}
.footer .el-button { min-width: 100px; }
.sms-template-preview {
  margin-top: 8px;
  padding: 10px 12px;
  background: #f5f7fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  word-break: break-all;
}
</style>
