<template>
  <div class="app-container">
    <!-- 数据统计卡片 -->
    <!-- <el-row :gutter="20" class="mb20" v-if="statistics">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="statistics-card">
            <div class="statistics-title">总线报消息</div>
            <div class="statistics-value">{{ statistics.total || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="statistics-card">
            <div class="statistics-title">线报商品</div>
            <div class="statistics-value">{{ statistics.childrenCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>


    </el-row> -->

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="消息内容" prop="content">
        <el-input v-model="queryParams.content" placeholder="请输入消息内容" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:xbmessage:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:xbmessage:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="xbmessageList" @selection-change="handleSelectionChange" @row-click="handleRowClick" highlight-current-row>
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="首行" prop="firstLine" :show-overflow-tooltip="true" min-width="180">
        <template slot-scope="scope">
          <span>{{ decodeUnicode(scope.row.firstLine) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线报商品" prop="firstSkuName" :show-overflow-tooltip="true" min-width="480">
        <template slot-scope="scope">
          <span>{{ decodeUnicode(scope.row.firstSkuName) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线报价格" prop="firstPrice" width="100" align="center" />
      <el-table-column label="线报商品数" width="80" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.childrenCount > 0" type="success" size="mini">
            {{ scope.row.childrenCount }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺信息" width="200" align="left">
        <template slot-scope="scope">
          <div v-if="scope.row.children && scope.row.children.length > 0">
            <span v-html="parseOwner(scope.row.children[0].owner)"></span>-
            <span v-if="scope.row.children[0].jsonShopInfo">{{ decodeUnicode(getJsonValue(scope.row.children[0].jsonShopInfo, 'shopName')) || '-' }}</span>
            <span v-else>-</span>
          
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="线报群" prop="fromWxid" width="240" align="center">
        <template slot-scope="scope">
          <span>{{ getGroupName(scope.row.fromWxid) || scope.row.fromWxid || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线报时间" prop="createDate" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createDate ? parseTime(scope.row.createDate) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-info" @click="showMessageDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:xbmessage:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />





    <!-- 子消息详情对话框 -->
    <el-dialog title="商品详情" :visible.sync="childDetailVisible" width="1200px" append-to-body>
      <div v-if="currentChild">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="店铺名称">{{ decodeUnicode(getJsonValue(currentChild.jsonQueryResult, 'shopInfo.shopName')) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ decodeUnicode(currentChild.skuName) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="价格">{{ currentChild.firstPrice ? `¥${currentChild.firstPrice}` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="所有者"></el-descriptions-item>
        </el-descriptions>
                <!-- 佣金信息 -->
                <div v-if="currentChild.jsonQueryResult" style="margin-top: 20px;">
          <h4>佣金信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="佣金">{{ getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.commission') ? `¥${getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.commission')}` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="佣金比例">{{ getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.commissionShare') ? `${getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.commissionShare')}%` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="券佣金">{{ getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.couponCommission') ? `¥${getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.couponCommission')}` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="PLUS佣金比例">{{ getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.plusCommissionShare') ? `${getJsonValue(currentChild.jsonQueryResult, 'commissionInfo.plusCommissionShare')}%` : '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <!-- 商品查询结果 -->
        <!-- <div v-if="currentChild.jsonQueryResult" style="margin-top: 20px;">
          <h4>商品查询结果</h4>
                      <el-descriptions :column="1" border>
              <el-descriptions-item label="品牌">{{ decodeUnicode(getJsonValue(currentChild.jsonQueryResult, 'brandName')) || '-' }}</el-descriptions-item>
               <el-descriptions-item label="分类">{{ decodeUnicode(getCategoryPath(currentChild.jsonQueryResult)) || '-' }}</el-descriptions-item>
              <el-descriptions-item label="评论数">{{ getJsonValue(currentChild.jsonQueryResult, 'comments') || '-' }}</el-descriptions-item>
              <el-descriptions-item label="好评率">{{ getJsonValue(currentChild.jsonQueryResult, 'goodCommentsShare') ? `${getJsonValue(currentChild.jsonQueryResult, 'goodCommentsShare')}%` : '-' }}</el-descriptions-item>
              <el-descriptions-item label="30天订单数">{{ getJsonValue(currentChild.jsonQueryResult, 'inOrderCount30Days') || '-' }}</el-descriptions-item>
              <el-descriptions-item label="是否热门">{{ getJsonValue(currentChild.jsonQueryResult, 'isHot') ? '是' : '否' }}</el-descriptions-item> 
              <el-descriptions-item label="是否京东自营">{{ getJsonValue(currentChild.jsonQueryResult, 'isJdSale') ? '是' : '否' }}</el-descriptions-item>
            </el-descriptions>
        </div> -->

        <!-- 价格信息 -->
        <div v-if="currentChild.jsonQueryResult" style="margin-top: 20px;">
          <h4>价格信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="原价">{{ getJsonValue(currentChild.jsonQueryResult, 'priceInfo.price') ? `¥${getJsonValue(currentChild.jsonQueryResult, 'priceInfo.price')}` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="最低券后价">{{ getJsonValue(currentChild.jsonQueryResult, 'priceInfo.lowestCouponPrice') ? `¥${getJsonValue(currentChild.jsonQueryResult, 'priceInfo.lowestCouponPrice')}` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="最低价">{{ getJsonValue(currentChild.jsonQueryResult, 'priceInfo.lowestPrice') ? `¥${getJsonValue(currentChild.jsonQueryResult, 'priceInfo.lowestPrice')}` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="购买价">{{ getJsonValue(currentChild.jsonQueryResult, 'purchasePriceInfo.purchasePrice') ? `¥${getJsonValue(currentChild.jsonQueryResult, 'purchasePriceInfo.purchasePrice')}` : '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>



        <!-- 店铺信息 -->
        <!-- <div v-if="currentChild.jsonQueryResult" style="margin-top: 20px;">
          <h4>店铺信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="店铺ID">{{ getJsonValue(currentChild.jsonQueryResult, 'shopInfo.shopId') || '-' }}</el-descriptions-item>
            <el-descriptions-item label="店铺等级">{{ getJsonValue(currentChild.jsonQueryResult, 'shopInfo.shopLevel') || '-' }}</el-descriptions-item>
            <el-descriptions-item label="店铺标签">{{ decodeUnicode(getJsonValue(currentChild.jsonQueryResult, 'shopInfo.shopLabel')) || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div> -->

        <!-- 优惠券信息 -->
        <div v-if="currentChild.jsonCouponList && currentChild.jsonCouponList !== '[]'" style="margin-top: 20px;">
          <h4>优惠券信息</h4>
          <el-table :data="parseCouponList(currentChild.jsonCouponList)" border style="width: 100%">
            <el-table-column label="优惠券类型" align="center" prop="couponStyle" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.couponStyle === 0 ? '满减券' : '其他' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="满减门槛" align="center" prop="quota" width="120">
              <template slot-scope="scope">
                <span>满{{ scope.row.quota }}减{{ scope.row.discount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="获取时间" align="center" width="200">
              <template slot-scope="scope">
                <div>开始：{{ formatTimestamp(scope.row.getStartTime) }}</div>
                <div>结束：{{ formatTimestamp(scope.row.getEndTime) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="使用时间" align="center" width="200">
              <template slot-scope="scope">
                <div>开始：{{ formatTimestamp(scope.row.useStartTime) }}</div>
                <div>结束：{{ formatTimestamp(scope.row.useEndTime) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="链接" align="center" min-width="200">
              <template slot-scope="scope">
                <el-link :href="scope.row.link" target="_blank" type="primary">查看优惠券</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="childDetailVisible = false">关 闭</el-button>
        <el-button type="primary" @click="openQuickLink(currentChild)" v-if="currentChild.jsonQueryResult">一键转链</el-button>
        <el-button type="warning" @click="openGiftDialog(currentChild)" v-if="currentChild.jsonQueryResult">开礼金</el-button>
        <el-button type="success" @click="addToFavorites(currentChild)" v-if="currentChild.jsonQueryResult">添加到常用</el-button>
      </div>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog title="消息详情" :visible.sync="messageDetailVisible" width="1600px" append-to-body>
      <div v-if="currentMessageDetail">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="创建时间">{{ currentMessageDetail.createDate ? parseTime(currentMessageDetail.createDate) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="线报群名称">{{ getGroupName(currentMessageDetail.fromWxid) || '-' }}</el-descriptions-item>
          <!-- <el-descriptions-item label="SKUID">{{ currentMessageDetail.skuid || '-' }}</el-descriptions-item> -->
        </el-descriptions>

        <!-- 原始消息内容 -->
        <div style="margin-top: 20px;">
          <h4 style="font-size: 18px; font-weight: bold; color: #303133;">原始消息内容</h4>
          <el-input
            type="textarea"
            :rows="8"
            :value="decodeUnicode(currentMessageDetail.tipOriginalMessage)"
            readonly
            placeholder="暂无消息内容"
            style="font-size: 18px; font-weight: bold;"
            class="original-message-content"
          />
        </div>

        <!-- 子消息列表 -->
        <div v-if="currentMessageDetail.children && currentMessageDetail.children.length > 0" style="margin-top: 20px;">
          <h4>子消息列表 (共{{ currentMessageDetail.children.length }}条)</h4>
          <el-table :data="currentMessageDetail.children" border style="width: 100%" max-height="400" @row-click="handleChildRowClick" highlight-current-row>
            <el-table-column label="商品名称" align="left" prop="skuName" :show-overflow-tooltip="true" min-width="250">
              <template slot-scope="scope">
                <span>{{ decodeUnicode(scope.row.skuName) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="价格" align="center" prop="firstPrice" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.firstPrice">¥{{ scope.row.firstPrice }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="店铺名称" align="center" width="150">
              <template slot-scope="scope">
                <span v-html="parseOwner(scope.row.owner)"></span>-
                <span v-if="scope.row.jsonQueryResult">{{ decodeUnicode(getJsonValue(scope.row.jsonQueryResult, 'shopInfo.shopName')) || '-' }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="佣金比例" align="center" width="80">
              <template slot-scope="scope">
                <span v-if="scope.row.jsonQueryResult && getJsonValue(scope.row.jsonQueryResult, 'commissionInfo.commissionShare')">{{ getJsonValue(scope.row.jsonQueryResult, 'commissionInfo.commissionShare') }}%</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="佣金" align="center" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.jsonQueryResult && getJsonValue(scope.row.jsonQueryResult, 'commissionInfo.commission')">¥{{ getJsonValue(scope.row.jsonQueryResult, 'commissionInfo.commission') }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="160">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-info" @click.stop="showChildDetail(scope.row)">详情</el-button>
                <el-button size="mini" type="text" icon="el-icon-s-promotion" @click.stop="openPublishFromXb(scope.row)">发品</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="messageDetailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 一键转链对话框 -->
    <el-dialog class="quick-link-dialog" title="一键转链" :visible.sync="quickLinkVisible" width="1000px" append-to-body>
      <div v-if="quickLinkProduct">
        <el-alert type="info" :closable="false" title="当前商品">
          <template slot="description">
            <div>
              <div><strong>名称：</strong>{{ decodeUnicode(quickLinkProduct.skuName) || '-' }}</div>
              <div><strong>店铺：</strong>{{ getJsonValue(quickLinkProduct.jsonQueryResult, 'shopInfo.shopName') || '-' }}</div>
              <div><strong>线报价：</strong>{{ quickLinkProduct.firstPrice ? `¥${quickLinkProduct.firstPrice}` : '-' }}</div>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 顶部左右布局：左输入，右通用文案（可多输入框） -->
      <div class="quick-link-top-row">
        <div class="quick-link-col">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
            <span style="font-weight:600;">输入内容</span>
            <div>
              <el-button type="primary" size="mini" :loading="quickLinkLoading" @click="generateQuickLink">生成转链内容</el-button>
            </div>
          </div>
          <el-input type="textarea" :rows="6" v-model="quickLinkInput" placeholder="示例 https://u.jd.com/... 或商品关键词" />
        </div>

        <div class="quick-link-col">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
            <span style="font-weight:600;">通用文案</span>
            <div style="display:flex; gap:6px; align-items:center;">
              <el-button size="mini" type="primary" @click="generateWenanFromQuickLink">生成文案</el-button>
              <span>礼金</span>
              <el-input v-model.number="quickLinkGift.amount" size="mini" style="width:80px" type="number" min="1" max="50" step="0.01" />
              <el-input v-model.number="quickLinkGift.quantity" size="mini" style="width:70px" type="number" min="1" max="100" />
              <el-button size="mini" type="warning" :loading="quickLinkGift.loading" @click="generateWenanWithGift">开礼金并生成</el-button>
              <el-button size="mini" @click="handleCopyText(quickLinkWenanText)" :disabled="!quickLinkWenanText">复制</el-button>
              <el-button size="mini" icon="el-icon-plus" @click="addExtraWenanBox">添加输入框</el-button>
            </div>
          </div>
          <el-input type="textarea" :rows="6" v-model="quickLinkWenanText" placeholder="点击上方按钮生成文案" />
          <div v-for="(val, i) in quickLinkExtraTexts" :key="'extra-'+i" style="margin-top:8px;">
            <div style="display:flex; justify-content:flex-end; gap:6px; margin-bottom:4px;">
              <el-button size="mini" @click="handleCopyText(quickLinkExtraTexts[i])" :disabled="!quickLinkExtraTexts[i]">复制</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeExtraWenanBox(i)"></el-button>
            </div>
            <el-input type="textarea" :rows="4" v-model="quickLinkExtraTexts[i]" placeholder="自定义文案输入" />
          </div>
        </div>
      </div>

      <div style="margin: 10px 0; display:flex; gap:10px; flex-wrap:wrap;">
        <el-button type="primary" :loading="quickLinkLoading" @click="generateQuickLink">生成转链内容</el-button>
        <el-button type="success" :disabled="!Array.isArray(parsedQuickLinkResult) || !parsedQuickLinkResult.length" @click="addQuickLinkResultsToFavorites">全部加入常用</el-button>
        <el-button @click="quickLinkVisible = false">关闭</el-button>
      </div>
      <div v-if="Array.isArray(parsedQuickLinkResult) && parsedQuickLinkResult.length">
        <el-alert title="转链结果" type="success" :closable="false" show-icon />
        <el-card v-for="(it, idx) in parsedQuickLinkResult" :key="idx" shadow="never" style="margin-top: 10px;">
          <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap;">
            <div style="flex:1 1 auto; min-width: 300px;">
              <div><strong>SPUID：</strong>{{ it.spuid || '-' }}</div>
              <div style="margin-top:4px;"><strong>名称：</strong>{{ decodeUnicode(it.skuName || it.title) || '-' }}</div>
              <div style="margin-top:4px;"><strong>店铺：</strong>{{ it.shopName || '-' }}<span v-if="it.shopId"> (ID: {{ it.shopId }})</span></div>
              <div style="margin-top:4px;"><strong>价格：</strong>{{ it.price ? `¥${it.price}` : '-' }} <span v-if="it.commissionShare" style="color:#67c23a;">/ 佣金比 {{ it.commissionShare }}%</span></div>
              <div style="margin-top:4px;"><strong>链接：</strong><el-link v-if="it.materialUrl || it.url" :href="it.materialUrl || it.url" target="_blank">查看</el-link><span v-else>-</span></div>
            </div>
            <div style="flex:0 0 auto; display:flex; gap:8px;">
              <el-button type="success" size="mini" @click="addQuickLinkItemToFavorites(it)">加入常用</el-button>
              <el-button type="primary" size="mini" @click="openPublishFromQuickLink(it)">发品</el-button>
            </div>
          </div>
        </el-card>

        <!-- 文案输出区 -->
        <el-divider>文案输出</el-divider>
        <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-bottom:8px;">
          <el-button size="mini" type="primary" @click="generateWenanFromQuickLink">生成文案</el-button>
          <div style="display:flex; gap:6px; align-items:center;">
            <span>礼金金额(元)</span>
            <el-input v-model.number="quickLinkGift.amount" size="mini" style="width:90px" type="number" min="1" max="50" step="0.01" />
            <span>数量</span>
            <el-input v-model.number="quickLinkGift.quantity" size="mini" style="width:80px" type="number" min="1" max="100" />
            <el-button size="mini" type="warning" :loading="quickLinkGift.loading" @click="generateWenanWithGift">开礼金并生成文案</el-button>
          </div>
          <el-button size="mini" @click="handleCopyText(quickLinkWenanText)" :disabled="!quickLinkWenanText">复制文案</el-button>
        </div>
        <el-input type="textarea" :rows="6" v-model="quickLinkWenanText" placeholder="点击上方按钮生成文案" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="quickLinkVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 公共发品对话框组件复用 -->
    <PublishDialog :visible.sync="publishDialogVisible" :initial-data="publishInitialData" @success="onPublishDialogSuccess" />
    <!-- 礼金设置弹窗 -->
    <el-dialog title="开礼金" :visible.sync="giftDialogVisible" width="420px" append-to-body>
      <el-form :model="giftForm" label-width="100px" ref="giftForm">
        <el-form-item label="金额(元)">
          <el-input v-model.number="giftForm.amount" type="number" min="1" max="50" step="0.01" placeholder="1-50" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model.number="giftForm.quantity" type="number" min="1" max="100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="giftDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="giftLoading" @click="submitGift">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listXbmessage, delXbmessage, getGroupNameOptions } from "@/api/system/xbmessage";
import { parseTime } from "@/utils/ruoyi";
import PublishDialog from '@/components/PublishDialog.vue'
import { generatePromotionContent, createGiftCoupon, transferWithGift } from "@/api/system/jdorder";
import { addToFavoritesAfterPublishFromXb } from "@/utils/publishHelper";
import { addToFavorites, getBySkuid } from "@/api/system/favoriteProduct";

export default {
  name: "Xbmessage",
  components: { PublishDialog },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息表格数据
      xbmessageList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null
      },
      // 子消息详情对话框
      childDetailVisible: false,
      // 当前查看的子消息
      currentChild: {},
      // 消息详情对话框
      messageDetailVisible: false,
      // 当前查看的消息详情
      currentMessageDetail: {},
      // 统计数据
      statistics: null,
      // 群名称选项
      groupNameOptions: [],
      publishDialogVisible: false,
      publishInitialData: {},
      // 一键转链相关
      quickLinkVisible: false,
      quickLinkProduct: null,
      quickLinkResult: null,
      parsedQuickLinkResult: null,
      activeQuickLinkTab: 0,
      activeQuickLinkWenanTab: {},
      quickLinkLoading: false,
      quickLinkInput: '',
      quickLinkWenanText: '',
      quickLinkGift: { amount: null, quantity: 10, loading: false },
      quickLinkExtraTexts: [],
      giftDialogVisible: false,
      giftForm: { amount: null, quantity: 10 },
      giftLoading: false,
      giftContext: { materialUrl: '', owner: 'g', skuName: '' },
      
      // 地区选项
      regionOptions: {
        provinces: [],
        cities: [],
        areas: []
      },
      // 类目选项
      categoryOptions: [],
      categoryLoading: false,
      // 会员名选项
      userNameOptions: [],
      userNameLoading: false,
      // ERP账号选项
      erpAccountsOptions: [],
      erpAccountLoading: false,
      // 属性选项
      pvOptions: [],
      selectedPv: {},
      // 商品类型选项
      itemBizTypeOptions: [
        { label: '普通商品', value: 2 },
        { label: '已验货', value: 0 },
        { label: '验货宝', value: 10 },
        { label: '闲鱼优品', value: 19 },
        { label: '闲鱼特卖', value: 24 },
        { label: '品牌捡漏', value: 26 }
      ],
      // 行业类型选项
      spBizTypeOptions: [
        { label: '手机', value: 1 },
        { label: '时尚', value: 2 },
        { label: '家电', value: 3 },
        { label: '乐器', value: 8 },
        { label: '数码3C', value: 9 },
        { label: '奢品', value: 16 },
        { label: '母婴', value: 17 },
        { label: '美妆', value: 18 },
        { label: '珠宝', value: 19 },
        { label: '游戏', value: 20 },
        { label: '家居', value: 21 },
        { label: '虚拟', value: 22 },
        { label: '图书', value: 24 },
        { label: '食品', value: 27 },
        { label: '玩具', value: 28 },
        { label: '其他', value: 99 }
      ],
      // 成色选项
      stuffStatusOptions: [
        { label: '不传', value: null },
        { label: '全新', value: 100 },
        { label: '99新', value: 99 },
        { label: '95新', value: 95 },
        { label: '9成新', value: 90 },
        { label: '8成新', value: 80 },
        { label: '7成新', value: 70 },
        { label: '6成新', value: 60 },
        { label: '5成新', value: 50 }
      ],
      // 服务支持选项
      serviceSupportOptions: [
        { label: '七天无理由退货', value: 'SDR' },
        { label: '描述不符包邮退', value: 'NFR' },
        { label: '描述不符全额退(虚拟)', value: 'VNR' },
        { label: '10分钟极速发货(虚拟)', value: 'FD_10MS' },
        { label: '24小时极速发货', value: 'FD_24HS' },
        { label: '48小时极速发货', value: 'FD_48HS' },
        { label: '正品保障', value: 'FD_GPA' }
      ]
    };
  },
  created() {
    this.getList();
    this.getGroupNameOptions();
  },
  methods: {
    openPublishFromXb(child) {
      const parsedQuery = this.safeJsonParse(child.jsonQueryResult);
      const images = this.extractImageUrlsFromQuery(parsedQuery, child);
      // 记录当前线报项，便于发品成功后加入常用
      this.currentXbMessageItem = child;

      // 与转链一致：统一先调用转链接口补全字段
      const materialUrl = this.getJsonValue(child.jsonQueryResult, 'materialUrl');
      const skuName = child.skuName;
      const inputContent = materialUrl || skuName || '';

      const baseInitialData = {
        title: this.decodeUnicode(child.skuName) || '',
        content: '',
        images: images,
        originalPrice: parsedQuery && parsedQuery.priceInfo ? Number(parsedQuery.priceInfo.price || parsedQuery.priceInfo.lowestCouponPrice || 0) : null,
        wenanOptions: []
      };

      if (!inputContent) {
        this.publishInitialData = baseInitialData;
        this.publishDialogVisible = true;
        return;
      }

      try { this.$modal && this.$modal.loading('正在生成转链文案，请稍候…'); } catch(e) {}

      generatePromotionContent({ promotionContent: inputContent }).then(res => {
        const result = res && (res.msg || res.data);
        let arr = [];
        try {
          if (typeof result === 'string') arr = JSON.parse(result); else if (Array.isArray(result)) arr = result;
        } catch (e) { arr = []; }

        let wenanOptions = [];
        let detailImages = [];
        if (Array.isArray(arr) && arr.length > 0) {
          const first = arr[0] || {};
          const wenanArr = Array.isArray(first.wenan) ? first.wenan : [];
          wenanOptions = wenanArr.map((w, i) => ({ label: w.type || `版本${i+1}` , content: w.content || '' }));
          detailImages = this.extractImageUrlsFromGenerateResult(first);
        }

        this.publishInitialData = Object.assign({}, baseInitialData, {
          content: (wenanOptions[0] && wenanOptions[0].content) || '',
          images: (detailImages && detailImages.length) ? detailImages : baseInitialData.images,
          wenanOptions
        });
      }).catch(() => {
        this.publishInitialData = baseInitialData;
      }).finally(() => {
        try { this.$modal && this.$modal.closeLoading(); } catch(e) {}
        this.publishDialogVisible = true;
      });
    },
    addExtraWenanBox() { this.quickLinkExtraTexts.push(''); },
    removeExtraWenanBox(i) { this.quickLinkExtraTexts.splice(i, 1); },
    // 兼容多种结构提取图片URL（线报查询结果/行数据）
    extractImageUrlsFromQuery(queryObj, rowFallback) {
      try {
        const urls = [];
        const pushIfUrl = (v) => {
          if (!v) return;
          const s = String(v).trim();
          if (/^https?:\/\//.test(s)) urls.push(s);
        };

        if (queryObj && Array.isArray(queryObj.images)) {
          queryObj.images.forEach(it => {
            if (typeof it === 'string') pushIfUrl(it);
            else if (it && (it.url || it.imageUrl || it.imgUrl)) pushIfUrl(it.url || it.imageUrl || it.imgUrl);
          });
        }
        if (queryObj && queryObj.imageInfo) {
          const ii = queryObj.imageInfo;
          pushIfUrl(ii.mainImage);
          if (Array.isArray(ii.imageList)) {
            ii.imageList.forEach(it => {
              if (typeof it === 'string') pushIfUrl(it);
              else if (it && (it.url || it.imageUrl || it.imgUrl)) pushIfUrl(it.url || it.imageUrl || it.imgUrl);
            });
          } else if (typeof ii.imageList === 'string') {
            ii.imageList.split(/[\s,]+/).forEach(pushIfUrl);
          }
        }
        // 兜底：从行数据尝试
        if (urls.length === 0 && rowFallback) {
          if (Array.isArray(rowFallback.images)) {
            rowFallback.images.forEach(it => { if (typeof it === 'string') pushIfUrl(it); else if (it && it.url) pushIfUrl(it.url); });
          }
          pushIfUrl(rowFallback.productImage);
          pushIfUrl(rowFallback.imageUrl);
          pushIfUrl(rowFallback.image);
        }
        return Array.from(new Set(urls));
      } catch (e) { return []; }
    },
    // 兼容 generatePromotionContent 返回结构提取图片
    extractImageUrlsFromGenerateResult(obj) {
      try {
        const urls = [];
        const pushIfUrl = (v) => {
          if (!v) return;
          const s = String(v).trim();
          if (/^https?:\/\//.test(s)) urls.push(s);
        };
        if (Array.isArray(obj.images)) {
          obj.images.forEach(it => {
            if (typeof it === 'string') pushIfUrl(it);
            else if (it && (it.url || it.imageUrl || it.imgUrl)) pushIfUrl(it.url || it.imageUrl || it.imgUrl);
          });
        }
        if (obj.mainImage) pushIfUrl(obj.mainImage);
        if (Array.isArray(obj.imageList)) obj.imageList.forEach(pushIfUrl);
        if (Array.isArray(obj.pics)) obj.pics.forEach(pushIfUrl);
        if (Array.isArray(obj.imgUrls)) obj.imgUrls.forEach(pushIfUrl);
        return Array.from(new Set(urls));
      } catch (e) { return []; }
    },
    /** 查询消息列表 */
    getList() {
      this.loading = true;
      listXbmessage(this.queryParams).then(response => {
        this.xbmessageList = this.normalizeList(response.rows || []);
        this.total = response.total;
        this.loading = false;
        console.log("接口返回数据:", response);
        
        // 处理统计数据
        this.processStatistics(response);
      });
    },
    /** 获取群名称选项 */
    getGroupNameOptions() {
      getGroupNameOptions().then(response => {
        this.groupNameOptions = response.data || [];
        console.log('群名称选项加载完成:', this.groupNameOptions);
      }).catch(error => {
        console.error('获取群名称选项失败:', error);
        this.groupNameOptions = [];
      });
    },
    /** 根据微信ID获取群名称 */
    getGroupName(wxid) {
      if (!wxid || !this.groupNameOptions || this.groupNameOptions.length === 0) return null;
      const group = this.groupNameOptions.find(item => item.value === wxid);
      return group ? group.label : null;
    },
    /** 归一化列表数据（解决 children 字段结构不同） */
    normalizeList(rows) {
      if (!Array.isArray(rows)) return [];
      return rows.map(parent => {
        const normalized = { ...parent };
        // 添加childrenCount字段
        normalized.childrenCount = Array.isArray(parent.children) ? parent.children.length : 0;
        
        if (Array.isArray(parent.children) && parent.children.length > 0) {
          normalized.children = parent.children.map(child => {
            // 如果接口已经提供了这些字段，直接使用；否则从jsonQueryResult中解析
            const parsedQuery = this.safeJsonParse(child.jsonQueryResult);
            const firstPrice = child.firstPrice || 
              parsedQuery?.priceInfo?.lowestCouponPrice ||
              parsedQuery?.priceInfo?.price ||
              parsedQuery?.purchasePriceInfo?.purchasePrice ||
              null;

            return {
              ...child,
              firstSkuName: child.firstSkuName || child.skuName || parsedQuery?.skuName || null,
              firstPrice: firstPrice,
              firstLine: child.firstLine || child.skuName || parsedQuery?.skuName || null
            }
          });
          
          // 父级信息：优先使用接口提供的字段，否则从子项中获取
          const firstChild = normalized.children[0];
          normalized.firstSkuName = normalized.firstSkuName || firstChild?.firstSkuName || null;
          normalized.firstPrice = normalized.firstPrice || firstChild?.firstPrice || null;
          normalized.firstLine = normalized.firstLine || firstChild?.firstLine || null;
        }
        return normalized;
      });
    },
    /** 安全 JSON 解析 */
    safeJsonParse(str) {
      if (!str || typeof str !== 'string') return null;
      try {
        return JSON.parse(str);
      } catch (e) {
        return null;
      }
    },
    /** 显示消息详情 */
    showMessageDetail(message) {
      this.currentMessageDetail = message;
      this.messageDetailVisible = true;
    },
    /** 显示子消息详情 */
    showChildDetail(child) {
      this.currentChild = child;
      this.childDetailVisible = true;
    },
    /** 从JSON字符串中安全获取嵌套值 */
    getJsonValue(jsonStr, path) {
      try {
        const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr;
        if (!obj) return null;
        
        const keys = path.split('.');
        let value = obj;
        for (const key of keys) {
          if (value && typeof value === 'object' && key in value) {
            value = value[key];
          } else {
            return null;
          }
        }
        return value;
      } catch (e) {
        return null;
      }
    },
    /** 获取分类路径 */
    getCategoryPath(jsonStr) {
      try {
        const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr;
        if (!obj?.categoryInfo) return null;
        
        const { cid1Name, cid2Name, cid3Name } = obj.categoryInfo;
        return [cid1Name, cid2Name, cid3Name].filter(Boolean).join(' > ');
      } catch (e) {
        return null;
      }
    },
    /** 解析所有者字段 */
    parseOwner(owner) {
      if (!owner) return '-';
      if (owner === 'g') return '<span style="color: #67C23A; font-weight: bold;">自营</span>';
      if (owner === 'p') return '<span style="color: #409EFF; font-weight: bold;">POP</span>';
      return owner;
    },
    /** 解码Unicode字符 */
    decodeUnicode(str) {
      if (!str || typeof str !== 'string') return str;
      try {
        // 处理 \u 开头的Unicode转义序列
        return str.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => {
          return String.fromCharCode(parseInt(hex, 16));
        });
      } catch (e) {
        return str;
      }
    },
    /** 行点击事件 */
    handleRowClick(row, column, event) {
      // 如果点击的是操作列，不触发详情
      if (column.label === '操作') {
        return;
      }
      this.showMessageDetail(row);
    },
    /** 子消息行点击事件 */
    handleChildRowClick(row, column, event) {
      // 如果点击的是操作列，不触发详情
      if (column.label === '操作') {
        return;
      }
      this.showChildDetail(row);
    },
    /** 解析优惠券列表 */
    parseCouponList(couponListStr) {
      try {
        if (!couponListStr || couponListStr === '[]') return [];
        const coupons = typeof couponListStr === 'string' ? JSON.parse(couponListStr) : couponListStr;
        return Array.isArray(coupons) ? coupons : [];
      } catch (e) {
        return [];
      }
    },
    /** 转换时间戳为可读时间 */
    formatTimestamp(timestamp) {
      if (!timestamp) return '-';
      try {
        // 如果是时间戳（数字），转换为日期
        if (typeof timestamp === 'number') {
          return this.parseTime(timestamp);
        }
        // 如果是字符串，尝试解析
        if (typeof timestamp === 'string') {
          const num = parseInt(timestamp);
          if (!isNaN(num)) {
            return this.parseTime(num);
          }
          // 如果不是数字字符串，直接返回
          return timestamp;
        }
        return '-';
      } catch (e) {
        return '-';
      }
    },
    /** 处理统计数据 */
    processStatistics(response) {
      if (response.rows && response.rows.length > 0) {
        const data = response.rows;
        const typeSet = new Set(data.map(item => item.type).filter(Boolean));
        
        // 计算子消息总数
        let childrenCount = 0;
        data.forEach(item => {
          if (item.children && Array.isArray(item.children)) {
            childrenCount += item.children.length;
          }
        });
        
        // 计算有效消息数（有内容的消息）
        const validCount = data.filter(item => item.content && item.content.trim()).length;
        
        this.statistics = {
          total: response.total || data.length,
          childrenCount: childrenCount,
          typeCount: typeSet.size,
          validCount: validCount
        };
      } else {
        this.statistics = {
          total: 0,
          childrenCount: 0,
          typeCount: 0,
          validCount: 0
        };
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
              this.$modal.confirm('是否确认删除选中的消息数据？').then(function() {
        return delXbmessage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/xbmessage/export', {
        ...this.queryParams
      }, `xbmessage_${new Date().getTime()}.xlsx`)
    },
    /** 一键转链 */
    openQuickLink(message) {
      this.quickLinkProduct = message;
      this.quickLinkResult = null;
      this.parsedQuickLinkResult = null;
      this.activeQuickLinkTab = 0;
      this.activeQuickLinkWenanTab = {};
      this.quickLinkVisible = true;
    },
    /** 生成转链内容 */
    generateQuickLink() {
      this.quickLinkLoading = true;
      this.$axios.post('/api/quickLink/generate', {
        skuName: this.quickLinkProduct.skuName,
        shopName: this.getJsonValue(this.quickLinkProduct.jsonQueryResult, 'shopInfo.shopName'),
        firstPrice: this.quickLinkProduct.firstPrice,
        commission: this.getJsonValue(this.quickLinkProduct.jsonQueryResult, 'commissionInfo.commission'),
        commissionShare: this.getJsonValue(this.quickLinkProduct.jsonQueryResult, 'commissionInfo.commissionShare'),
        spuid: this.getJsonValue(this.quickLinkProduct.jsonQueryResult, 'spuid'),
        url: this.getJsonValue(this.quickLinkProduct.jsonQueryResult, 'url'),
        wenan: this.quickLinkProduct.wenan, // 假设wenan是父消息的wenan
        images: this.quickLinkProduct.images, // 假设images是父消息的images
      }).then(response => {
        this.quickLinkResult = response.data.result;
        this.parsedQuickLinkResult = this.parseQuickLinkResult(this.quickLinkResult);
        this.activeQuickLinkWenanTab = {}; // 重置文案版本tab
        this.quickLinkLoading = false;
      }).catch(error => {
        this.quickLinkLoading = false;
        this.$modal.msgError('生成转链内容失败: ' + error.message);
      });
    },

    /** 一键转链并自动加入常用（使用返回结构） */
    async quickLinkAndAddToFavorites(message) {
      try {
        this.quickLinkProduct = message;
        this.quickLinkLoading = true;
        const payload = {
          skuName: message.skuName,
          shopName: this.getJsonValue(message.jsonQueryResult, 'shopInfo.shopName'),
          firstPrice: message.firstPrice,
          commission: this.getJsonValue(message.jsonQueryResult, 'commissionInfo.commission'),
          commissionShare: this.getJsonValue(message.jsonQueryResult, 'commissionInfo.commissionShare'),
          spuid: this.getJsonValue(message.jsonQueryResult, 'spuid'),
          url: this.getJsonValue(message.jsonQueryResult, 'url'),
          wenan: message.wenan,
          images: message.images
        };
        const resp = await this.$axios.post('/api/quickLink/generate', payload);
        this.quickLinkLoading = false;
        const resultStr = resp && resp.data && (resp.data.result || resp.data.msg);
        if (!resultStr) { this.$modal.msgError('生成转链失败'); return; }
        let arr = [];
        try { arr = JSON.parse(resultStr); } catch(e) { this.$modal.msgError('返回数据格式错误'); return; }
        if (!Array.isArray(arr) || arr.length === 0) { this.$modal.msgWarning('无可用转链结果'); return; }
        const r0 = arr[0];
        // 直接用返回的结构添加到常用（使用spuid）
        const spuid = r0.spuid || this.getJsonValue(message.jsonQueryResult, 'spuid') || '';
        const favoriteData = {
          skuid: spuid,
          productName: r0.skuName || r0.title || message.skuName || '',
          shopName: r0.shopName || '',
          shopId: r0.shopId || '',
          productUrl: r0.materialUrl || r0.url || '',
          productImage: Array.isArray(r0.images) && r0.images.length ? r0.images[0] : '',
          price: r0.price || message.firstPrice || '',
          commissionInfo: r0.commissionShare ? `${r0.commissionShare}%` : (r0.commission || ''),
          category: '',
          brand: '',
          remark: '来自一键转链',
          isTop: 0,
          sortWeight: 0
        };
        // 查重
        const exist = await getBySkuid(spuid);
        if (exist && exist.data) { this.$modal.msgWarning('该商品已在常用列表中'); return; }
        const addRes = await addToFavorites(favoriteData);
        if (addRes && addRes.code === 200) {
          this.$modal.msgSuccess('转链成功并已加入常用');
          this.$store.dispatch('app/triggerFavoriteProductRefresh');
        } else {
          this.$modal.msgError((addRes && addRes.msg) || '加入常用失败');
        }
      } catch(e) {
        this.quickLinkLoading = false;
        this.$modal.msgError('转链或加入常用失败');
      }
    },
    /** 解析转链结果 */
    parseQuickLinkResult(result) {
      try {
        const parsed = JSON.parse(result);
        if (Array.isArray(parsed)) {
          return parsed.map(item => ({
            ...item,
            wenan: item.wenan || [] // 确保wenan存在
          }));
        }
        return [];
      } catch (e) {
        return [];
      }
    },
    /** 由转链结果生成文案（不带礼金替换） */
    generateWenanFromQuickLink() {
      if (!Array.isArray(this.parsedQuickLinkResult) || !this.parsedQuickLinkResult.length) {
        this.$modal.msgWarning('请先生成转链内容');
        return;
      }
      // 拼接首条或全部的文案
      const parts = [];
      this.parsedQuickLinkResult.forEach((it) => {
        const title = this.decodeUnicode(it.skuName || it.title || '');
        const firstWenan = Array.isArray(it.wenan) && it.wenan.length ? it.wenan[0].content : '';
        const link = it.materialUrl || it.url || '';
        parts.push([title, firstWenan, link].filter(Boolean).join('\n'));
      });
      this.quickLinkWenanText = parts.join('\n\n');
      this.$modal.msgSuccess('文案已生成');
    },
    /** 开礼金并生成替换后的文案（逐条创建礼金，替换每条链接） */
    async generateWenanWithGift() {
      if (!Array.isArray(this.parsedQuickLinkResult) || !this.parsedQuickLinkResult.length) {
        this.$modal.msgWarning('请先生成转链内容');
        return;
      }
      if (!this.quickLinkGift.amount || !this.quickLinkGift.quantity) {
        this.$modal.msgWarning('请输入礼金金额与数量');
        return;
      }
      this.quickLinkGift.loading = true;
      const parts = [];
      for (const it of this.parsedQuickLinkResult) {
        try {
          const materialUrl = it.materialUrl || it.url;
          const owner = it.owner || 'g';
          const skuName = it.skuName || it.title || '';
          if (!materialUrl) continue;
          // 1) 开礼金
          const cg = await createGiftCoupon({ amount: this.quickLinkGift.amount, quantity: this.quickLinkGift.quantity, materialUrl, owner, skuName });
          const giftKey = cg && cg.data && (cg.data.giftCouponKey || cg.data.giftKey);
          // 2) 转链（带礼金）
          let shortUrl = materialUrl;
          if (giftKey) {
            const tf = await transferWithGift({ materialUrl, giftCouponKey: giftKey });
            if (tf && tf.data) {
              if (typeof tf.data === 'string') shortUrl = tf.data; else if (tf.data.shortURL) shortUrl = tf.data.shortURL;
            }
          }
          const title = this.decodeUnicode(it.skuName || it.title || '');
          const firstWenan = Array.isArray(it.wenan) && it.wenan.length ? it.wenan[0].content : '';
          parts.push([title, firstWenan, shortUrl].filter(Boolean).join('\n'));
        } catch (e) {
          // 单条失败不中断
        }
      }
      this.quickLinkWenanText = parts.join('\n\n');
      this.quickLinkGift.loading = false;
      this.$modal.msgSuccess('礼金已开通并生成文案');
    },
    /** 将一键转链结果全部加入常用 */
    async addQuickLinkResultsToFavorites() {
      if (!Array.isArray(this.parsedQuickLinkResult) || !this.parsedQuickLinkResult.length) return;
      let success = 0, skipped = 0, failed = 0;
      for (const it of this.parsedQuickLinkResult) {
        try {
          const spuid = it.spuid || '';
          if (!spuid) { skipped++; continue; }
          const exist = await getBySkuid(spuid);
          if (exist && exist.data) { skipped++; continue; }
          const favoriteData = {
            skuid: spuid,
            productName: it.skuName || it.title || '',
            shopName: it.shopName || '',
            shopId: it.shopId || '',
            productUrl: it.materialUrl || it.url || '',
            productImage: Array.isArray(it.images) && it.images.length ? it.images[0] : '',
            price: it.price || '',
            commissionInfo: it.commissionShare ? `${it.commissionShare}%` : (it.commission || ''),
            remark: '来自一键转链',
            isTop: 0,
            sortWeight: 0
          };
          const addRes = await addToFavorites(favoriteData);
          if (addRes && addRes.code === 200) success++; else failed++;
        } catch (e) { failed++; }
      }
      this.$modal.msgSuccess(`加入常用完成：成功${success}，跳过${skipped}，失败${failed}`);
      if (success > 0) this.$store.dispatch('app/triggerFavoriteProductRefresh');
    },
    /** 从转链结果直接打开发品弹窗 */
    openPublishFromQuickLink(it) {
      const images = Array.isArray(it.images) ? it.images : [];
      const wenanOptions = Array.isArray(it.wenan) ? it.wenan.map((w, i) => ({ label: w.type || `版本${i+1}`, content: w.content || '' })) : [];
      this.publishInitialData = {
        title: it.skuName || it.title || '',
        content: (wenanOptions[0] && wenanOptions[0].content) || '',
        images: images,
        originalPrice: it.price ? Number(it.price) : undefined,
        wenanOptions
      };
      this.publishDialogVisible = true;
    },
    /** 复制文本 */
    handleCopyText(text) {
      this.$copyText(text).then(() => {
        this.$modal.msgSuccess('复制成功');
      }).catch(() => {
        this.$modal.msgError('复制失败');
      });
    },
    /** 复制图片URL */
    handleCopyImageUrl(url) {
      this.$copyText(url).then(() => {
        this.$modal.msgSuccess('复制成功');
      }).catch(() => {
        this.$modal.msgError('复制失败');
      });
    },
    /** 预览图片 */
    handlePreviewImage(url) {
      this.$previewImage({
        images: [url],
        initialIndex: 0,
        onClose: () => {
          console.log('图片预览关闭');
        }
      });
    },
    /** 打开发品对话框 */
    openQuickLinkPublish(product, productIndex) {
      // 保存当前商品信息，用于发品成功后添加到常用商品
      this.currentXbMessageItem = product;
      
      this.quickLinkPublishDialog.form.title = product.skuName || '新品';
      this.quickLinkPublishDialog.form.content = product.wenan && product.wenan.length > 0 ? product.wenan[0].content : '';
      this.quickLinkPublishDialog.form.productImages = product.images || [];
      this.quickLinkPublishDialog.form.extraImagesText = '';
      this.quickLinkPublishDialog.form.whiteImages = '';
      this.quickLinkPublishDialog.form.serviceSupport = [];
      this.quickLinkPublishDialog.form.userName = '';
      this.quickLinkPublishDialog.form.province = null;
      this.quickLinkPublishDialog.form.city = null;
      this.quickLinkPublishDialog.form.district = null;
      this.quickLinkPublishDialog.form.price = null;
      this.quickLinkPublishDialog.form.originalPrice = null;
      this.quickLinkPublishDialog.form.expressFee = null;
      this.quickLinkPublishDialog.form.stock = null;
      this.quickLinkPublishDialog.form.outerId = '';
      this.quickLinkPublishDialog.form.itemBizType = null;
      this.quickLinkPublishDialog.form.spBizType = null;
      this.quickLinkPublishDialog.form.channelCatId = null;
      this.quickLinkPublishDialog.form.channelPvJson = '';
      this.quickLinkPublishDialog.form.stuffStatus = null;
      this.quickLinkPublishDialog.wenanOptions = product.wenan || [];
      this.quickLinkPublishDialog.productImages = product.images || [];
      this.quickLinkPublishDialog.visible = true;
      this.quickLinkPublishDialog.form.wenanIndex = 0; // 默认选中第一个文案版本
      this.quickLinkPublishDialog.form.appid = ''; // 清空账号
      this.quickLinkPublishDialog.form.userName = ''; // 清空会员名
      this.quickLinkPublishDialog.form.province = null; // 清空省市区
      this.quickLinkPublishDialog.form.city = null;
      this.quickLinkPublishDialog.form.district = null;
      this.quickLinkPublishDialog.form.price = null;
      this.quickLinkPublishDialog.form.originalPrice = null;
      this.quickLinkPublishDialog.form.expressFee = null;
      this.quickLinkPublishDialog.form.stock = null;
      this.quickLinkPublishDialog.form.outerId = '';
      this.quickLinkPublishDialog.form.itemBizType = null;
      this.quickLinkPublishDialog.form.spBizType = null;
      this.quickLinkPublishDialog.form.channelCatId = null;
      this.quickLinkPublishDialog.form.channelPvJson = '';
      this.quickLinkPublishDialog.form.stuffStatus = null;
      this.selectedPv = {};
    },
    /** 发品 */
    submitQuickLinkPublish() {
      this.$refs.quickLinkPublishForm.validate(valid => {
        if (valid) {
          this.quickLinkPublishDialog.loading = true;
                  const payload = {
          appid: this.quickLinkPublishDialog.form.appid || undefined,
          title: this.quickLinkPublishDialog.form.title || undefined,
          content: this.quickLinkPublishDialog.form.content || undefined,
          images: this.quickLinkPublishDialog.form.productImages.filter(img => img.selected).map(img => img.url) || [],
          extraImages: this.quickLinkPublishDialog.form.extraImagesText.split('\n').filter(url => url.trim() && url.trim().startsWith('http')) || [],
          whiteImages: this.quickLinkPublishDialog.form.whiteImages ? [this.quickLinkPublishDialog.form.whiteImages] : [],
          serviceSupport: (this.quickLinkPublishDialog.form.serviceSupport && this.quickLinkPublishDialog.form.serviceSupport.length) ? this.quickLinkPublishDialog.form.serviceSupport.join(',') : undefined,
          userName: this.quickLinkPublishDialog.form.userName || undefined,
          province: this.quickLinkPublishDialog.form.province || undefined,
          city: this.quickLinkPublishDialog.form.city || undefined,
          district: this.quickLinkPublishDialog.form.district || undefined,
          price: this.cents(this.quickLinkPublishDialog.form.price) || undefined,
          originalPrice: this.quickLinkPublishDialog.form.originalPrice != null ? this.cents(this.quickLinkPublishDialog.form.originalPrice) : undefined,
          expressFee: this.cents(this.quickLinkPublishDialog.form.expressFee) || undefined,
          stock: this.quickLinkPublishDialog.form.stock || undefined,
          outerId: this.quickLinkPublishDialog.form.outerId || undefined, // 如果为空，后端自动生成
          skuid: this.getJsonValue(this.currentXbMessageItem?.jsonQueryResult, 'spuid') || this.currentXbMessageItem?.spuid || this.currentXbMessageItem?.skuid || undefined, // 优先使用spuid
          itemBizType: this.quickLinkPublishDialog.form.itemBizType || undefined,
          spBizType: this.quickLinkPublishDialog.form.spBizType || undefined,
          channelCatId: this.quickLinkPublishDialog.form.channelCatId || undefined,
          channelPvJson: this.quickLinkPublishDialog.form.channelPvJson || undefined,
          stuffStatus: this.quickLinkPublishDialog.form.stuffStatus || undefined,
        };
        
                        createProductByPromotion(payload).then(response => {
          this.quickLinkPublishDialog.loading = false;
          if (response.code === 200) {
            // 发品成功，弹窗显示商品ID、状态和商家编码
            const productId = response.data.product_id;
            const productStatus = response.data.product_status;
            const outerId = response.data.outer_id || response.data.outerId || '';
            
            let successMsg = `发品提交成功！商品ID: ${productId}, 状态: ${productStatus}`;
            if (outerId) {
              successMsg += `, 商家编码: ${outerId}`;
            }
            
            this.$modal.msgSuccess(successMsg);
            
            // 自动添加到常用商品
            this.addToFavoritesAfterPublish(productId, productStatus, outerId);
            
            this.quickLinkPublishDialog.visible = false;
          } else {
            this.$modal.msgError(response.msg || '发品失败');
          }
        }).catch(error => {
          this.quickLinkPublishDialog.loading = false;
          console.error('发品失败', error);
          this.$modal.msgError('发品失败，请稍后重试');
        });
        }
      });
    },
    /** 复制原始转链数据 */
    handleCopyQuickLinkResult() {
      this.$copyText(this.quickLinkResult).then(() => {
        this.$modal.msgSuccess('复制成功');
      }).catch(() => {
        this.$modal.msgError('复制失败');
      });
    },
    /** 选择所有图片 */
    selectAllQuickLinkImages(selected) {
      this.quickLinkPublishDialog.productImages.forEach(img => {
        img.selected = selected;
      });
    },
    /** 反选图片 */
    invertQuickLinkSelection() {
      this.quickLinkPublishDialog.productImages.forEach(img => {
        img.selected = !img.selected;
      });
    },
    /** 切换文案版本 */
    onQuickLinkWenanChange(index) {
      this.quickLinkPublishDialog.form.wenanIndex = index;
    },
    /** 切换闲管家账号 */
    onQuickLinkAppidChange(appid) {
      this.quickLinkPublishDialog.form.appid = appid;
      this.loadUserNameOptions(appid);
      // 应用切换时，重置类目与属性
      this.quickLinkPublishDialog.form.channelCatId = null;
      this.quickLinkPublishDialog.form.channelPvJson = '';
      this.categoryOptions = [];
      this.selectedPv = {};
      // 有必要时重新拉取类目
      this.loadCategoryOptions(this.quickLinkPublishDialog.form.itemBizType);
    },
    /** 加载会员名选项 */
    loadUserNameOptions(appid) {
      this.userNameLoading = true;
      getUsernames({ pageNum: 1, pageSize: 200, appid }).then(response => {
        if (response.code === 200) this.userNameOptions = response.data || [];
        else this.$modal.msgError(response.msg || '加载会员名失败');
        this.userNameLoading = false;
      }).catch(error => {
        this.$modal.msgError('加载会员名失败');
        this.userNameLoading = false;
      });
    },
    /** 类目选择变化时，清空属性 JSON 并拉取属性 */
    onQuickLinkCategoryChange() {
      this.quickLinkPublishDialog.form.channelPvJson = '';
      this.selectedPv = {};
      this.loadQuickLinkProperties();
    },
    /** 切换省 */
    async onQuickLinkProvinceChange(province) {
      this.quickLinkPublishDialog.form.city = null;
      this.quickLinkPublishDialog.form.district = null;
      this.regionOptions.areas = [];
      await this.loadCityOptions(province);
    },
    /** 加载市选项 */
    async loadCityOptions(province) {
      this.regionOptions.cities = [];
      if (province) {
        try {
          const response = await getCities(province);
          if (response.code === 200) {
            this.regionOptions.cities = response.data || [];
            // 如果当前选中的城市不在新加载的城市列表中，清空城市和区县选择
            if (this.quickLinkPublishDialog.form.city && 
                !this.regionOptions.cities.find(city => city.value === this.quickLinkPublishDialog.form.city)) {
              this.quickLinkPublishDialog.form.city = null;
              this.quickLinkPublishDialog.form.district = null;
              this.regionOptions.areas = [];
            }
          } else {
            this.$modal.msgError(response.msg || '加载市失败');
          }
        } catch (error) {
          this.$modal.msgError('加载市失败');
        }
      }
    },
    /** 切换市 */
    async onQuickLinkCityChange(city) {
      this.quickLinkPublishDialog.form.district = null;
      await this.loadDistrictOptions(this.quickLinkPublishDialog.form.province, city);
    },
    /** 加载区选项 */
    async loadDistrictOptions(province, city) {
      this.regionOptions.areas = [];
      if (province && city) {
        try {
          const response = await getAreas(province, city);
          if (response.code === 200) {
            this.regionOptions.areas = response.data || [];
            // 如果当前选中的区县不在新加载的区县列表中，清空区县选择
            if (this.quickLinkPublishDialog.form.district && 
                !this.regionOptions.areas.find(area => area.value === this.quickLinkPublishDialog.form.district)) {
              this.quickLinkPublishDialog.form.district = null;
            }
          } else {
            this.$modal.msgError(response.msg || '加载区失败');
          }
        } catch (error) {
          this.$modal.msgError('加载区失败');
        }
      }
    },
    /** 切换区 */
    onQuickLinkDistrictChange(district) {
      this.quickLinkPublishDialog.form.district = district;
    },
    /** 切换商品类型 */
    onQuickLinkItemBizTypeChange(itemBizType) {
      this.quickLinkPublishDialog.form.channelPvJson = ''; // 清空属性
      this.selectedPv = {};
      this.loadCategoryOptions(itemBizType);
    },
    /** 切换行业类型 */
    onQuickLinkSpBizTypeChange(spBizType) {
      this.quickLinkPublishDialog.form.channelPvJson = ''; // 清空属性
      this.selectedPv = {};
      // 行业类型变化后，若已选商品类型且已选应用，则拉取类目
      this.loadCategoryOptions(this.quickLinkPublishDialog.form.itemBizType);
    },
        /** 加载类目选项 */
    loadCategoryOptions(itemBizType) {
      this.categoryOptions = [];
      // 需要具备 itemBizType、spBizType、appid
      const spBizType = this.quickLinkPublishDialog.form.spBizType;
      const appid = this.quickLinkPublishDialog.form.appid;
      if (!itemBizType || !spBizType || !appid) {
        this.categoryLoading = false;
        return;
      }
      this.categoryLoading = true;
      const params = { itemBizType, spBizType, appid };
      getCategories(params).then(response => {
        if (response.code === 200) this.categoryOptions = response.data || [];
        else this.$modal.msgError(response.msg || '加载类目失败');
        this.categoryLoading = false;
      }).catch(error => {
        this.$modal.msgError('加载类目失败');
        this.categoryLoading = false;
      });
    },
    /** 加载属性选项 */
    loadQuickLinkProperties() {
      this.quickLinkPublishDialog.pvOptions = [];
      this.selectedPv = {};
      const channelCatId = this.quickLinkPublishDialog.form.channelCatId;
      if (!channelCatId) return;
      // 保护：若类目ID非数字或空，直接返回
      if (channelCatId === '' || channelCatId == null) return;
      this.$axios.get('/api/property/options', { params: { channelCatId } }).then(response => {
        this.quickLinkPublishDialog.pvOptions = response.data || [];
      }).catch(error => {
        this.$modal.msgError('加载属性失败: ' + (error && error.message ? error.message : ''));
      });
    },
    /** 切换属性 */
    onQuickLinkPvChange(value) {
      this.selectedPv[this.quickLinkPublishDialog.form.channelCatId] = value;
    },
    /** 切换成色 */
    onQuickLinkStuffStatusChange(stuffStatus) {
      this.quickLinkPublishDialog.form.stuffStatus = stuffStatus;
    },
    /** 切换服务项 */
    onQuickLinkServiceSupportChange(serviceSupport) {
      this.quickLinkPublishDialog.form.serviceSupport = serviceSupport;
    },
    /** 切换会员名 */
    onQuickLinkUserNameChange(userName) {
      this.quickLinkPublishDialog.form.userName = userName;
    },
    
    /** 打开一键转链弹窗 */
    openQuickLink(child) {
      this.quickLinkProduct = child;
      this.quickLinkResult = null;
      this.parsedQuickLinkResult = null;
      this.activeQuickLinkTab = 0;
      this.activeQuickLinkWenanTab = {};
      this.quickLinkVisible = true;
    },
    openGiftDialog(child) {
      const materialUrl = this.getJsonValue(child.jsonQueryResult, 'materialUrl') || this.getJsonValue(child.jsonQueryResult, 'url');
      const owner = this.getJsonValue(child.jsonQueryResult, 'owner') || 'g';
      const skuName = child.skuName || '';
      if (!materialUrl) { this.$modal.msgError('无法获取商品链接'); return; }
      this.giftContext = { materialUrl, owner, skuName };
      this.giftForm = { amount: null, quantity: 10 };
      this.giftDialogVisible = true;
    },
    async submitGift() {
      if (!this.giftContext.materialUrl || !this.giftForm.amount || !this.giftForm.quantity) {
        this.$modal.msgError('请完善礼金金额与数量'); return;
      }
      this.giftLoading = true;
      try {
        const cg = await createGiftCoupon({ materialUrl: this.giftContext.materialUrl, amount: this.giftForm.amount, quantity: this.giftForm.quantity, owner: this.giftContext.owner, skuName: this.giftContext.skuName });
        if (!cg || cg.code !== 200) { this.$modal.msgError((cg && cg.msg) || '开礼金失败'); this.giftLoading = false; return; }
        const giftKey = (cg.data && (cg.data.giftCouponKey || cg.data.giftKey)) || (typeof cg.data === 'string' ? cg.data : null);
        const tf = await transferWithGift({ materialUrl: this.giftContext.materialUrl, giftCouponKey: giftKey });
        let shortUrl = '';
        if (tf && tf.code === 200) {
          const d = tf.data; if (typeof d === 'string') shortUrl = d; else if (d && d.shortURL) shortUrl = d.shortURL;
        }
        if (shortUrl) {
          if (this.publishInitialData && this.publishDialogVisible) {
            this.publishInitialData = Object.assign({}, this.publishInitialData, { content: (this.publishInitialData.content ? (this.publishInitialData.content + '\n' + shortUrl) : shortUrl) });
          }
          this.$modal.msgSuccess('礼金短链已生成');
        } else {
          this.$modal.msgSuccess('礼金创建成功');
        }
        this.giftDialogVisible = false;
      } catch (e) {
        this.$modal.msgError('礼金处理失败');
      }
      this.giftLoading = false;
    },
    
    /** 生成转链内容 */
    generateQuickLink() {
      if (!this.quickLinkProduct && !this.quickLinkInput) return;
      
      this.quickLinkLoading = true;
      // 从线报消息中提取商品链接或信息
      const materialUrl = this.quickLinkInput || this.getJsonValue(this.quickLinkProduct.jsonQueryResult, 'materialUrl');
      const skuName = this.quickLinkProduct ? this.quickLinkProduct.skuName : '';
      
      let inputContent = '';
      if (materialUrl) {
        inputContent = materialUrl;
      } else if (skuName) {
        inputContent = skuName;
      } else {
        this.$modal.msgError('无法获取商品信息');
        this.quickLinkLoading = false;
        return;
      }
      
      generatePromotionContent({
        promotionContent: inputContent
      }).then(response => {
        this.quickLinkLoading = false;
        if (response.code === 200) {
          this.quickLinkResult = response.msg || response.data || "转链成功";
          try {
            if (typeof this.quickLinkResult === 'string') {
              this.parsedQuickLinkResult = JSON.parse(this.quickLinkResult);
            } else {
              this.parsedQuickLinkResult = this.quickLinkResult;
            }
            // 初始化每个商品的文案标签页状态
            if (Array.isArray(this.parsedQuickLinkResult)) {
              this.parsedQuickLinkResult.forEach((_, index) => {
                this.$set(this.activeQuickLinkWenanTab, index, 0);
              });
            }
          } catch (e) {
            console.log('数据解析失败，使用原始数据');
            this.parsedQuickLinkResult = {};
          }
          this.$modal.msgSuccess("转链内容生成成功");
        } else {
          this.$modal.msgError(response.msg || "转链失败");
        }
      }).catch(error => {
        this.quickLinkLoading = false;
        console.error('转链失败:', error);
        this.$modal.msgError("转链失败，请稍后重试");
      });
    },
    
    /** 复制转链结果 */
    handleCopyQuickLinkResult() {
      if (this.quickLinkResult) {
        if (navigator.clipboard) {
          navigator.clipboard.writeText(this.quickLinkResult).then(() => {
            this.$modal.msgSuccess("复制成功");
          }).catch(() => {
            this.fallbackCopyText(this.quickLinkResult);
          });
        } else {
          this.fallbackCopyText(this.quickLinkResult);
        }
      }
    },
    
    /** 复制文案内容 */
    handleCopyText(text) {
      if (text) {
        if (navigator.clipboard) {
          navigator.clipboard.writeText(text).then(() => {
            this.$modal.msgSuccess("复制成功");
          }).catch(() => {
            this.fallbackCopyText(text);
          });
        } else {
          this.fallbackCopyText(text);
        }
      }
    },
    
    /** 复制图片链接 */
    handleCopyImageUrl(imageUrl) {
      if (imageUrl) {
        if (navigator.clipboard) {
          navigator.clipboard.writeText(imageUrl).then(() => {
            this.$modal.msgSuccess("图片链接复制成功");
          }).catch(() => {
            this.fallbackCopyText(imageUrl);
          });
        } else {
          this.fallbackCopyText(imageUrl);
        }
      }
    },
    /** 从转链结果加入常用 */
    async addQuickLinkItemToFavorites(it) {
      try {
        const spuid = it.spuid || '';
        if (!spuid) { this.$modal.msgError('缺少SPUID'); return; }
        const exist = await getBySkuid(spuid);
        if (exist && exist.data) { this.$modal.msgWarning('该商品已在常用列表中'); return; }
        const favoriteData = {
          skuid: spuid,
          productName: it.skuName || it.title || '',
          shopName: it.shopName || '',
          shopId: it.shopId || '',
          productUrl: it.materialUrl || it.url || '',
          productImage: Array.isArray(it.images) && it.images.length ? it.images[0] : '',
          price: it.price || '',
          commissionInfo: it.commissionShare ? `${it.commissionShare}%` : (it.commission || ''),
          remark: '来自一键转链',
          isTop: 0,
          sortWeight: 0
        };
        const addRes = await addToFavorites(favoriteData);
        if (addRes && addRes.code === 200) {
          this.$modal.msgSuccess('已加入常用');
          this.$store.dispatch('app/triggerFavoriteProductRefresh');
        } else {
          this.$modal.msgError((addRes && addRes.msg) || '加入常用失败');
        }
      } catch(e) {
        this.$modal.msgError('加入常用失败');
      }
    },
    
    /** 预览图片 */
    handlePreviewImage(imageUrl) {
      window.open(imageUrl, '_blank');
    },
    
    /** 备用复制方法 */
    fallbackCopyText(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand('copy');
        this.$modal.msgSuccess("复制成功");
      } catch (err) {
        this.$modal.msgError("复制失败");
      }
      document.body.removeChild(textArea);
    },
    
    /** 打开发品弹窗 */
    openQuickLinkPublish(product, productIndex) {
      const wenanIndex = this.activeQuickLinkWenanTab[productIndex] || 0;
      const wenanContent = product && product.wenan && product.wenan[wenanIndex] ? (product.wenan[wenanIndex].content || '') : '';
      const images = Array.isArray(product.images) ? product.images : [];
      const wenanOptions = Array.isArray(product.wenan) ? product.wenan.map((w, i) => ({ label: w.type || `版本${i+1}`, content: w.content || '' })) : [];
      
      this.quickLinkPublishDialog.wenanOptions = wenanOptions;
      this.quickLinkPublishDialog.form = Object.assign({}, this.quickLinkPublishDialog.form, {
        title: product.skuName || '',
        content: wenanContent,
        wenanIndex: wenanIndex,
        extraImagesText: '',
        whiteImages: '',
        serviceSupport: this.quickLinkPublishDialog.form.serviceSupport,
        userName: '',
        province: this.quickLinkPublishDialog.form.province,
        city: this.quickLinkPublishDialog.form.city,
        district: this.quickLinkPublishDialog.form.district,
        price: null,
        originalPrice: null,
        expressFee: 0,
        stock: this.quickLinkPublishDialog.form.stock,
        outerId: '',
        itemBizType: this.quickLinkPublishDialog.form.itemBizType,
        spBizType: this.quickLinkPublishDialog.form.spBizType,
        channelCatId: '',
        stuffStatus: this.quickLinkPublishDialog.form.stuffStatus,
        channelPvJson: ''
      });
      
      // 预填原价
      const guessed = this.guessYuanPrice(product);
      if (guessed != null) {
        this.quickLinkPublishDialog.form.originalPrice = Number(Number(guessed).toFixed(2));
      }
      
      this.quickLinkPublishDialog.productImages = images.map(u => ({ url: u, selected: true }));
      this.quickLinkPublishDialog.visible = true;
      this.$nextTick(() => {
        if (this.$refs.quickLinkPublishForm) {
          this.$refs.quickLinkPublishForm.clearValidate();
        }
        // 确保地区数据被加载
        this.ensureRegionDataLoaded();
      });
    },
    
    /** 从商品信息中推测原价 */
    guessYuanPrice(product) {
      const candidates = [
        product && product.price,
        product && product.oriPrice,
        product && product.originPrice,
        product && product.jdPrice,
        product && product.marketPrice,
        product && product.opPrice,
      ].filter(v => v != null);
      
      for (const v of candidates) {
        const n = Number(v);
        if (!Number.isNaN(n) && n > 0) {
          return n;
        }
      }
      return null;
    },
    
    /** 文案版本切换 */
    onQuickLinkWenanChange(val) {
      if (this.quickLinkPublishDialog.wenanOptions && this.quickLinkPublishDialog.wenanOptions[val]) {
        this.quickLinkPublishDialog.form.content = this.quickLinkPublishDialog.wenanOptions[val].content || '';
      }
    },
    
    /** 图片选择相关方法 */
    selectAllQuickLinkImages(flag) {
      (this.quickLinkPublishDialog.productImages || []).forEach(it => { it.selected = !!flag; });
    },
    
    invertQuickLinkSelection() {
      (this.quickLinkPublishDialog.productImages || []).forEach(it => { it.selected = !it.selected; });
    },
    
    /** 加载省份 */
    async loadProvinces() {
      try {
        const res = await getProvinces();
        if (res.code === 200) {
          this.regionOptions.provinces = res.data || [];
          // 如果有默认省份，自动加载对应的城市和区县
          if (this.quickLinkPublishDialog.form.province) {
            await this.loadCityOptions(this.quickLinkPublishDialog.form.province);
            if (this.quickLinkPublishDialog.form.city) {
              await this.loadDistrictOptions(this.quickLinkPublishDialog.form.province, this.quickLinkPublishDialog.form.city);
            }
          }
        } else {
          this.$modal.msgError(res.msg || '加载省份失败');
        }
      } catch (e) { this.$modal.msgError('加载省份失败'); }
    },
    
    /** 加载ERP账号 */
    async loadERPAccounts() {
      this.erpAccountLoading = true;
      try {
        const res = await getERPAccounts();
        if (res.code === 200) this.erpAccountsOptions = res.data || []; 
        else this.$modal.msgError(res.msg || '加载应用失败');
      } catch (e) { this.$modal.msgError('加载应用失败'); }
      this.erpAccountLoading = false;
    },
    
    /** 加载类目 */
    async loadCategories() {
      const itemBizType = this.quickLinkPublishDialog.form.itemBizType;
      const spBizType = this.quickLinkPublishDialog.form.spBizType;
      const appid = this.quickLinkPublishDialog.form.appid;
      if (!itemBizType) return;
      
      this.categoryLoading = true;
      try {
        const res = await getCategories({ itemBizType, spBizType, appid });
        if (res.code === 200) this.categoryOptions = res.data || []; 
        else this.$modal.msgError(res.msg || '加载类目失败');
      } catch (e) { this.$modal.msgError('加载类目失败'); }
      this.categoryLoading = false;
    },
    
    /** 加载会员名 */
    async loadUsernames() {
      this.userNameLoading = true;
      try {
        const res = await getUsernames({ pageNum: 1, pageSize: 200, appid: this.quickLinkPublishDialog.form.appid });
        if (res.code === 200) this.userNameOptions = res.data || []; 
        else this.$modal.msgError(res.msg || '加载会员名失败');
      } catch (e) { this.$modal.msgError('加载会员名失败'); }
      this.userNameLoading = false;
    },
    
    /** 加载属性 */
    async loadQuickLinkProperties() {
      const f = this.quickLinkPublishDialog.form;
      if (!f.itemBizType || !f.spBizType || !f.channelCatId) {
        this.pvOptions = []; this.selectedPv = {}; return;
      }
      try {
        const res = await getProperties({ itemBizType: f.itemBizType, spBizType: f.spBizType, channelCatId: f.channelCatId, appid: f.appid });
        if (res.code === 200) {
          this.pvOptions = res.data || [];
          const keep = { ...this.selectedPv };
          this.selectedPv = {};
          (this.pvOptions || []).forEach(p => { if (keep[p.propertyId]) this.selectedPv[p.propertyId] = keep[p.propertyId]; });
        } else {
          this.$modal.msgError(res.msg || '加载属性失败');
        }
      } catch (e) {
        this.$modal.msgError('加载属性失败');
      }
    },
    
    /** 提交发品 */
    submitQuickLinkPublish() {
      this.$refs.quickLinkPublishForm.validate(valid => {
        if (!valid) return;
        
        const f = this.quickLinkPublishDialog.form;
        const selectedImages = (this.quickLinkPublishDialog.productImages || [])
          .filter(it => it.selected)
          .map(it => it.url)
          .filter(Boolean);
        const extraImages = String(f.extraImagesText || '')
          .split(/\n+/)
          .map(s => s.trim())
          .filter(Boolean);
        const images = [...selectedImages, ...extraImages];
        
        if (!images.length) {
          this.$modal.msgError('请至少选择或填写一张图片');
          return;
        }
        
        let channelPv = undefined;
        if (f.channelPvJson && f.channelPvJson.trim()) {
          try { channelPv = JSON.parse(f.channelPvJson); } 
          catch (e) { this.$modal.msgError('属性JSON格式不正确'); return; }
        }
        
        const payload = {
          appid: f.appid || undefined,
          title: f.title,
          content: f.content,
          images: images,
          whiteImages: f.whiteImages || undefined,
          userName: f.userName,
          province: f.province,
          city: f.city,
          district: f.district,
          serviceSupport: (f.serviceSupport && f.serviceSupport.length) ? f.serviceSupport.join(',') : undefined,
          price: this.cents(f.price),
          originalPrice: f.originalPrice != null ? this.cents(f.originalPrice) : undefined,
          expressFee: this.cents(f.expressFee),
          stock: f.stock,
          outerId: f.outerId || undefined,
          itemBizType: f.itemBizType,
          spBizType: f.spBizType,
          channelCatId: f.channelCatId,
          stuffStatus: f.stuffStatus || undefined,
          channelPv: channelPv
        };
        
        this.quickLinkPublishDialog.loading = true;
        createProductByPromotion(payload).then(res => {
          this.quickLinkPublishDialog.loading = false;
          if (res.code === 200) {
            // 发品成功，弹窗显示商品ID、状态和商家编码
            const productId = res.data.product_id;
            const productStatus = res.data.product_status;
            const outerId = res.data.outer_id || res.data.outerId || '';
            
            let successMsg = `发品提交成功！商品ID: ${productId}, 状态: ${productStatus}`;
            if (outerId) {
              successMsg += `, 商家编码: ${outerId}`;
            }
            
            this.$modal.msgSuccess(successMsg);
            
            // 自动添加到常用商品
            this.addToFavoritesAfterPublish(productId, productStatus, outerId);
            
            this.quickLinkPublishDialog.visible = false;
          } else {
            this.$modal.msgError(res.msg || '发品失败');
          }
        }).catch(err => {
          this.quickLinkPublishDialog.loading = false;
          console.error('发品失败', err);
          this.$modal.msgError('发品失败，请稍后重试');
        });
      });
    },
    
    /** 确保地区数据被加载 */
    async ensureRegionDataLoaded() {
      // 如果省份数据未加载，先加载省份
      if (this.regionOptions.provinces.length === 0) {
        await this.loadProvinces();
      }
      
      // 如果有省份但城市数据未加载，加载城市
      if (this.quickLinkPublishDialog.form.province && this.regionOptions.cities.length === 0) {
        await this.loadCityOptions(this.quickLinkPublishDialog.form.province);
      }
      
      // 如果有省份和城市但区县数据未加载，加载区县
      if (this.quickLinkPublishDialog.form.province && 
          this.quickLinkPublishDialog.form.city && 
          this.regionOptions.areas.length === 0) {
        await this.loadDistrictOptions(this.quickLinkPublishDialog.form.province, this.quickLinkPublishDialog.form.city);
      }
    },
    
    /** 价格转换（元转分） */
    cents(yuan) {
      const n = Number(yuan);
      if (Number.isNaN(n)) return undefined;
      return Math.round(n * 100);
    },

    /** 发品成功后自动添加到常用商品 */
    async addToFavoritesAfterPublish(productId, productStatus, outerId) {
      try {
        // 获取当前线报消息项信息
        const currentItem = this.currentXbMessageItem;
        if (!currentItem) {
          console.warn('无法获取当前线报消息项信息');
          return;
        }

        // 构建常用商品数据
        const favoriteData = {
          skuid: this.getJsonValue(currentItem.jsonQueryResult, 'spuid') || currentItem.spuid || currentItem.skuid || '',
          productName: currentItem.skuName || currentItem.productName || '',
          shopName: this.getShopName(currentItem),
          shopId: this.getShopId(currentItem),
          productUrl: currentItem.materialUrl || currentItem.productUrl || '',
          productImage: this.getProductImage(currentItem),
          price: currentItem.price || '',
          commissionInfo: currentItem.commissionInfo || '',
          productId: productId,
          productStatus: productStatus,
          remark: `自动添加 - 发品时间: ${new Date().toLocaleString()}${outerId ? `, 商家编码: ${outerId}` : ''}`
        };

        // 调用API添加到常用商品
        const res = await addToFavorites(favoriteData);
        if (res.code === 200) {
          console.log('已自动添加到常用商品');
        } else {
          console.warn('自动添加到常用商品失败:', res.msg);
        }
      } catch (error) {
        console.error('自动添加到常用商品出错:', error);
      }
    },

    /** 接收通用发品弹窗成功事件：等待接口返回后自动加常用，但不关闭页面 */
    onPublishDialogSuccess(res) {
      try {
        if (this.currentXbMessageItem) {
          addToFavoritesAfterPublishFromXb(this.currentXbMessageItem, res).then(() => {
            this.$store.dispatch('app/triggerFavoriteProductRefresh');
          });
        }
      } catch (e) { /* 忽略解析异常 */ }
    },

    /** 获取店铺名称 */
    getShopName(item) {
      if (item.jsonShopInfo) {
        try {
          const shopInfo = JSON.parse(item.jsonShopInfo);
          return shopInfo.shopName || '';
        } catch (e) {
          return '';
        }
      }
      return item.shopName || '';
    },

    /** 获取店铺ID */
    getShopId(item) {
      if (item.jsonShopInfo) {
        try {
          const shopInfo = JSON.parse(item.jsonShopInfo);
          return shopInfo.shopId || '';
        } catch (e) {
          return '';
        }
      }
      return item.shopId || '';
    },

    /** 获取商品图片 */
    getProductImage(item) {
      if (item.jsonQueryResult && item.jsonQueryResult.materialUrl) {
        return item.jsonQueryResult.materialUrl;
      }
      if (item.productImage) {
        return item.productImage;
      }
      return '';
    },
    
    /** 添加到常用商品 */
    async addToFavorites(child) {
      try {
        // 检查是否已经添加到常用
        const spuid = this.getJsonValue(child.jsonQueryResult, 'spuid') || child.spuid || child.skuid;
        const existingProduct = await getBySkuid(spuid);
        if (existingProduct && existingProduct.data) {
          this.$modal.msgWarning("该商品已在常用列表中");
          return;
        }
        
        // 构建常用商品数据
        const favoriteData = {
          skuid: spuid,
          productName: child.skuName,
          shopName: this.getJsonValue(child.jsonQueryResult, 'shopInfo.shopName') || '',
          shopId: this.getJsonValue(child.jsonQueryResult, 'shopInfo.shopId') || '',
          productUrl: this.getJsonValue(child.jsonQueryResult, 'materialUrl') || '',
          productImage: this.getJsonValue(child.jsonQueryResult, 'imageInfo.mainImage') || '',
          price: child.firstPrice || '',
          commissionInfo: this.getJsonValue(child.jsonQueryResult, 'commissionInfo.commissionShare') ? 
            `${this.getJsonValue(child.jsonQueryResult, 'commissionInfo.commissionShare')}%` : '',
          category: this.getJsonValue(child.jsonQueryResult, 'categoryInfo.cid3Name') || '',
          brand: this.getJsonValue(child.jsonQueryResult, 'brandName') || '',
          remark: `来自线报消息: ${child.skuName}`,
          isTop: 0,
          sortWeight: 0
        };
        
        // 添加到常用列表
        const result = await addToFavorites(favoriteData);
        if (result.code === 200) {
          this.$modal.msgSuccess("已添加到常用商品列表");
        } else {
          this.$modal.msgError(result.msg || "添加失败");
        }
      } catch (error) {
        console.error('添加到常用失败:', error);
        this.$modal.msgError("添加失败，请稍后重试");
      }
    }
  }
};
</script>

<style scoped>
.statistics-card {
  text-align: center;
  padding: 10px;
}

.statistics-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.statistics-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.mb20 {
  margin-bottom: 20px;
}

.original-message-content .el-textarea__inner {
  font-size: 18px !important;
  font-weight: bold !important;
  line-height: 1.6;
}

/* 一键转链相关样式 */
.img-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
}

.img-item {
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  padding: 8px;
  text-align: center;
  transition: all 0.3s ease;
}

.img-item:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.img-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.img-item img:hover {
  transform: scale(1.05);
}

.img-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.quick-link-dialog .el-dialog__body {
  max-height: 75vh;
  overflow-y: auto;
  padding: 20px;
}

/* 强制左右两栏布局 */
.quick-link-top-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  margin: 10px 0;
  /* 防止换行，若宽度不足，允许横向滚动 */
  white-space: nowrap;
  overflow-x: auto;
}
.quick-link-col {
  flex: 1 0 0;
  min-width: 480px; /* 两栏最小宽度，屏幕窄时出现横向滚动 */
  white-space: normal; /* 内部文本正常换行 */
}

.quick-link-dialog .el-dialog {
  margin: 5vh auto !important;
}

/* 响应式优化 */
@media (max-width: 1600px) {
  .quick-link-dialog .el-dialog {
    width: 95% !important;
  }
}

@media (max-width: 1200px) {
  .quick-link-dialog .el-dialog {
    width: 98% !important;
  }
  
  .img-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 12px;
  }
  
  .img-item img {
    height: 100px;
  }
}

/* 弹窗内容优化 */
.quick-link-dialog .el-descriptions {
  margin-bottom: 20px;
}

.quick-link-dialog .el-tabs {
  margin-top: 20px;
}

.quick-link-dialog .el-alert {
  margin-bottom: 25px;
}

/* 发品弹窗优化 */
.quick-link-dialog .el-form-item {
  margin-bottom: 18px;
}

.quick-link-dialog .el-form-item__label {
  font-weight: 500;
  color: #303133;
}

.quick-link-dialog .el-input,
.quick-link-dialog .el-select,
.quick-link-dialog .el-textarea {
  width: 100%;
}

.quick-link-dialog .el-dialog__header {
  padding: 20px 20px 10px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.quick-link-dialog .el-dialog__footer {
  padding: 15px 20px 20px 20px;
  border-top: 1px solid #e4e7ed;
  text-align: right;
}

/* 转链结果展示优化 */
.quick-link-dialog .el-tabs__content {
  padding: 20px 0;
}

.quick-link-dialog .el-descriptions-item__label {
  font-weight: 500;
  color: #606266;
}

.quick-link-dialog .el-descriptions-item__content {
  color: #303133;
}

/* 按钮样式优化 */
.quick-link-dialog .el-button {
  margin-left: 8px;
}

.quick-link-dialog .el-button:first-child {
  margin-left: 0;
}
</style> 