<template>
  <div class="add-equity-product">
    <el-card>
      <template #header>
        <div class="header-title">
          <span>添加权益</span>
        </div>
      </template>

      <!-- 步骤条 -->
      <el-steps :active="activeStep" simple style="margin-bottom: 20px;">
        <el-step title="填写权益信息">
          <template #icon><el-icon><InfoFilled /></el-icon></template>
        </el-step>
        <el-step title="设置规则">
          <template #icon><el-icon><Setting /></el-icon></template>
        </el-step>
        <el-step title="更多设置">
          <template #icon><el-icon><Monitor /></el-icon></template>
        </el-step>
      </el-steps>

      <!-- 步骤内容 -->
      <div v-show="activeStep === 0">
        <!-- 填写权益信息 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="section-title">基本信息</div>
          </template>
          <el-form :model="form" label-width="120px" label-position="left">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="是否权益平台兑换" required label-width="150px">
                  <el-radio-group v-model="form.isPlatformExchange" @change="handlePlatformExchangeChange">
                    <el-radio label="是"></el-radio>
                    <el-radio label="否"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.isPlatformExchange === '是'">
                <el-form-item label="商品类型" required>
                  <el-radio-group v-model="form.productType" @change="handleProductTypeChange">
                    <el-radio label="券码"></el-radio>
                    <el-radio label="微信立减金"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.isPlatformExchange === '是' && form.productType === '微信立减金'">
                <el-form-item label="选择权益" required>
                  <el-input
                    v-model="form.rongshuProduct"
                    placeholder="请选择权益"
                    readonly
                  >
                    <template #append>
                      <el-button @click="rongshuDialogVisible = true">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.isPlatformExchange === '是' && form.productType === '微信立减金' && form.rongshuSkuNo">
                <el-form-item label="SKU编号">
                  <el-input v-model="form.rongshuSkuNo" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" v-if="form.isPlatformExchange === '否'">
                <el-form-item label="外部权益链接" required>
                  <el-select v-model="form.externalLink" placeholder="请选择外部权益链接">
                    <el-option label="太古地产" value="太古地产"></el-option>
                    <el-option label="龙腾" value="龙腾"></el-option>
                    <el-option label="h5链接" value="h5链接"></el-option>
                    <el-option label="小程序链接" value="小程序链接"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.isPlatformExchange === '否' && form.externalLink === 'h5链接'" :gutter="20">
                <el-form-item label="h5链接" required>
                  <el-input v-model="form.customLink" placeholder="请输入h5链接"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.isPlatformExchange === '否'">
                <el-form-item required label-width="140px">
                  <template #label>
                    <span style="white-space: nowrap;">是否有详情页<el-tooltip content="没有详情页时直接从首页/列表页/组装页直接跳转" placement="top"><el-icon class="tip-icon"><QuestionFilled /></el-icon></el-tooltip></span>
                  </template>
                  <el-radio-group v-model="form.externalJumpMethod">
                    <el-radio-button label="没有"></el-radio-button>
                    <el-radio-button label="有"></el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="form.isPlatformExchange === '否' && form.externalLink === '小程序链接'">
              <el-col :span="8">
                <el-form-item label="小程序appid" required>
                  <el-input v-model="form.miniAppId" placeholder="请输入小程序appid"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="小程序页面地址" required label-width="140px">
                  <el-input v-model="form.miniAppPath" placeholder="请输入小程序页面地址"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <template v-if="form.isPlatformExchange === '是'">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="权益名称" required>
                    <el-input v-model="form.equityName" maxlength="40" placeholder="请输入权益名称"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="form.productType === '微信立减金'">
                <el-col :span="8">
                  <el-form-item label="库存数" required>
                    <el-input-number
                      v-model="form.stockCount"
                      :min="0"
                      :max="100000"
                      style="width: 100%"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item required>
                    <template #label>
                      <span>权益图标
                        <el-tooltip content="展示在权益首页和权益列表页" placement="top">
                          <el-icon class="tip-icon"><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </span>
                    </template>
                    <el-upload
                      action=""
                      :auto-upload="false"
                      :file-list="form.listIcon"
                      :on-change="file => handleUpload(file, 'listIcon')"
                      :on-preview="handlePreviewImage"
                      :on-remove="() => form.listIcon = []"
                      :class="{ 'upload-hide-trigger': form.listIcon.length >= 1 }"
                      :limit="1"
                      list-type="picture-card"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-size-tip">建议尺寸：80x80px</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>

            <template v-else-if="form.isPlatformExchange === '否'">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="权益名称" required>
                    <el-input v-model="form.equityName" maxlength="40" placeholder="请输入权益名称"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="form.externalJumpMethod === '没有'">
                <el-col :span="8">
                  <el-form-item required>
                    <template #label>
                      <span>权益图标
                        <el-tooltip content="展示在权益首页和权益列表页" placement="top">
                          <el-icon class="tip-icon"><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </span>
                    </template>
                    <el-upload
                      action=""
                      :auto-upload="false"
                      :file-list="form.listIcon"
                      :on-change="file => handleUpload(file, 'listIcon')"
                      :on-preview="handlePreviewImage"
                      :on-remove="() => form.listIcon = []"
                      :class="{ 'upload-hide-trigger': form.listIcon.length >= 1 }"
                      :limit="1"
                      list-type="picture-card"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-size-tip">建议尺寸：80x80px</div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="form.externalJumpMethod === '有'" :gutter="20">
                <el-col :span="8">
                  <el-form-item required>
                    <template #label>
                      <span>权益图标
                        <el-tooltip content="展示在权益首页和权益列表页" placement="top">
                          <el-icon class="tip-icon"><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </span>
                    </template>
                    <el-upload
                      action=""
                      :auto-upload="false"
                      :file-list="form.listIcon"
                      :on-change="file => handleUpload(file, 'listIcon')"
                      :on-preview="handlePreviewImage"
                      :on-remove="() => form.listIcon = []"
                      :class="{ 'upload-hide-trigger': form.listIcon.length >= 1 }"
                      :limit="1"
                      list-type="picture-card"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-size-tip">建议尺寸：80x80px</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </el-form>
        </el-card>

        <!-- 详情信息 -->
        <el-card v-if="shouldShowDetailCard" shadow="never" class="section-card">
          <template #header>
            <div class="section-title">详情信息</div>
          </template>
          <el-form :model="form" label-width="120px" label-position="left">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="权益主图" required>
                  <el-upload
                    action=""
                    :auto-upload="false"
                    :file-list="form.mainImage"
                    :on-change="file => handleUpload(file, 'mainImage')"
                    :on-preview="handlePreviewImage"
                    :on-remove="() => form.mainImage = []"
                    :class="{ 'upload-hide-trigger': form.mainImage.length >= 1 }"
                    :limit="1"
                    list-type="picture-card"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-upload>
                  <div class="upload-size-tip">建议尺寸：716x400px</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="权益介绍">
                  <el-input
                    v-model="form.introduction"
                    type="textarea"
                    :rows="4"
                    maxlength="500"
                    show-word-limit
                    placeholder="请输入权益介绍"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="权益有效期" required>
                  <template v-if="form.isPlatformExchange === '是'">
                    <el-radio-group v-model="form.validityType">
                      <el-radio label="fromGrantPlan">取自发放计划</el-radio>
                      <el-radio label="custom">自定义输入</el-radio>
                    </el-radio-group>
                    <el-input
                      v-if="form.validityType === 'custom'"
                      v-model="form.validityText"
                      maxlength="50"
                      show-word-limit
                      placeholder="请输入权益有效期"
                      style="margin-top: 8px;"
                    ></el-input>
                  </template>
                  <el-input
                    v-else
                    v-model="form.validityText"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入权益有效期"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="权益内容" required>
                  <quill-editor v-model:content="form.overview" content-type="html" :options="quillOptions"></quill-editor>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="权益说明" required>
                  <quill-editor v-model:content="form.details" content-type="html" :options="quillOptions"></quill-editor>
                </el-form-item>
              </el-col>
            </el-row>
            <template v-if="form.isPlatformExchange === '是'">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item>
                    <template #label>
                      <span>下单成功短信
                        <el-tooltip placement="top">
                          <template #content>
                            此模板为权益支付成功，发送给持卡人的短信模板；<br/>
                            开启后需选择短信模板，关闭则不发送短信。<br/>
                            占位符如下：<br/>
                            权益名称：${productName}<br/>
                            结束日期：${expireDate}<br/>
                            卡号：${exchangeNum}<br/>
                            卡密：${exchangePwd}<br/>
                            券码使用路径：${qrCodeDownPaths}
                          </template>
                          <el-icon class="tip-icon"><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </span>
                    </template>
                    <el-switch v-model="form.smsEnabled" @change="handleSmsEnabledChange"></el-switch>
                    <template v-if="form.smsEnabled">
                      <div style="max-width: 600px;background: #f1f2f5;padding: 20px;margin-top: 10px;flex-basis: 100%;">
                        <el-select
                          v-model="form.smsTemplateId"
                          placeholder="请选择短信模板"
                          style="width: 100%"
                          @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>
                      </div>
                    </template>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="form.productType === '券码'">
                <el-col :span="8">
                  <el-form-item label="领取成功按钮" required>
                    <el-input v-model="form.successButtonText" placeholder="请输入按钮文案"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </el-form>
        </el-card>

      </div>

      <div v-show="activeStep === 1">
        <!-- 展示规则 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="section-title">展示规则</div>
          </template>
          <div class="rule-section">
            <el-form :model="form" label-width="120px" label-position="left">
              <el-form-item label="展示时间限制">
                <el-switch v-model="form.showTimeEnabled"></el-switch>
                <template v-if="form.showTimeEnabled">
                  <div style="display: flex;max-width: 600px;background: #f1f2f5;padding: 20px;margin-top: 10px;flex-basis: 100%;">
                    <el-date-picker
                      v-model="form.showStartTime"
                      type="datetime"
                      placeholder="请选择开始时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                    ></el-date-picker>
                    <div style="width: 50px;text-align: center;">-</div>
                    <el-date-picker
                      v-model="form.showEndTime"
                      type="datetime"
                      placeholder="请选择结束时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                    ></el-date-picker>
                  </div>
                </template>
              </el-form-item>
              <el-form-item label="展示客群限制">
                <el-switch v-model="form.showGroupEnabled"></el-switch>
                <template v-if="form.showGroupEnabled">
                  <div style="display: flex;max-width: 600px;background: #f1f2f5;padding: 20px;margin-top: 10px;flex-basis: 100%;">
                    <el-select v-model="form.showGroupTagIds" multiple filterable placeholder="请选择客群" style="width: 100%">
                      <el-option label="客群A" value="客群A"></el-option>
                      <el-option label="客群B" value="客群B"></el-option>
                      <el-option label="客群C" value="客群C"></el-option>
                    </el-select>
                  </div>
                </template>
              </el-form-item>
            </el-form>
          </div>
        </el-card>

        <!-- 领取规则 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="section-title">领取规则</div>
          </template>
          <div class="rule-section">
            <el-form :model="form" label-width="120px" label-position="left">
              <el-form-item label="领取时间限制">
                <el-switch v-model="form.claimTimeEnabled"></el-switch>
                <template v-if="form.claimTimeEnabled">
                  <div style="display: flex;max-width: 600px;background: #f1f2f5;padding: 20px;margin-top: 10px;flex-basis: 100%;">
                    <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="width: 100%"
                    ></el-date-picker>
                    <div style="width: 50px;text-align: center;">-</div>
                    <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="width: 100%"
                    ></el-date-picker>
                  </div>
                </template>
              </el-form-item>
              <el-form-item label="领取客群限制">
                <el-switch v-model="form.claimGroupEnabled"></el-switch>
                <template v-if="form.claimGroupEnabled">
                  <div style="max-width: 600px;background: #f1f2f5;padding: 20px;margin-top: 10px;flex-basis: 100%;">
                    <el-alert
                      title="需在【发放计划】中选择权益发放，未发放的权益移动端不展示"
                      type="info"
                      :closable="false"
                      show-icon
                      style="margin-bottom: 12px;"
                    ></el-alert>
                    <div style="font-size: 14px;color: #606266;margin-bottom: 8px;font-weight: 500;">不满足提示</div>
                    <el-form-item label="提示内容" label-width="100px" style="margin-bottom: 12px;">
                      <el-input v-model="form.claimDenyMessage" maxlength="200" placeholder="请输入提示内容"></el-input>
                    </el-form-item>
                    <el-form-item label="跳转按钮文案" label-width="100px" style="margin-bottom: 12px;">
                      <el-input v-model="form.claimDenyButtonText" maxlength="10" placeholder="请输入按钮文案"></el-input>
                    </el-form-item>
                    <el-form-item label="跳转按钮链接" label-width="100px" style="margin-bottom: 0;">
                      <el-input v-model="form.claimDenyButtonLink" maxlength="200" placeholder="请输入按钮链接"></el-input>
                    </el-form-item>
                  </div>
                </template>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>

      <div v-show="activeStep === 2">
        <!-- 显示页面 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="section-title">显示页面</div>
          </template>
          <el-form :model="form" label-width="120px" label-position="left">
            <el-form-item label="权益首页">
              <el-radio-group v-model="form.showOnHome">
                <el-radio label="显示">显示</el-radio>
                <el-radio label="不显示">不显示</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="组装页">
              <el-radio-group v-model="form.showOnAssembly">
                <el-radio label="显示">显示</el-radio>
                <el-radio label="不显示">不显示</el-radio>
              </el-radio-group>
              <div
                v-if="form.showOnAssembly === '显示'"
                style="max-width: 600px;background: #f1f2f5;padding: 20px;margin-top: 10px;flex-basis: 100%;"
              >
                <el-select
                  v-model="form.assemblyPages"
                  multiple
                  filterable
                  placeholder="请选择组装页"
                  style="width: 100%"
                >
                  <el-option label="组装页A" value="组装页A"></el-option>
                  <el-option label="组装页B" value="组装页B"></el-option>
                  <el-option label="组装页C" value="组装页C"></el-option>
                  <el-option label="组装页D" value="组装页D"></el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 分享设置 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="section-title">分享设置</div>
          </template>
          <el-form :model="form" label-width="120px" label-position="left">
            <el-form-item label="是否支持分享">
              <el-switch v-model="form.shareEnabled" @change="handleShareEnabledChange"></el-switch>
              <template v-if="form.shareEnabled">
                <div style="max-width: 600px;background: #f1f2f5;padding: 20px;margin-top: 10px;flex-basis: 100%;">
                  <el-form-item label="分享名称" label-width="100px" required style="margin-bottom: 16px;">
                    <el-input
                      v-model="form.shareName"
                      maxlength="40"
                      placeholder="请输入分享名称"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="分享图片" label-width="100px" required style="margin-bottom: 0;">
                    <el-upload
                      action=""
                      :auto-upload="false"
                      :file-list="form.shareImage"
                      :on-change="file => handleUpload(file, 'shareImage')"
                      :limit="1"
                      list-type="picture-card"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                  </el-form-item>
                </div>
              </template>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 操作栏 -->
      <div class="action-bar">
        <div class="action-left">
          <el-button
            v-if="activeStep > 0"
            @click="prevStep"
          ><el-icon><ArrowLeft /></el-icon>上一步</el-button>
        </div>
        <div class="action-center">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" plain @click="handleSaveDraft">保存草稿</el-button>
          <el-button
            v-if="activeStep === 2"
            type="primary"
            @click="handleSubmitAudit"
          >提交审核</el-button>
        </div>
        <div class="action-right">
          <el-button
            v-if="activeStep < 2"
            type="primary"
            @click="nextStep"
          >下一步<el-icon class="el-icon--right"><ArrowRight /></el-icon></el-button>
        </div>
      </div>
    </el-card>

    <rongshu-product-dialog
      v-model="rongshuDialogVisible"
      @select="onRongshuSelect"
    />

    <el-dialog v-model="previewVisible" title="图片预览" width="640px" append-to-body>
      <img v-if="previewImageUrl" :src="previewImageUrl" style="display:block; max-width:100%; margin:0 auto;" />
    </el-dialog>
  </div>
</template>

<script>
import RongshuProductDialog from '@/components/RongshuProductDialog.vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AddEquityProduct',
  components: { RongshuProductDialog },
  data() {
    return {
      activeStep: 0,
      rongshuDialogVisible: false,
      previewVisible: false,
      previewImageUrl: '',
      quillOptions: {
        placeholder: '请输入内容...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ header: [1, 2, 3, false] }],
            ['link', 'image'],
            ['clean']
          ]
        }
      },
      smsTemplateOptions: [
        { id: 'SMS_TPL_001', name: '通用权益支付成功模板', content: '【银行】您购买的${productName}已支付成功，卡号：${exchangeNum}，卡密：${exchangePwd}，有效期至${expireDate}，详情：${qrCodeDownPaths}' },
        { id: 'SMS_TPL_002', name: '券码类短信模板', content: '【银行】尊敬的客户，您的${productName}购买成功，券码为${exchangeNum}，请于${expireDate}前使用。' },
        { id: 'SMS_TPL_003', name: '实物类短信模板', content: '【银行】您购买的${productName}已受理，我们将尽快安排发货，感谢您的支持。' }
      ],
      form: {
        isPlatformExchange: '是',
        source: '银行自有',
        rongshuProduct: '',
        rongshuSkuNo: '',
        productType: '券码',
        faceValueThreshold: '',
        faceValueDiscount: '',
        stockCount: null,
        shareEnabled: false,
        shareImage: [],
        shareName: '',
        externalJumpMethod: '没有',
        externalLink: '太古地产',
        customLink: '',
        miniAppId: '',
        miniAppPath: '',
        equityName: '',
        productId: '',
        merchantName: '',
        listIcon: [],
        mainImage: [],
        introduction: '',
        validityType: 'fromGrantPlan',
        validityText: '',
        overview: '',
        details: '',
        smsEnabled: false,
        smsTemplateId: '',
        smsTemplate: '',
        successButtonText: '马上去使用',
        showTimeEnabled: false,
        showStartTime: '',
        showEndTime: '',
        showGroupEnabled: false,
        showGroupTagIds: [],
        claimTimeEnabled: false,
        claimStartTime: '',
        claimEndTime: '',
        claimGroupEnabled: false,
        claimGroupIsPotential: false,
        claimGroupTagId: '',
        claimDenyMessage: '很抱歉，您暂不符合领取条件。',
        claimDenyButtonText: '返回',
        claimDenyButtonLink: '权益首页',
        showOnHome: '显示',
        showOnAssembly: '不显示',
        assemblyPages: []
      }
    }
  },
  computed: {
    mappedSource() {
      if (this.form.isPlatformExchange === '否') return '第三方'
      if (this.form.productType === '微信立减金') return '荣数商品'
      return '银行自有'
    },
    shouldShowDetailCard() {
      if (this.form.isPlatformExchange === '是') return true
      if (this.form.isPlatformExchange === '否' && this.form.externalJumpMethod === '有') return true
      return false
    }
  },
  created() {
    const copyFrom = this.$route.query.copyFrom
    if (copyFrom) {
      this.loadCopySource(copyFrom)
    }
  },
  methods: {
    handlePlatformExchangeChange(val) {
      if (val === '是') {
        this.form.productType = '券码'
        this.form.externalLink = '太古地产'
        this.form.externalJumpMethod = '没有'
        this.form.customLink = ''
        this.form.miniAppId = ''
        this.form.miniAppPath = ''
      } else {
        this.form.rongshuProduct = ''
        this.form.rongshuSkuNo = ''
        this.form.stockCount = null
        this.form.merchantName = ''
      }
    },
    handleProductTypeChange(val) {
      if (val === '券码') {
        this.form.rongshuProduct = ''
        this.form.rongshuSkuNo = ''
        this.form.stockCount = null
        this.form.merchantName = ''
      }
    },
    loadCopySource(id) {
      const mockMap = {
        'Q100001': {
          source: '银行自有',
          isPlatformExchange: '是',
          productType: '券码',
          externalJumpMethod: '',
          externalLink: '',
          customLink: '',
          miniAppId: '',
          miniAppPath: '',
          skuNo: 'SKU001',
          equityName: '权益A',
          listIcon: [],
          mainImage: [],
          overview: '<p>权益内容内容</p>',
          details: '<p>权益说明内容</p>',
          smsEnabled: true,
          smsTemplateId: 'SMS_TPL_001',
          smsTemplate: '【银行】您购买的${productName}已支付成功，卡号：${exchangeNum}，卡密：${exchangePwd}，有效期至${expireDate}，详情：${qrCodeDownPaths}',
          successButtonText: '马上去使用',
          showTimeEnabled: true,
          showStartTime: '2026-01-01 00:00:00',
          showEndTime: '2026-12-31 23:59:59',
          showGroupEnabled: false,
          showGroupTagIds: [],
          claimTimeEnabled: true,
          claimStartTime: '2026-01-01 00:00:00',
          claimEndTime: '2026-12-31 23:59:59',
          claimGroupEnabled: false,
          claimGroupTagId: '',
          claimDenyMessage: '很抱歉，您暂不符合领取条件。',
          claimDenyButtonText: '返回',
          claimDenyButtonLink: '权益首页'
        },
        'Q100002': {
          source: '第三方',
          isPlatformExchange: '否',
          productType: '',
          externalJumpMethod: '没有',
          externalLink: '太古地产',
          customLink: '',
          miniAppId: '',
          miniAppPath: '',
          skuNo: 'SKU002',
          equityName: '权益B',
          listIcon: [],
          mainImage: [],
          overview: '',
          details: '',
          smsEnabled: false,
          smsTemplateId: '',
          smsTemplate: '',
          successButtonText: '',
          showTimeEnabled: false,
          showStartTime: '',
          showEndTime: '',
          showGroupEnabled: true,
          showGroupTagIds: ['客群A'],
          claimTimeEnabled: true,
          claimStartTime: '2026-02-01 00:00:00',
          claimEndTime: '2026-11-30 23:59:59',
          claimGroupEnabled: true,
          claimGroupIsPotential: false,
          claimGroupTagId: '客群奖励活动A',
          claimDenyMessage: '很抱歉，您暂不符合领取条件。',
          claimDenyButtonText: '返回',
          claimDenyButtonLink: '权益首页'
        },
        'Q100003': {
          source: '第三方',
          isPlatformExchange: '否',
          productType: '',
          externalJumpMethod: '有',
          externalLink: '龙腾',
          customLink: '',
          miniAppId: '',
          miniAppPath: '',
          skuNo: 'SKU003',
          equityName: '权益C',
          listIcon: [],
          mainImage: [],
          overview: '<p>外部详情页权益内容</p>',
          details: '<p>外部详情页权益说明</p>',
          smsEnabled: false,
          smsTemplateId: '',
          smsTemplate: '',
          successButtonText: '',
          showTimeEnabled: false,
          showStartTime: '',
          showEndTime: '',
          showGroupEnabled: false,
          showGroupTagIds: [],
          claimTimeEnabled: false,
          claimStartTime: '',
          claimEndTime: '',
          claimGroupEnabled: false,
          claimGroupTagId: '',
          claimDenyMessage: '很抱歉，您暂不符合领取条件。',
          claimDenyButtonText: '返回',
          claimDenyButtonLink: '权益首页'
        },
        'Q100004': {
          source: '第三方',
          isPlatformExchange: '否',
          productType: '',
          externalJumpMethod: '有',
          externalLink: 'h5链接',
          customLink: 'https://example.com/custom',
          skuNo: 'SKU004',
          equityName: '权益D',
          listIcon: [],
          mainImage: [],
          overview: '<p>自定义链接权益内容</p>',
          details: '<p>自定义链接权益说明</p>',
          smsEnabled: false,
          smsTemplateId: '',
          smsTemplate: '',
          successButtonText: '',
          showTimeEnabled: false,
          showStartTime: '',
          showEndTime: '',
          showGroupEnabled: false,
          showGroupTagIds: [],
          claimTimeEnabled: false,
          claimStartTime: '',
          claimEndTime: '',
          claimGroupEnabled: false,
          claimGroupTagId: '',
          claimDenyMessage: '很抱歉，您暂不符合领取条件。',
          claimDenyButtonText: '返回',
          claimDenyButtonLink: '权益首页'
        }
      }

      request.get(`/api/equity/detail?id=${id}`).then(res => {
        const core = res.data || {}
        const rich = mockMap[id] || {}
        const merged = { ...rich }
        const coreFields = ['equityName', 'source', 'isPlatformExchange', 'productType', 'skuNo', 'merchantName']
        coreFields.forEach(k => {
          if (core[k] !== undefined && core[k] !== null && core[k] !== '') {
            merged[k] = core[k]
          }
        })
        // 根据接口返回的 source 推算 isPlatformExchange 和 productType
        if (!merged.isPlatformExchange) {
          if (core.source === '第三方') merged.isPlatformExchange = '否'
          else merged.isPlatformExchange = '是'
        }
        if (merged.isPlatformExchange === '是' && !merged.productType) {
          merged.productType = core.source === '荣数商品' ? '微信立减金' : '券码'
        }
        if (merged.isPlatformExchange === '否') {
          merged.productType = ''
        }
        if (merged.isPlatformExchange === '否') {
          if (core.jumpMethod) merged.externalJumpMethod = core.jumpMethod
          if (core.jumpLink) merged.externalLink = core.jumpLink
        }
        if (core.showOnHome) merged.showOnHome = core.showOnHome
        if (core.showOnAssembly) merged.showOnAssembly = core.showOnAssembly
        if (Array.isArray(core.assemblyPages)) merged.assemblyPages = [...core.assemblyPages]
        // 复制后清空标识字段，让用户重新命名并由后端生成新编号
        delete merged.productId
        Object.keys(merged).forEach(k => {
          this.form[k] = merged[k]
        })
        ElMessage.success(`已复制「${core.equityName || id}」的内容，请确认后保存`)
      }).catch(() => {
        ElMessage.warning('未能加载源权益信息，将以空白表单创建')
      })
    },
    nextStep() {
      if (this.activeStep < 2) {
        this.activeStep++
      }
    },
    prevStep() {
      if (this.activeStep > 0) {
        this.activeStep--
      }
    },
    buildPayload() {
      const f = this.form
      const source = this.mappedSource
      const isNotPlatform = f.isPlatformExchange === '否'
      const isCustomValidity = isNotPlatform || f.validityType === 'custom'
      return {
        equityName: f.equityName,
        source: source,
        isPlatformExchange: f.isPlatformExchange,
        productType: f.isPlatformExchange === '是' ? f.productType : '',
        skuNo: (f.isPlatformExchange === '是' && f.productType === '微信立减金') ? (f.rongshuSkuNo || f.skuNo || '') : (f.skuNo || ''),
        merchantName: f.merchantName || '',
        jumpMethod: isNotPlatform ? f.externalJumpMethod : '-',
        jumpLink: isNotPlatform ? f.externalLink : '-',
        exchangeMethod: isNotPlatform
          ? (f.externalJumpMethod === '有' ? '第三方（详情页跳转）' : '第三方（列表跳转）')
          : '权益平台',
        validityType: isCustomValidity ? 'custom' : 'fromGrantPlan',
        validityText: isCustomValidity ? (f.validityText || '') : '',
        showOnHome: f.showOnHome,
        showOnAssembly: f.showOnAssembly,
        assemblyPages: [...(f.assemblyPages || [])]
      }
    },
    handleSaveDraft() {
      if (!this.form.equityName) {
        ElMessage.warning('请填写权益名称后再保存草稿')
        return
      }
      request.post('/api/equity/save-draft', this.buildPayload()).then(() => {
        ElMessage.success('草稿已保存')
        this.$router.push('/customization/hsbc/equity-products')
      }).catch(() => {})
    },
    handleSubmitAudit() {
      if (!this.form.equityName) {
        ElMessage.warning('请填写权益名称后再提交')
        return
      }
      ElMessageBox.prompt('请填写提交说明（可选）', '提交审核', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '可填写本次提交的关键变更点',
        inputValidator: () => true
      }).then(({ value }) => {
        const payload = { ...this.buildPayload(), submitReason: value || '' }
        request.post('/api/equity/submit', payload).then(() => {
          ElMessage.success('已提交审核')
          this.$router.push('/customization/hsbc/equity-products')
        }).catch(() => {})
      }).catch(() => {})
    },
    goBack() {
      this.$router.push('/customization/hsbc/equity-products')
    },
    handleShareEnabledChange(val) {
      if (val) {
        if (!this.form.shareName) {
          this.form.shareName = this.form.equityName || ''
        }
      }
    },
    handleSmsEnabledChange(val) {
      if (!val) {
        this.form.smsTemplateId = ''
        this.form.smsTemplate = ''
      }
    },
    handleSmsTemplateChange(id) {
      const tpl = this.smsTemplateOptions.find(i => i.id === id)
      this.form.smsTemplate = tpl ? tpl.content : ''
    },
    handleUpload(file, field) {
      if (!file || !file.raw) return
      const reader = new FileReader()
      reader.onload = (e) => {
        this.form[field] = [{ name: file.name, url: e.target.result, uid: file.uid }]
      }
      reader.readAsDataURL(file.raw)
    },
    handlePreviewImage(file) {
      this.previewImageUrl = file.url || ''
      this.previewVisible = !!this.previewImageUrl
    },
    onRongshuSelect(product) {
      this.form.rongshuProduct = product.name
      this.form.rongshuSkuNo = product.skuNo
      this.form.equityName = product.name
      this.form.merchantName = product.merchant
      this.form.stockCount = product.stock
      this.form.mainImage = product.mainImage ? [...product.mainImage] : []
    }
  }
}
</script>

<style scoped>
.add-equity-product {
  padding: 20px;
}
.header-title {
  font-size: 18px;
  font-weight: 500;
}
.section-card {
  margin-bottom: 16px;
  border: none;
}
.upload-hide-trigger >>> .el-upload--picture-card { display: none; }

.section-card >>> .el-card__header {
  padding: 12px 20px;
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
}
.section-card >>> .el-form-item__content {
  display: block;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.action-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
.action-left, .action-right {
  width: 120px;
}
.action-center {
  display: flex;
  justify-content: center;
  gap: 12px;
}
.tip-icon {
  color: #909399;
  cursor: pointer;
  font-size: 14px;
}
.upload-size-tip {
  width: 100%;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
.sms-template-preview {
  margin-top: 12px;
  padding: 12px;
  background: #fff;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
