<template>
  <div class="edit-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" disabled>
                  <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" disabled>
                  <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链接'">
              <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>
                <div style="display: flex; align-items: center; gap: 12px; width: 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="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-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="使用有效期" required>
                <template v-if="form.isPlatformExchange === '是' && form.productType === '微信立减金'">
                  <el-radio-group v-model="form.validityType" style="margin-bottom: 8px;">
                    <el-radio label="fixed">固定日期</el-radio>
                    <el-radio label="relative">相对日期</el-radio>
                  </el-radio-group>
                  <div v-if="form.validityType === 'fixed'">
                    <el-date-picker
                      v-model="form.validityRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="YYYY-MM-DD"
                      style="width: 100%;"
                    />
                  </div>
                  <div v-else style="display: flex; align-items: center;">
                    <span style="margin-right: 8px;">领取后</span>
                    <el-input-number v-model="form.validityDays" :min="1" :max="3650" controls-position="right" style="width: 200px;" />
                    <span style="margin-left: 8px;">天</span>
                  </div>
                </template>
                <template v-else-if="form.isPlatformExchange === '是' && form.productType === '券码'">
                  <el-date-picker
                    v-model="form.validityRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%;"
                  />
                </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>
                          <div>
                            此模板为权益支付成功，发送给持卡人的短信模板；<br/>
                            开启后需选择短信模板，关闭则不发送短信。<br/>
                            占位符如下：<br/>
                            权益名称：${productName}<br/>
                            结束日期：${expireDate}<br/>
                            卡号：${exchangeNum}<br/>
                            卡密：${exchangePwd}<br/>
                            券码使用路径：${qrCodeDownPaths}
                          </div>
                        </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>
        <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
                    v-for="item in crowdOptions"
                    :key="item.id"
                    :label="`${item.name} (${item.id})`"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
            </template>
          </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.claimGroupEnabled" disabled></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>
      </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
                    v-for="page in assemblyPageOptions"
                    :key="page.id"
                    :label="page.name"
                    :value="page.name"
                  />
                </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
            v-if="currentAuditStatus === '草稿'"
            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 { ElMessage, ElMessageBox } from 'element-plus'
import RongshuProductDialog from '@/components/RongshuProductDialog.vue'
import request from '@/utils/request'
import crowdTaskStore from '@/store/crowdTaskStore'

export default {
  name: 'EditEquityProduct',
  components: { RongshuProductDialog },
  data() {
    return {
      activeStep: 0,
      rongshuDialogVisible: false,
      previewVisible: false,
      previewImageUrl: '',
      currentShelfStatus: '',
      currentAuditStatus: '',
      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: '',
        skuNo: '',
        equityName: '',
        productId: '',
        merchantName: '',
        listIcon: [],
        mainImage: [],
        introduction: '',
        validityType: 'fixed',
        validityText: '',
        validityRange: [],
        validityDays: 30,
        overview: '',
        details: '',
        smsEnabled: false,
        smsTemplateId: '',
        smsTemplate: '',
        successButtonText: '',
        showTimeEnabled: false,
        showStartTime: '',
        showEndTime: '',
        showGroupEnabled: false,
        showGroupTagIds: [],
        claimStartTime: '',
        claimEndTime: '',
        claimGroupEnabled: true,
        claimGroupIsPotential: false,
        claimGroupTagId: '',
        claimDenyMessage: '很抱歉，您暂不符合领取条件。',
        claimDenyButtonText: '返回',
        claimDenyButtonLink: '权益首页',
        showOnHome: '显示',
        showOnAssembly: '不显示',
        assemblyPages: []
      },
      assemblyPageOptions: []
    }
  },
  computed: {
    // 选择客群：取客群任务管理（crowdTaskStore）的数据
    crowdOptions() {
      return crowdTaskStore.list
    },
    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() {
    this.fetchAssemblyPages()
    this.loadData()
    this.loadStatus()
  },
  methods: {
    async fetchAssemblyPages() {
      try {
        const res = await request.get('/api/assembly/list')
        this.assemblyPageOptions = res.data || []
      } catch {
        this.assemblyPageOptions = []
      }
    },
    loadStatus() {
      const id = this.$route.params.id
      if (!id) return
      request.get(`/api/equity/detail?id=${id}`).then(res => {
        if (res.data) {
          this.currentShelfStatus = res.data.shelfStatus || ''
          this.currentAuditStatus = res.data.auditStatus || ''
          // 用 API 返回的核心字段覆盖（保证编辑/已上架的内容是当前线上版本）
          const fields = ['equityName', 'source', 'isPlatformExchange', 'productType', 'skuNo', 'merchantName']
          fields.forEach(k => {
            if (res.data[k] !== undefined && res.data[k] !== null && res.data[k] !== '') {
              this.form[k] = res.data[k]
            }
          })
          // 根据接口返回的 source 推算 isPlatformExchange 和 productType
          if (!this.form.isPlatformExchange) {
            if (res.data.source === '第三方') this.form.isPlatformExchange = '否'
            else this.form.isPlatformExchange = '是'
          }
          if (this.form.isPlatformExchange === '是' && !this.form.productType) {
            this.form.productType = res.data.source === '荣数商品' ? '微信立减金' : '券码'
          }
          if (this.form.isPlatformExchange === '否') {
            this.form.productType = ''
          }
          this.form.productId = id
        }
      }).catch(() => {})
    },
    buildPayload() {
      const f = this.form
      const source = this.mappedSource
      const isNotPlatform = f.isPlatformExchange === '否'
      const isCustomValidity = isNotPlatform || f.validityType === 'custom'
      return {
        productId: f.productId || this.$route.params.id,
        equityName: f.equityName,
        source: source,
        isPlatformExchange: f.isPlatformExchange,
        productType: f.isPlatformExchange === '是' ? f.productType : '',
        skuNo: (f.isPlatformExchange === '是' && f.productType === '微信立减金') ? (f.rongshuSkuNo || f.skuNo || '') : (f.skuNo || ''),
        rongshuProduct: f.rongshuProduct || '',
        stockCount: (f.isPlatformExchange === '是' && f.productType === '微信立减金') ? f.stockCount : null,
        merchantName: f.merchantName || '',
                jumpMethod: isNotPlatform ? f.externalJumpMethod : '-',
        jumpLink: isNotPlatform ? f.externalLink : '-',
        exchangeMethod: isNotPlatform
          ? (f.externalJumpMethod === '有' ? '第三方（详情页跳转）' : '第三方（列表跳转）')
          : '权益平台',
        validityType: f.validityType || 'fixed',
        validityText: f.validityText || '',
        validityRange: f.validityRange || [],
        validityDays: f.validityDays || 30,
        showOnHome: f.showOnHome,
        showOnAssembly: f.showOnAssembly,
        assemblyPages: [...(f.assemblyPages || [])]
      }
    },
    handleSaveDraft() {
      request.post('/api/equity/save-draft', this.buildPayload()).then(() => {
        ElMessage.success('草稿已保存')
        this.$router.push('/customization/hsbc/equity-products')
      }).catch(() => {})
    },
    handleSubmitAudit() {
      ElMessageBox.confirm('提交后将进入审核流程，期间不可再编辑。确定提交审核吗？', '提交审核', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const payload = { ...this.buildPayload(), submitReason: '' }
        request.post('/api/equity/submit', payload).then(() => {
          ElMessage.success('已提交审核')
          this.$router.push('/customization/hsbc/equity-products')
        }).catch(() => {})
      }).catch(() => {})
    },
    loadData() {
      const id = this.$route.params.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: ['00000120251224'],
          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: '权益首页'
        }
      }
      if (id && mockMap[id]) {
        Object.assign(this.form, mockMap[id])
        // 根据 mockMap 数据推算 isPlatformExchange 和 productType（以防 mockMap 缺少这些字段）
        if (!this.form.isPlatformExchange) {
          if (this.form.source === '第三方') this.form.isPlatformExchange = '否'
          else this.form.isPlatformExchange = '是'
        }
        if (this.form.isPlatformExchange === '是' && !this.form.productType) {
          this.form.productType = this.form.source === '荣数商品' ? '微信立减金' : '券码'
        }
        if (this.form.isPlatformExchange === '否') {
          this.form.productType = ''
        }
      }
    },
    nextStep() {
      if (this.activeStep < 2) {
        this.activeStep++
      }
    },
    prevStep() {
      if (this.activeStep > 0) {
        this.activeStep--
      }
    },
    goBack() {
      this.$router.push('/customization/hsbc/equity-products')
    },
    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 = ''
      }
    },
    handleSmsEnabledChange(val) {
      if (!val) {
        this.form.smsTemplateId = ''
        this.form.smsTemplate = ''
      }
    },
    handleShareEnabledChange(val) {
      if (val) {
        if (!this.form.shareName) {
          this.form.shareName = this.form.equityName || ''
        }
      }
    },
    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>
.edit-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>
