<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="targetType" required>
          <el-radio-group v-model="form.targetType" @change="handleTargetChange">
            <el-radio label="客群">客群</el-radio>
            <el-radio label="潜客">潜客</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="showCrowdSelect" 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 v-if="showProspectType" label="潜客类型" prop="prospectTypes" required>
          <el-checkbox-group v-model="form.prospectTypes">
            <el-checkbox label="无客户号潜客">无客户号潜客</el-checkbox>
            <el-checkbox label="标签潜客">标签潜客</el-checkbox>
          </el-checkbox-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 v-if="isClaimMode" label="领取有效期" required>
          <div style="display: flex; align-items: center; gap: 12px; width: 420px;">
            <el-date-picker
              v-model="form.claimStartTime"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="flex: 1;"
            ></el-date-picker>
            <span>至</span>
            <el-date-picker
              v-model="form.claimEndTime"
              type="datetime"
              placeholder="请选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="flex: 1;"
            ></el-date-picker>
          </div>
        </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: '',
    targetType: '客群',
    crowdList: [],
    prospectTypes: [],
    isAutoGrant: '是',
    grantMode: 'claim',
    equityList: [],
    claimStartTime: '',
    claimEndTime: '',
    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' }],
        targetType: [
          { required: true, message: '请选择发放对象', trigger: 'change' }
        ],
        crowdList: [
          { type: 'array', required: true, message: '请至少选择一个客群', trigger: 'change' }
        ],
        prospectTypes: [
          { type: 'array', 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
    },
    showCrowdSelect() {
      return this.form.targetType === '客群'
    },
    showProspectType() {
      return this.form.targetType === '潜客'
    },
    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,
        targetType: row.targetType || ((row.crowdList || []).length ? '客群' : '潜客'),
        crowdList: [...(row.crowdList || [])],
        prospectTypes: [...(row.prospectTypes || [])],
        grantMode: 'claim',
        equityList: [...(row.equityList || [])],
        claimStartTime: row.claimStartTime || '',
        claimEndTime: row.claimEndTime || '',
        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 || ''
      }
    },
    handleTargetChange(val) {
      if (val === '客群') {
        this.form.prospectTypes = []
      } else {
        this.form.crowdList = []
      }
    },
    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>
