<template>
  <div class="level-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button type="text" @click="goBack" class="back-btn">
          <i class="el-icon-arrow-left"></i>
          返回
        </el-button>
        <span class="page-title">{{
          isBatchMode
            ? "批量会员等级编辑"
            : shopName
            ? `${shopName} - 会员等级设置`
            : "会员等级设置"
        }}</span>
      </div>
      <div class="header-right">
        <el-button
          v-if="!isEditMode && !isBatchMode"
          type="primary"
          size="small"
          @click="handleEditLevel"
        >
          等级编辑
        </el-button>
        <div v-if="isEditMode" class="edit-actions">
          <el-button v-if="!isBatchMode" size="small" @click="handleCancelEdit"
            >取消</el-button
          >
          <el-button type="primary" size="small" @click="handleSaveEdit"
            >保存</el-button
          >
        </div>
      </div>
    </div>

    <!-- 店铺选择区域 (批量编辑模式) -->
    <div v-if="isBatchMode" class="shop-selector-section">
      <div class="selector-header">
        <span class="selector-title">请选择要编辑的门店区域</span>
      </div>
      <div class="shop-checkboxes">
        <div class="checkbox-container">
          <div class="checkbox-section">
            <!-- 独立的全选checkbox -->
            <el-checkbox
              v-model="isAllSelected"
              @change="handleAllSelectionChange"
              class="all-select-checkbox"
            >
              全选
            </el-checkbox>

            <!-- 店铺选择区域 -->
            <el-checkbox-group
              v-model="selectedShopIds"
              @change="handleShopSelectionChange"
              class="shop-checkbox-group"
            >
              <el-checkbox
                v-for="shop in availableShops"
                :key="shop.shopId"
                :label="shop.shopId"
                class="shop-checkbox"
              >
                {{ shop.shopName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div class="selection-summary">
            已选择 {{ getSelectedShopCount() }} 个门店
          </div>
        </div>
      </div>
    </div>

    <!-- 查看模式 -->
    <div v-if="!isEditMode" class="view-mode">
      <!-- 会员等级简洁列表 -->
      <div class="level-simple-table">
        <el-table :data="levelDetailData" style="width: 100%">
          <el-table-column
            prop="levelName"
            label="等级名称"
            width="200"
            align="center"
          >
            <template slot-scope="scope">
              <span :style="{ color: getLevelColor(scope.row.level) }">
                {{ scope.row.levelName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="所需成长值" width="200" align="center">
            <template slot-scope="scope">
              <span style="color: #1890ff; font-weight: 500;">
                {{ scope.row.startGrowthValue }}-{{ scope.row.endGrowthValue }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="会员人数" width="200" align="center">
            <template slot-scope="scope">
              <span style="color: #52c41a; font-weight: 500;">
                {{ scope.row.membershipCount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="会员权益" align="left">
            <template slot-scope="scope">
              <span style="color: #666; line-height: 1.5;">
                {{
                  scope.row.benefitsInfo || generateMemberBenefits(scope.row)
                }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 编辑模式 -->
    <div v-if="isEditMode" class="edit-mode">
      <!-- 会员等级设置表格 - 编辑模式 -->
      <div class="level-table-section">
        <h3 class="section-title">会员等级设置</h3>
        <el-table :data="editLevelData" border style="width: 100%">
          <el-table-column
            prop="levelName"
            label="等级"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <span :style="{ color: getLevelColor(scope.row.level) }">
                {{ scope.row.level }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="等级名称" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.levelName" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="成长值范围" width="280" align="center">
            <template slot-scope="scope">
              <div class="growth-range">
                <el-input-number
                  v-model="scope.row.startGrowthValue"
                  :min="0"
                  size="mini"
                  style="width: 120px;"
                ></el-input-number>
                <span style="margin: 0 5px;">-</span>
                <el-input-number
                  v-model="scope.row.endGrowthValue"
                  :min="scope.row.startGrowthValue"
                  size="mini"
                  style="width: 120px;"
                ></el-input-number>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="开启会员折扣" width="120" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enableDiscount"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="折扣率%" width="180" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.discountRate"
                :min="0"
                :max="100"
                size="mini"
                :disabled="!scope.row.enableDiscount"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="开启积分抵扣" width="120" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enablePointsDeduction"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="积分抵扣额度" width="180" align="center">
            <template slot-scope="scope">
              <div
                v-if="scope.row.enablePointsDeduction"
                class="deduction-amount-input"
              >
                <el-input-number
                  v-model="scope.row.pointsDeductionQuota"
                  :min="0"
                  :max="10000"
                  size="mini"
                  style="width: 120px;"
                ></el-input-number>
                <span style="margin-left: 5px; font-size: 12px; color: #666;"
                  >积分=1元</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="开启生日优惠券" width="130" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enableBirthdayCoupons"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="生日优惠券操作" width="150" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.enableBirthdayCoupons">
                <el-button
                  type="primary"
                  size="mini"
                  @click="handleAddCoupon(scope.row)"
                >
                  {{
                    scope.row.birthdayCouponsName ? "编辑优惠券" : "添加优惠券"
                  }}
                </el-button>
                <div
                  v-if="scope.row.birthdayCouponsName"
                  style="margin-top: 5px; font-size: 12px; color: #666;"
                >
                  {{ scope.row.birthdayCouponsName }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="开启生日双倍积分" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enableBirthdayReward"></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <!-- 只有最后一条记录显示操作按钮 -->
              <div v-if="scope.$index === editLevelData.length - 1">
                <el-button
                  type="primary"
                  size="mini"
                  @click="handleAddLevel()"
                  style="margin-right: 5px;"
                >
                  新增
                </el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="handleDeleteLevel(scope.$index)"
                  :disabled="editLevelData.length <= 1"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 积分有效期设置 - 编辑模式 -->
      <div class="points-validity-section">
        <h3 class="section-title">积分有效期设置</h3>
        <div class="validity-setting">
          <span>有效期天数</span>
          <el-input-number
            v-model="editPointsValidityDays"
            :min="1"
            style="width: 180px; margin: 0 10px;"
          ></el-input-number>
          <span>天</span>
        </div>
      </div>

      <!-- 积分任务管理 - 编辑模式 -->
      <div class="points-task-section">
        <h3 class="section-title">积分任务管理</h3>
        <el-table :data="editPointsTaskData" border style="width: 100%">
          <el-table-column
            prop="taskName"
            label="任务名称"
            width="120"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="taskDesc" label="任务描述" align="center">
          </el-table-column>
          <el-table-column label="是否启用" width="100" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.isEnabled"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleEditTask(scope.row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加优惠券弹框 -->
    <el-dialog
      title="添加优惠券"
      :visible.sync="showCouponDialog"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="couponForm" label-width="120px">
        <el-form-item label="优惠券名称" required>
          <el-input
            v-model="couponForm.birthdayCouponsName"
            placeholder="生日优惠券"
          ></el-input>
        </el-form-item>
        <el-form-item label="优惠券门槛金额" required>
          <el-input-number
            v-model="couponForm.birthdayCouponsThreshold"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入门槛金额"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="优惠券减免金额" required>
          <el-input-number
            v-model="couponForm.birthdayCouponsMinus"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入减免金额"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="优惠券有效时间" required>
          <el-select
            v-model="couponForm.couponsEffectiveTimeType"
            style="width: 100%"
          >
            <el-option label="当天" :value="1"></el-option>
            <el-option label="7天" :value="2"></el-option>
            <el-option label="本月" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showCouponDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCouponForm">确认添加</el-button>
      </div>
    </el-dialog>

    <!-- 每日签到设置弹框 -->
    <el-dialog
      title="每日积分设置"
      :visible.sync="showSignInDialog"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="sign-in-form">
        <div class="form-item">
          <span class="label">连续签到1天</span>
          <el-input-number
            v-model="dailySignSettings.taskConfigDetail.oneDay"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
        <div class="form-item">
          <span class="label">连续签到2天</span>
          <el-input-number
            v-model="dailySignSettings.taskConfigDetail.twoDay"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
        <div class="form-item">
          <span class="label">连续签到3天</span>
          <el-input-number
            v-model="dailySignSettings.taskConfigDetail.threeDay"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
        <div class="form-item">
          <span class="label">连续签到4天</span>
          <el-input-number
            v-model="dailySignSettings.taskConfigDetail.fourDay"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
        <div class="form-item">
          <span class="label">连续签到5天</span>
          <el-input-number
            v-model="dailySignSettings.taskConfigDetail.fiveDay"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
        <div class="form-item">
          <span class="label">连续签到6天</span>
          <el-input-number
            v-model="dailySignSettings.taskConfigDetail.sixDay"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
        <div class="form-item">
          <span class="label">连续签到7天</span>
          <el-input-number
            v-model="dailySignSettings.taskConfigDetail.sevenDay"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showSignInDialog = false">取消</el-button>
        <el-button type="primary" @click="saveSignInForm">确认</el-button>
      </div>
    </el-dialog>

    <!-- 浏览商品积分设置弹框 -->
    <el-dialog
      title="浏览商品积分/成长值配置"
      :visible.sync="showBrowseDialog"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="browse-form">
        <div class="form-item">
          <span class="label">每浏览1个商品积分增加</span>
          <el-input-number
            v-model="viewGoodsSettings.taskConfigDetail.oneGoodsViewPoints"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
        <div class="form-item">
          <span class="label">该任务每日最高可获积分</span>
          <el-input-number
            v-model="viewGoodsSettings.taskConfigDetail.dailyPointsLimit"
            :min="0"
            :max="1000"
            size="small"
            controls-position="right"
          ></el-input-number>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showBrowseDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBrowseForm">确认</el-button>
      </div>
    </el-dialog>

    <!-- 购买商品任务配置弹框 -->
    <el-dialog
      title="购买商品任务配置"
      :visible.sync="showPurchaseDialog"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="purchase-form">
        <div class="form-item">
          <span class="label">购买商品实付</span>
          <el-input-number
            v-model="buyGoodsSettings.taskConfigDetail.pointsRatioAmount"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
          <span class="unit">元获得1积分</span>
        </div>
        <div class="form-item">
          <span class="label">该任务每日最高获得</span>
          <el-input-number
            v-model="buyGoodsSettings.taskConfigDetail.dailyPointsLimit"
            :min="0"
            :max="10000"
            size="small"
            controls-position="right"
          ></el-input-number>
          <span class="unit">积分</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPurchaseDialog = false">取消</el-button>
        <el-button type="primary" @click="savePurchaseForm">确认</el-button>
      </div>
    </el-dialog>

    <!-- 分享商品任务配置弹框 -->
    <el-dialog
      title="分享商品任务配置"
      :visible.sync="showShareDialog"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="share-form">
        <div class="form-item">
          <span class="label">每分享1个商品1次获得</span>
          <el-input-number
            v-model="shareGoodsSettings.taskConfigDetail.oneSharePoints"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
          <span class="unit">积分</span>
        </div>
        <div class="form-item">
          <span class="label">该任务每日最高获得</span>
          <el-input-number
            v-model="shareGoodsSettings.taskConfigDetail.dailyPointsLimit"
            :min="0"
            :max="1000"
            size="small"
            controls-position="right"
          ></el-input-number>
          <span class="unit">积分</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showShareDialog = false">取消</el-button>
        <el-button type="primary" @click="saveShareForm">确认</el-button>
      </div>
    </el-dialog>

    <!-- 评价商品任务配置弹框 -->
    <el-dialog
      title="评价商品任务配置"
      :visible.sync="showReviewDialog"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="review-form">
        <div class="form-item">
          <span class="label">文字评价1个商品获得</span>
          <el-input-number
            v-model="commentGoodsSettings.taskConfigDetail.textCommentPoints"
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
          <span class="unit">积分</span>
        </div>
        <div class="form-item">
          <span class="label">图文评价1个商品获得</span>
          <el-input-number
            v-model="
              commentGoodsSettings.taskConfigDetail.imageTextCommentPoints
            "
            :min="0"
            :max="100"
            size="small"
            controls-position="right"
          ></el-input-number>
          <span class="unit">积分</span>
        </div>
        <div class="form-item">
          <span class="label">该任务每日最高获得</span>
          <el-input-number
            v-model="commentGoodsSettings.taskConfigDetail.dailyPointsLimit"
            :min="0"
            :max="1000"
            size="small"
            controls-position="right"
          ></el-input-number>
          <span class="unit">积分</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" @click="saveReviewForm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "LevelDetail",
  data() {
    return {
      isEditMode: false,
      shopId: "", // 店铺ID
      shopName: "", // 店铺名称
      recordId: null, // 记录ID，用于调用接口获取设置数据
      isBatchMode: false, // 是否为批量编辑模式
      selectedShopIds: [], // 选中的店铺ID列表
      availableShops: [], // 可选择的店铺列表
      isAllSelected: false, // 全选状态
      pointsValidityDays: 365,
      // 弹框状态
      showCouponDialog: false,
      showSignInDialog: false,
      showBrowseDialog: false,
      showPurchaseDialog: false,
      showShareDialog: false,
      showReviewDialog: false,
      // 弹框表单数据
      couponForm: {
        birthdayCouponsName: "",
        birthdayCouponsThreshold: 0,
        birthdayCouponsMinus: 0,
        couponsEffectiveTimeType: 1
      },
      currentEditingLevel: null, // 当前正在编辑优惠券的等级
      // 积分任务设置数据（按接口格式）
      dailySignSettings: {
        taskEnable: false,
        taskConfigDetail: {
          oneDay: 0,
          twoDay: 0,
          threeDay: 0,
          fourDay: 0,
          fiveDay: 0,
          sixDay: 0,
          sevenDay: 0
        },
        taskDesc: ""
      },
      viewGoodsSettings: {
        taskEnable: false,
        taskConfigDetail: {
          oneGoodsViewPoints: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      },
      buyGoodsSettings: {
        taskEnable: false,
        taskConfigDetail: {
          pointsRatioAmount: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      },
      shareGoodsSettings: {
        taskEnable: false,
        taskConfigDetail: {
          oneSharePoints: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      },
      commentGoodsSettings: {
        taskEnable: false,
        taskConfigDetail: {
          textCommentPoints: 0,
          imageTextCommentPoints: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      },
      editPointsValidityDays: 365,
      levelDetailData: [
        {
          level: "LV1",
          levelName: "LV1",
          levelDisplayName: "铜牌会员",
          startGrowthValue: 0,
          endGrowthValue: 100,
          requiredGrowthValue: "100",
          membershipCount: 1250,
          memberBenefits: "新会员双倍积分，享受基础会员价格优惠",
          enableDiscount: true,
          discountRate: 5,
          enablePointsDeduction: false,
          pointsDeductionQuota: 100,
          enableBirthdayCoupons: true,
          enableBirthdayReward: false,
          birthdayCouponsName: "",
          birthdayCouponsThreshold: 0,
          birthdayCouponsMinus: 0,
          couponsEffectiveTimeType: 1,
          benefitsInfo: ""
        },
        {
          level: "LV2",
          levelName: "LV2",
          levelDisplayName: "银牌会员",
          startGrowthValue: 101,
          endGrowthValue: 500,
          requiredGrowthValue: "500",
          membershipCount: 850,
          memberBenefits: "享受9.5折优惠，每月专属优惠券，生日礼品",
          enableDiscount: true,
          discountRate: 10,
          enablePointsDeduction: true,
          pointsDeductionQuota: 100,
          enableBirthdayCoupons: true,
          enableBirthdayReward: true,
          birthdayCouponsName: "",
          birthdayCouponsThreshold: 0,
          birthdayCouponsMinus: 0,
          couponsEffectiveTimeType: 1,
          benefitsInfo: ""
        },
        {
          level: "LV3",
          levelName: "LV3",
          levelDisplayName: "金牌会员",
          startGrowthValue: 501,
          endGrowthValue: 1200,
          requiredGrowthValue: "1,200",
          membershipCount: 450,
          memberBenefits: "享受9折优惠，免费配送服务，专属客服支持",
          enableDiscount: true,
          discountRate: 15,
          enablePointsDeduction: true,
          pointsDeductionQuota: 100,
          enableBirthdayCoupons: true,
          enableBirthdayReward: true,
          birthdayCouponsName: "",
          birthdayCouponsThreshold: 0,
          birthdayCouponsMinus: 0,
          couponsEffectiveTimeType: 1,
          benefitsInfo: ""
        },
        {
          level: "LV4",
          levelName: "LV4",
          levelDisplayName: "钻石会员",
          startGrowthValue: 1201,
          endGrowthValue: 9999,
          requiredGrowthValue: "2,500",
          membershipCount: 180,
          memberBenefits: "享受8.5折优惠，优先配送，专属活动邀请，年度礼品",
          enableDiscount: true,
          discountRate: 20,
          enablePointsDeduction: true,
          pointsDeductionQuota: 100,
          enableBirthdayCoupons: true,
          enableBirthdayReward: true,
          birthdayCouponsName: "",
          birthdayCouponsThreshold: 0,
          birthdayCouponsMinus: 0,
          couponsEffectiveTimeType: 1,
          benefitsInfo: ""
        }
      ],
      editLevelData: [],
      editPointsTaskData: []
    };
  },
  created() {
    // 重置页面状态
    this.resetPageState();

    // 从路由参数获取店铺信息
    this.shopId = this.$route.query.shopId;
    this.shopName = this.$route.query.shopName;
    this.recordId = this.$route.query.id;

    // 检查是否为批量编辑模式
    this.isBatchMode = this.$route.query.mode === "batch";

    // 如果是单独店铺模式，确保退出批量编辑模式并进入查看模式
    if (this.shopId && this.shopName && !this.isBatchMode) {
      this.isEditMode = false; // 默认进入查看模式
    }

    // 为现有数据生成会员权益信息
    this.levelDetailData = this.levelDetailData.map(level => ({
      ...level,
      benefitsInfo: level.benefitsInfo || this.generateMemberBenefits(level)
    }));
  },
  mounted() {
    if (this.isBatchMode) {
      // 批量编辑模式：初始化店铺数据并自动进入编辑状态
      this.initBatchMode();
      this.handleEditLevel();
    } else if (this.shopId && this.shopName) {
      // 单独店铺模式：默认进入查看模式
      this.isEditMode = false;

      // 如果有记录ID，获取设置数据进行回显
      if (this.recordId) {
        this.loadSettingsData();
      }
    }
  },
  methods: {
    // 获取默认的等级数据
    getDefaultLevelData() {
      return [
        {
          level: "LV1",
          levelName: "等级1",
          startGrowthValue: 0,
          endGrowthValue: 100,
          enableDiscount: false,
          discountRate: 0,
          enablePointsDeduction: false,
          pointsDeductionQuota: 100,
          enableBirthdayCoupons: false,
          birthdayCouponsName: "",
          birthdayCouponsThreshold: 0,
          birthdayCouponsMinus: 0,
          couponsEffectiveTimeType: 1,
          enableBirthdayReward: false,
          membershipCount: 0,
          benefitsInfo: ""
        }
      ];
    },

    // 重置页面状态
    resetPageState() {
      // 重置编辑状态
      this.isEditMode = false;
      this.isBatchMode = false;

      // 重置店铺相关数据
      this.shopId = "";
      this.shopName = "";
      this.recordId = null;
      this.selectedShopIds = [];
      this.availableShops = [];
      this.isAllSelected = false;

      // 重置编辑数据
      this.levelDetailData = [];
      this.editLevelData = [];
      this.editPointsTaskData = [];
      this.editPointsValidityDays = 365;

      // 重置弹框状态
      this.showCouponDialog = false;
      this.showSignInDialog = false;
      this.showBrowseDialog = false;
      this.showPurchaseDialog = false;
      this.showShareDialog = false;
      this.showReviewDialog = false;

      // 重置表单数据
      this.couponForm = {
        birthdayCouponsName: "",
        birthdayCouponsThreshold: 0,
        birthdayCouponsMinus: 0,
        couponsEffectiveTimeType: 1
      };
      this.currentEditingLevel = null;

      // 重置积分任务设置数据
      this.dailySignSettings = {
        taskEnable: false,
        taskConfigDetail: {
          oneDay: 0,
          twoDay: 0,
          threeDay: 0,
          fourDay: 0,
          fiveDay: 0,
          sixDay: 0,
          sevenDay: 0
        },
        taskDesc: ""
      };
      this.viewGoodsSettings = {
        taskEnable: false,
        taskConfigDetail: {
          oneGoodsViewPoints: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      };
      this.buyGoodsSettings = {
        taskEnable: false,
        taskConfigDetail: {
          pointsRatioAmount: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      };
      this.shareGoodsSettings = {
        taskEnable: false,
        taskConfigDetail: {
          oneSharePoints: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      };
      this.commentGoodsSettings = {
        taskEnable: false,
        taskConfigDetail: {
          textCommentPoints: 0,
          imageTextCommentPoints: 0,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 0
        },
        taskDesc: ""
      };
    },

    // 加载设置数据并进行回显
    loadSettingsData() {
      if (!this.recordId) {
        // 没有记录ID时，查看模式下不显示数据，编辑模式下使用默认数据
        this.levelDetailData = [];
        return;
      }

      this.$api.mer_admin
        .membershipEnableGetSettings({
          id: this.recordId
        })
        .then(res => {
          console.log("获取会员设置数据:", res);
          if (res.data && res.data.code == 200) {
            const settingsData = res.data.data;
            this.applySettingsData(settingsData);
          } else {
            console.error("获取设置数据失败:", res.data?.message);
            // 获取失败时，查看模式下不显示数据
            this.levelDetailData = [];
          }
        })
        .catch(err => {
          console.error("获取会员设置失败:", err);
          // 接口调用失败时，查看模式下不显示数据
          this.levelDetailData = [];
        });
    },

    // 应用设置数据到表单
    applySettingsData(settingsData) {
      if (!settingsData) {
        // 如果获取不到设置，查看模式下不显示数据
        this.levelDetailData = [];
        return;
      }

      // 回显积分有效天数
      if (settingsData.pointsValidDays) {
        this.pointsValidityDays = settingsData.pointsValidDays;
      }

      // 回显会员等级设置列表
      if (
        settingsData.levelSettingsList &&
        settingsData.levelSettingsList.length > 0
      ) {
        this.levelDetailData = settingsData.levelSettingsList.map(level => ({
          level: level.level,
          levelName: level.levelName,
          startGrowthValue: level.startGrowthValue,
          endGrowthValue: level.endGrowthValue,
          enableDiscount: level.enableDiscount,
          discountRate: level.discountRate,
          enablePointsDeduction: level.enablePointsDeduction || false,
          pointsDeductionQuota: level.pointsDeductionQuota || 100,
          enableBirthdayCoupons: level.enableBirthdayCoupons,
          birthdayCouponsName: level.birthdayCouponsName || "",
          birthdayCouponsThreshold: level.birthdayCouponsThreshold || 0,
          birthdayCouponsMinus: level.birthdayCouponsMinus || 0,
          couponsEffectiveTimeType: level.couponsEffectiveTimeType || 1,
          enableBirthdayReward: level.enableBirthdayReward,
          membershipCount: level.membershipCount || 0,
          benefitsInfo: level.benefitsInfo || ""
        }));
      } else {
        // 如果没有等级设置列表，查看模式下不显示数据
        this.levelDetailData = [];
      }

      // 直接使用接口数据，不做映射
      if (settingsData.dailySignSettings) {
        this.dailySignSettings = { ...settingsData.dailySignSettings };
      }

      if (settingsData.viewGoodsSettings) {
        this.viewGoodsSettings = { ...settingsData.viewGoodsSettings };
      }

      if (settingsData.buyGoodsSettings) {
        this.buyGoodsSettings = { ...settingsData.buyGoodsSettings };
      }

      if (settingsData.shareGoodsSettings) {
        this.shareGoodsSettings = { ...settingsData.shareGoodsSettings };
      }

      if (settingsData.commentGoodsSettings) {
        this.commentGoodsSettings = { ...settingsData.commentGoodsSettings };
      }

      console.log("数据回显完成");
    },

    // 生成会员权益描述
    generateMemberBenefits(level) {
      const benefits = [];

      // 会员折扣权益
      if (level.enableDiscount && level.discountRate) {
        const discount = (100 - level.discountRate) / 10;
        benefits.push(`享受${discount}折优惠`);
      }

      // 积分兑换权益
      if (level.enablePointsDeduction) {
        benefits.push("积分兑换商品");
      }

      // 生日优惠券权益
      if (level.enableBirthdayCoupons) {
        benefits.push("有生日优惠券");
      }

      // 生日双倍积分权益
      if (level.enableBirthdayReward) {
        benefits.push("生日双倍积分");
      }

      return benefits.length > 0 ? benefits.join("，") : "暂无特殊权益";
    },

    // 保存设置数据
    saveSettingsData() {
      const saveData = {
        shopIdList: this.isBatchMode ? this.selectedShopIds : [this.shopId],
        pointsValidDays: this.pointsValidityDays,
        enable: true,
        levelSettingsList: this.levelDetailData.map(level => ({
          level: level.level,
          levelName: level.levelName,
          startGrowthValue: level.startGrowthValue,
          endGrowthValue: level.endGrowthValue,
          enableDiscount: level.enableDiscount,
          discountRate: level.discountRate,
          enablePointsDeduction: level.enablePointsDeduction || false,
          pointsDeductionQuota: level.pointsDeductionQuota || 100,
          enableBirthdayCoupons: level.enableBirthdayCoupons,
          birthdayCouponsName: level.birthdayCouponsName,
          birthdayCouponsThreshold: level.birthdayCouponsThreshold,
          birthdayCouponsMinus: level.birthdayCouponsMinus,
          couponsEffectiveTimeType: level.couponsEffectiveTimeType,
          enableBirthdayReward: level.enableBirthdayReward,
          membershipCount: level.membershipCount,
          benefitsInfo: this.generateMemberBenefits(level)
        })),
        dailySignSettings: {
          ...this.dailySignSettings,
          taskDesc: "第一天签到1分，第二天2分，第三天3分，连续7天10分"
        },
        buyGoodsSettings: {
          ...this.buyGoodsSettings,
          taskDesc: "购买1元=1分，每天最多获得500分"
        },
        shareGoodsSettings: {
          ...this.shareGoodsSettings,
          taskDesc: "分享一个商品获得5分，每天最多获得3次"
        },
        commentGoodsSettings: {
          ...this.commentGoodsSettings,
          taskDesc: "评价一个商品获得3分，每天最多获得5次"
        },
        viewGoodsSettings: {
          ...this.viewGoodsSettings,
          taskDesc: "浏览一个商品获得1分，每天最多获得2分"
        }
      };

      console.log("保存数据:", saveData);

      this.$api.mer_admin
        .membershipEnableSaveSettings(saveData)
        .then(res => {
          console.log("保存设置数据:", res);
          if (res.data && res.data.code == 200) {
            this.$message.success("设置保存成功");
          } else {
            this.$message.error(res.data?.message || "保存失败");
          }
        })
        .catch(err => {
          console.error("保存设置失败:", err);
          this.$message.error("保存失败");
        });
    },

    goBack() {
      // 获取当前路由名称
      const currentRouteName = this.$route.name;

      // 从mainTabs中移除当前tab
      const mainTabs = this.$store.state.common.mainTabs;
      const filteredTabs = mainTabs.filter(
        tab => tab.name !== currentRouteName
      );
      this.$store.commit("common/updateMainTabs", filteredTabs);

      // 如果还有其他tab，跳转到最后一个tab，否则跳转到首页
      if (filteredTabs.length > 0) {
        const lastTab = filteredTabs[filteredTabs.length - 1];
        this.$router.push({
          name: lastTab.name,
          query: lastTab.query,
          params: lastTab.params
        });
      } else {
        this.$router.push({ name: "home" });
      }
    },

    // 初始化批量编辑模式
    initBatchMode() {
      // 从store中获取店铺列表
      const storeList = this.storeList || [];

      // 构建可选择的店铺列表，不包含全选选项
      this.availableShops = storeList.map(shop => ({
        shopId: shop.shopId,
        shopName: shop.shopName
      }));

      // 默认不选择任何店铺
      this.selectedShopIds = [];
    },

    // 处理全选状态变化
    handleAllSelectionChange(isSelected) {
      console.log("全选状态变化:", isSelected);

      if (isSelected) {
        // 选择全选：选择所有店铺
        this.selectedShopIds = this.availableShops.map(shop => shop.shopId);
        console.log("全选后结果:", this.selectedShopIds);
      } else {
        // 取消全选：清空所有选择
        this.selectedShopIds = [];
        console.log("取消全选后结果:", this.selectedShopIds);
      }
    },

    // 处理店铺选择变化
    handleShopSelectionChange(selectedIds) {
      console.log("店铺选择变化:", selectedIds);

      // 更新选择的店铺
      this.selectedShopIds = selectedIds;

      // 检查是否需要更新全选状态
      const allShopIds = this.availableShops.map(shop => shop.shopId);
      const isAllShopsSelected =
        allShopIds.length > 0 &&
        allShopIds.every(shopId => selectedIds.includes(shopId));

      // 更新全选状态，但不触发全选的change事件
      this.isAllSelected = isAllShopsSelected;

      console.log("店铺选择后，全选状态:", this.isAllSelected);
      console.log("最终选择结果:", this.selectedShopIds);
    },

    // 获取选中店铺数量
    getSelectedShopCount() {
      return this.selectedShopIds.length;
    },

    handleEditLevel() {
      this.isEditMode = true;
      // 如果没有等级数据，使用默认数据
      if (this.levelDetailData.length === 0) {
        this.levelDetailData = this.getDefaultLevelData();
      }
      // 深拷贝数据用于编辑
      this.editLevelData = JSON.parse(JSON.stringify(this.levelDetailData));
      this.editPointsTaskData = JSON.parse(JSON.stringify(this.pointsTaskData));
      console.log(this.editPointsTaskData);
      this.editPointsValidityDays = this.pointsValidityDays;
    },

    handleCancelEdit() {
      // 批量编辑模式下不允许取消编辑
      if (this.isBatchMode) {
        this.$message.warning("批量编辑模式下无法取消编辑");
        return;
      }
      this.isEditMode = false;
      this.editLevelData = [];
      this.editPointsTaskData = [];
    },

    handleSaveEdit() {
      // 保存编辑的数据，并为每个等级生成会员权益信息
      this.levelDetailData = JSON.parse(JSON.stringify(this.editLevelData)).map(
        level => ({
          ...level,
          benefitsInfo: this.generateMemberBenefits(level)
        })
      );
      this.pointsValidityDays = this.editPointsValidityDays;

      // 更新积分任务的启用状态：将 isEnabled 映射到 taskEnable
      this.updateTaskEnableStatus();

      this.isEditMode = false;

      // 调用保存接口
      this.saveSettingsData();
    },

    // 更新积分任务的启用状态：将 isEnabled 映射到 taskEnable
    updateTaskEnableStatus() {
      if (this.editPointsTaskData && this.editPointsTaskData.length > 0) {
        this.editPointsTaskData.forEach(task => {
          switch (task.taskName) {
            case "每日签到":
              this.dailySignSettings.taskEnable = task.isEnabled;
              break;
            case "浏览商品":
              this.viewGoodsSettings.taskEnable = task.isEnabled;
              break;
            case "购买商品":
              this.buyGoodsSettings.taskEnable = task.isEnabled;
              break;
            case "分享商品":
              this.shareGoodsSettings.taskEnable = task.isEnabled;
              break;
            case "评价商品":
              this.commentGoodsSettings.taskEnable = task.isEnabled;
              break;
          }
        });
      }
    },

    // 新增会员等级
    handleAddLevel() {
      // 创建新的等级数据
      const newLevel = {
        level: `LV${this.editLevelData.length + 1}`,
        levelName: `等级${this.editLevelData.length + 1}`,
        startGrowthValue: 0,
        endGrowthValue: 0,
        enableDiscount: false,
        discountRate: 0,
        enablePointsDeduction: false,
        pointsDeductionQuota: 100,
        enableBirthdayCoupons: false,
        birthdayCouponsName: "",
        birthdayCouponsThreshold: 0,
        birthdayCouponsMinus: 0,
        couponsEffectiveTimeType: 1,
        enableBirthdayReward: false,
        membershipCount: 0,
        benefitsInfo: ""
      };

      // 总是在最后添加新等级
      this.editLevelData.push(newLevel);
    },

    // 删除会员等级
    handleDeleteLevel(index) {
      if (this.editLevelData.length <= 1) {
        this.$message.warning("至少需要保留一个等级");
        return;
      }

      this.$confirm("确定要删除这个等级吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.editLevelData.splice(index, 1);
        })
        .catch(() => {
          // 用户取消删除
        });
    },

    handleAddCoupon(level) {
      this.currentEditingLevel = level;
      this.showCouponDialog = true;

      // 如果等级已有优惠券配置，则回显数据
      this.couponForm = {
        birthdayCouponsName: level.birthdayCouponsName || "生日优惠券",
        birthdayCouponsThreshold: level.birthdayCouponsThreshold || 0,
        birthdayCouponsMinus: level.birthdayCouponsMinus || 0,
        couponsEffectiveTimeType: level.couponsEffectiveTimeType || 1
      };
    },

    // 检查积分任务配置是否为空或未配置
    isTaskConfigEmpty(taskSettings) {
      if (!taskSettings || !taskSettings.taskConfigDetail) {
        return true;
      }

      const config = taskSettings.taskConfigDetail;

      // 检查关键配置字段是否都为0或空
      // 对于每日签到，检查所有天数配置
      if (config.hasOwnProperty("oneDay")) {
        return (
          !config.oneDay &&
          !config.twoDay &&
          !config.threeDay &&
          !config.fourDay &&
          !config.fiveDay &&
          !config.sixDay &&
          !config.sevenDay
        );
      }

      // 对于浏览商品，检查浏览积分
      if (config.hasOwnProperty("oneGoodsViewPoints")) {
        return !config.oneGoodsViewPoints;
      }

      // 对于购买商品，检查积分比例
      if (config.hasOwnProperty("pointsRatioAmount")) {
        return !config.pointsRatioAmount;
      }

      // 对于分享商品，检查分享积分
      if (config.hasOwnProperty("oneSharePoints")) {
        return !config.oneSharePoints;
      }

      // 对于评价商品，检查文字和图文评价积分
      if (config.hasOwnProperty("textCommentPoints")) {
        return !config.textCommentPoints && !config.imageTextCommentPoints;
      }

      // 默认情况：检查所有值是否都为0或空
      const values = Object.values(config);
      return values.every(value => !value || value === 0);
    },

    // 弹框相关方法
    handleEditSignIn() {
      this.showSignInDialog = true;
      // 如果配置为空或未配置，设置默认值
      if (this.isTaskConfigEmpty(this.dailySignSettings)) {
        this.dailySignSettings.taskConfigDetail = {
          oneDay: 1,
          twoDay: 2,
          threeDay: 3,
          fourDay: 4,
          fiveDay: 5,
          sixDay: 6,
          sevenDay: 10
        };
      }
    },

    handleEditBrowse() {
      this.showBrowseDialog = true;
      // 如果配置为空或未配置，设置默认值
      if (this.isTaskConfigEmpty(this.viewGoodsSettings)) {
        this.viewGoodsSettings.taskConfigDetail = {
          oneGoodsViewPoints: 1,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 2
        };
      }
    },

    handleEditPurchase() {
      this.showPurchaseDialog = true;
      // 如果配置为空或未配置，设置默认值
      if (this.isTaskConfigEmpty(this.buyGoodsSettings)) {
        this.buyGoodsSettings.taskConfigDetail = {
          pointsRatioAmount: 1,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 500
        };
      }
    },

    handleEditShare() {
      this.showShareDialog = true;
      // 如果配置为空或未配置，设置默认值
      if (this.isTaskConfigEmpty(this.shareGoodsSettings)) {
        this.shareGoodsSettings.taskConfigDetail = {
          oneSharePoints: 5,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 15
        };
      }
    },

    handleEditReview() {
      this.showReviewDialog = true;
      // 如果配置为空或未配置，设置默认值
      if (this.isTaskConfigEmpty(this.commentGoodsSettings)) {
        this.commentGoodsSettings.taskConfigDetail = {
          textCommentPoints: 3,
          imageTextCommentPoints: 5,
          enableDailyPointsLimit: true,
          dailyPointsLimit: 15
        };
      }
    },

    // 保存弹框数据
    saveCouponForm() {
      // 验证表单数据
      if (!this.couponForm.birthdayCouponsName) {
        this.$message.error("请输入优惠券名称");
        return;
      }
      if (
        !this.couponForm.birthdayCouponsThreshold &&
        this.couponForm.birthdayCouponsThreshold !== 0
      ) {
        this.$message.error("请输入优惠券门槛金额");
        return;
      }
      if (
        !this.couponForm.birthdayCouponsMinus &&
        this.couponForm.birthdayCouponsMinus !== 0
      ) {
        this.$message.error("请输入优惠券减免金额");
        return;
      }
      if (!this.couponForm.couponsEffectiveTimeType) {
        this.$message.error("请选择优惠券有效时间");
        return;
      }

      // 将优惠券数据设置到当前等级对象中
      if (this.currentEditingLevel) {
        this.currentEditingLevel.birthdayCouponsName = this.couponForm.birthdayCouponsName;
        this.currentEditingLevel.birthdayCouponsThreshold = this.couponForm.birthdayCouponsThreshold;
        this.currentEditingLevel.birthdayCouponsMinus = this.couponForm.birthdayCouponsMinus;
        this.currentEditingLevel.couponsEffectiveTimeType = this.couponForm.couponsEffectiveTimeType;
      }

      this.showCouponDialog = false;
      this.currentEditingLevel = null;
    },

    saveSignInForm() {
      // 生成任务描述并保存
      const taskDesc = this.generateDailySignDescription();
      this.dailySignSettings.taskDesc = taskDesc;

      // 同时更新editPointsTaskData中的任务描述
      if (this.editPointsTaskData && this.editPointsTaskData.length > 0) {
        const task = this.editPointsTaskData.find(
          t => t.taskName === "每日签到"
        );
        if (task) {
          task.taskDesc = taskDesc;
        }
      }

      this.showSignInDialog = false;
      // this.$message.success("每日签到设置已更新");
    },

    saveBrowseForm() {
      // 生成任务描述并保存
      const taskDesc = this.generateViewGoodsDescription();
      this.viewGoodsSettings.taskDesc = taskDesc;

      // 同时更新editPointsTaskData中的任务描述
      if (this.editPointsTaskData && this.editPointsTaskData.length > 0) {
        const task = this.editPointsTaskData.find(
          t => t.taskName === "浏览商品"
        );
        if (task) {
          task.taskDesc = taskDesc;
        }
      }

      this.showBrowseDialog = false;
      // this.$message.success("浏览商品设置已更新");
    },

    savePurchaseForm() {
      // 生成任务描述并保存
      const taskDesc = this.generateBuyGoodsDescription();
      this.buyGoodsSettings.taskDesc = taskDesc;

      // 同时更新editPointsTaskData中的任务描述
      if (this.editPointsTaskData && this.editPointsTaskData.length > 0) {
        const task = this.editPointsTaskData.find(
          t => t.taskName === "购买商品"
        );
        if (task) {
          task.taskDesc = taskDesc;
        }
      }

      this.showPurchaseDialog = false;
      // this.$message.success("购买商品设置已更新");
    },

    saveShareForm() {
      // 生成任务描述并保存
      const taskDesc = this.generateShareGoodsDescription();
      this.shareGoodsSettings.taskDesc = taskDesc;

      // 同时更新editPointsTaskData中的任务描述
      if (this.editPointsTaskData && this.editPointsTaskData.length > 0) {
        const task = this.editPointsTaskData.find(
          t => t.taskName === "分享商品"
        );
        if (task) {
          task.taskDesc = taskDesc;
        }
      }

      this.showShareDialog = false;
      // this.$message.success("分享商品设置已更新");
    },

    saveReviewForm() {
      // 生成任务描述并保存
      const taskDesc = this.generateCommentGoodsDescription();
      this.commentGoodsSettings.taskDesc = taskDesc;

      // 同时更新editPointsTaskData中的任务描述
      if (this.editPointsTaskData && this.editPointsTaskData.length > 0) {
        const task = this.editPointsTaskData.find(
          t => t.taskName === "评价商品"
        );
        if (task) {
          task.taskDesc = taskDesc;
        }
      }

      this.showReviewDialog = false;
      // this.$message.success("评价商品设置已更新");
    },

    handleEditTask(row) {
      switch (row.taskName) {
        case "每日签到":
          this.handleEditSignIn();
          break;
        case "浏览商品":
          this.handleEditBrowse();
          break;
        case "购买商品":
          this.handleEditPurchase();
          break;
        case "分享商品":
          this.handleEditShare();
          break;
        case "评价商品":
          this.handleEditReview();
          break;
        default:
          this.$message.info(`编辑任务"${row.taskName}"功能待实现`);
      }
    },

    getLevelColor(levelName) {
      const colorMap = {
        LV1: "#52c41a",
        LV2: "#1890ff",
        LV3: "#fa8c16",
        LV4: "#f5222d"
      };
      return colorMap[levelName] || "#666";
    },

    // 生成每日签到任务描述
    generateDailySignDescription() {
      const config = this.dailySignSettings.taskConfigDetail;
      if (
        !config ||
        (!config.oneDay &&
          !config.twoDay &&
          !config.threeDay &&
          !config.fourDay &&
          !config.fiveDay &&
          !config.sixDay &&
          !config.sevenDay)
      ) {
        return "-";
      }

      const descriptions = [];
      if (config.oneDay) descriptions.push(`第一天签到${config.oneDay}分`);
      if (config.twoDay) descriptions.push(`第二天${config.twoDay}分`);
      if (config.threeDay) descriptions.push(`第三天${config.threeDay}分`);
      if (config.fourDay) descriptions.push(`第四天${config.fourDay}分`);
      if (config.fiveDay) descriptions.push(`第五天${config.fiveDay}分`);
      if (config.sixDay) descriptions.push(`第六天${config.sixDay}分`);
      if (config.sevenDay) descriptions.push(`连续7天${config.sevenDay}分`);

      return descriptions.length > 0 ? descriptions.join("，") : "-";
    },

    // 生成浏览商品任务描述
    generateViewGoodsDescription() {
      const config = this.viewGoodsSettings.taskConfigDetail;
      if (!config || !config.oneGoodsViewPoints) {
        return "-";
      }

      let description = `浏览一个商品获得${config.oneGoodsViewPoints}分`;
      if (config.enableDailyPointsLimit && config.dailyPointsLimit) {
        description += `，每天最多获得${config.dailyPointsLimit}分`;
      }

      return description;
    },

    // 生成购买商品任务描述
    generateBuyGoodsDescription() {
      const config = this.buyGoodsSettings.taskConfigDetail;
      if (!config || !config.pointsRatioAmount) {
        return "-";
      }

      let description = `购买${config.pointsRatioAmount}元=1分`;
      if (config.enableDailyPointsLimit && config.dailyPointsLimit) {
        description += `，每天最多获得${config.dailyPointsLimit}分`;
      }

      return description;
    },

    // 生成分享商品任务描述
    generateShareGoodsDescription() {
      const config = this.shareGoodsSettings.taskConfigDetail;
      if (!config || !config.oneSharePoints) {
        return "-";
      }

      let description = `分享一个商品获得${config.oneSharePoints}分`;
      if (config.enableDailyPointsLimit && config.dailyPointsLimit) {
        const maxTimes = Math.floor(
          config.dailyPointsLimit / config.oneSharePoints
        );
        description += `，每天最多获得${maxTimes}次`;
      }

      return description;
    },

    // 生成评价商品任务描述
    generateCommentGoodsDescription() {
      const config = this.commentGoodsSettings.taskConfigDetail;
      if (
        !config ||
        (!config.textCommentPoints && !config.imageTextCommentPoints)
      ) {
        return "-";
      }

      const descriptions = [];
      if (config.textCommentPoints) {
        descriptions.push(`文字评价获得${config.textCommentPoints}分`);
      }
      if (config.imageTextCommentPoints) {
        descriptions.push(`图文评价获得${config.imageTextCommentPoints}分`);
      }

      let description = descriptions.join("，");
      if (config.enableDailyPointsLimit && config.dailyPointsLimit) {
        description += `，每天最多获得${config.dailyPointsLimit}分`;
      }

      return description;
    }
  },
  computed: {
    ...mapState("userData", [
      "isMerchant",
      "marketList",
      "storeList",
      "marketId"
    ]),

    // 积分任务数据，优先使用编辑弹框中配置的数据进行生成展示
    pointsTaskData() {
      return [
        {
          taskName: "每日签到",
          taskDesc: this.generateDailySignDescription(),
          isEnabled: this.dailySignSettings.taskEnable
        },
        {
          taskName: "浏览商品",
          taskDesc: this.generateViewGoodsDescription(),
          isEnabled: this.viewGoodsSettings.taskEnable
        },
        {
          taskName: "购买商品",
          taskDesc: this.generateBuyGoodsDescription(),
          isEnabled: this.buyGoodsSettings.taskEnable
        },
        {
          taskName: "分享商品",
          taskDesc: this.generateShareGoodsDescription(),
          isEnabled: this.shareGoodsSettings.taskEnable
        },
        {
          taskName: "评价商品",
          taskDesc: this.generateCommentGoodsDescription(),
          isEnabled: this.commentGoodsSettings.taskEnable
        }
      ];
    }
  }
};
</script>

<style lang="scss" scoped>
.level-detail {
  background: #fff;
  min-height: calc(100vh - 84px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e8e8e8;

    .header-left {
      display: flex;
      align-items: center;

      .back-btn {
        color: #1890ff;
        font-size: 14px;
        margin-right: 15px;

        &:hover {
          color: #40a9ff;
        }
      }

      .page-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
    }

    .header-right {
      .edit-actions {
        .el-button {
          margin-left: 8px;
        }
      }
    }
  }

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 15px;
    padding-left: 10px;
    border-left: 4px solid #1890ff;
  }

  .level-simple-table {
    margin-bottom: 30px;

    .el-table {
      border: 1px solid #e8e8e8;
      border-radius: 6px;
      overflow: hidden;

      .el-table__header {
        th {
          background-color: #f8f9fa;
          color: #333;
          font-weight: 600;
          font-size: 14px;
          border-bottom: 1px solid #e8e8e8;
          padding: 12px 8px;
        }
      }

      .el-table__body {
        td {
          padding: 16px 8px;
          font-size: 14px;
          border-bottom: 1px solid #f0f0f0;
          vertical-align: middle;
        }

        tr:last-child td {
          border-bottom: none;
        }
      }
    }
  }

  .level-table-section {
    margin-bottom: 30px;

    .el-table {
      .el-table__header {
        th {
          background-color: #fafafa;
          color: #333;
          font-weight: 600;
          font-size: 13px;
        }
      }

      .el-table__body {
        td {
          padding: 12px 0;
          font-size: 13px;
        }
      }

      .growth-range {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .points-validity-section {
    margin-bottom: 30px;
    border-radius: 6px;

    .validity-setting {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #666;
    }
  }

  .points-task-section {
    .el-table {
      .el-table__header {
        th {
          background-color: #fafafa;
          color: #333;
          font-weight: 600;
          font-size: 13px;
        }
      }

      .el-table__body {
        td {
          padding: 12px 0;
          font-size: 13px;
        }
      }
    }
  }

  // 编辑模式特殊样式
  .edit-mode {
    .el-input-number {
      .el-input__inner {
        text-align: center;
      }
    }

    .el-switch {
      margin: 0;
    }
  }

  // 查看模式特殊样式
  .view-mode {
    .el-switch {
      pointer-events: none;
    }

    .el-button[disabled] {
      opacity: 0.6;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .level-detail {
    .level-simple-table,
    .level-table-section {
      overflow-x: auto;
    }
  }
}

@media (max-width: 768px) {
  .level-detail {
    padding: 15px;

    .level-simple-table {
      .el-table {
        .el-table__header th,
        .el-table__body td {
          padding: 12px 6px;
          font-size: 13px;
        }
      }
    }

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;

      .header-right {
        align-self: flex-end;
      }
    }
  }
}

// 店铺选择区域样式
.shop-selector-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e8e8e8;

  .selector-header {
    margin-bottom: 15px;

    .selector-title {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }

  .shop-checkboxes {
    .checkbox-container {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 20px;
    }

    .checkbox-section {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: center;
    }

    .all-select-checkbox {
      margin-right: 16px;
      margin-bottom: 12px;

      .el-checkbox__label {
        font-size: 14px;
        color: #333;
        font-weight: 500;
        padding-left: 8px;
      }

      &.is-checked {
        .el-checkbox__label {
          color: #1890ff;
          font-weight: 600;
        }
      }
    }

    .shop-checkbox-group {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      flex: 1;
    }

    .shop-checkbox {
      margin-right: 0;
      margin-bottom: 12px;

      .el-checkbox__label {
        font-size: 14px;
        color: #333;
        padding-left: 8px;
      }

      &.is-checked {
        .el-checkbox__label {
          color: #1890ff;
          font-weight: 500;
        }
      }

      &:hover {
        .el-checkbox__label {
          color: #1890ff;
        }
      }
    }

    .selection-summary {
      font-size: 14px;
      color: #666;
      padding: 8px 12px;
      background: #fff;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      white-space: nowrap;
      align-self: flex-start;
    }
  }
}

// 弹框样式
.sign-in-form,
// 积分抵扣额度输入框样式
.deduction-amount-input {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-input-number {
    .el-input__inner {
      text-align: center;
    }
  }

  span {
    white-space: nowrap;
    font-size: 12px;
    color: #666;
  }
}

.browse-form,
.purchase-form,
.share-form,
.review-form {
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .label {
      flex: 1;
      font-size: 14px;
      color: #333;
      margin-right: 15px;

      &::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
      }
    }

    .unit {
      margin-left: 8px;
      font-size: 14px;
      color: #666;
    }
  }
}

.dialog-footer {
  text-align: right;

  .el-button {
    margin-left: 10px;
  }
}
</style>
