<template >
  <div  class="watch-reward-page" v-loading="loading">
    <!-- 提示信息 -->
    <div class="tip-message" >
      设置观看奖励，用户达到直播观看时长后可领取奖励
    </div>

    <!-- 开启观看奖励开关 -->
    <div class="reward-switch">
      <span class="switch-label">开启观看奖励</span>
      <el-switch v-model="watchRewardForm.enabled"></el-switch>
    </div>

    <!-- 观看奖励设置 -->
    <div v-if="watchRewardForm.enabled" class="section-block">
      <div class="section-title">观看奖励设置</div>

      <!-- 表单内容 -->
      <el-form
        :model="watchRewardForm"
        :rules="rules"
        ref="watchRewardForm"
        label-width="130px"
      >
        <!-- 参与条件 -->
        <el-form-item label="参与条件" prop="participateCondition">
          <el-radio-group v-model="watchRewardForm.participateCondition">
            <el-radio label="1">达到指定观看时长发积分</el-radio>
            <el-radio label="2" v-if="this.projectFrom!=='颐安心'">启用完课积分</el-radio>
            <el-radio label="3">启动直播完课奖励</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 观看时长 -->
        <el-form-item label="观看时长" prop="watchDuration" v-if="watchRewardForm.participateCondition === '1'">
          <el-input v-model="watchRewardForm.watchDuration" placeholder="请输入观看时长" class="duration-input">
            <template #append>分钟</template>
          </el-input>
        </el-form-item>

        <!-- 完课率要求 -->
        <el-form-item label="完课率要求" prop="completionRate" v-if="watchRewardForm.participateCondition === '2' || watchRewardForm.participateCondition === '3'">
          <el-input-number
            v-model="watchRewardForm.completionRate"
            :min="1"
            :max="100"
            :precision="0"
            placeholder="请输入完课率"
            style="width: 200px;"
          ></el-input-number>
          <span style="margin-left: 10px; color: #909399;">%（观看时长占直播总时长的比例）</span>
        </el-form-item>



        <!-- 连续完课积分配置 -->
        <el-form-item label="连续完课积分" prop="pointsConfig" v-if="watchRewardForm.participateCondition === '2'">
          <div style="display: flex; flex-direction: column; gap: 10px;">
            <div v-for="(point, index) in watchRewardForm.pointsConfig" :key="index" style="display: flex; align-items: center;">
              <span style="width: 80px;">第{{ index + 1 }}天：</span>
              <el-input-number
                v-model="watchRewardForm.pointsConfig[index]"
                :min="0"
                :precision="0"
                placeholder="请输入积分值"
                style="width: 200px;"
              ></el-input-number>
              <span style="margin-left: 10px; color: #909399;">积分</span>
            </div>
          </div>
        </el-form-item>

        <!-- 实施动作（仅在达到指定观看时长时显示） -->
        <el-form-item label="实施动作" prop="action" v-if="watchRewardForm.participateCondition === '1'">
          <el-select v-model="watchRewardForm.action" placeholder="请选择实施动作" style="width: 300px;">
            <el-option
              v-for="item in actionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 领取提示语 -->
<!--        <el-form-item label="领取提示语" prop="receivePrompt">-->
<!--          <el-input v-model="watchRewardForm.receivePrompt" placeholder="请输入领取提示语"></el-input>-->
<!--        </el-form-item>-->


        <div v-if="watchRewardForm.participateCondition === '3'">
          <div class="section-title">直播红包答题设置</div>
          <el-form-item label="可答题次数">
            <el-input-number
              v-model="watchRewardForm.answerAttempts"
              :min="1"
              :precision="0"
              placeholder="请输入可答题次数"
              style="width: 200px;"
            ></el-input-number>
          </el-form-item>
          <el-button type="primary" plain icon="el-icon-plus" style="margin-bottom: 1%" @click="openQuestionDialog">选择试题</el-button>
          <div v-if="selectedQuestionList.length > 0" class="selected-question-card-list">
            <div
              v-for="row in selectedQuestionList"
              :key="row.id"
              class="selected-question-card"
            >
              <div class="selected-question-card-body">
                <div class="selected-question-card-title">{{ row.title }}</div>
                <div v-if="row.answer" class="selected-question-card-answer">答案：{{ row.answer }}</div>
                <div class="selected-question-card-meta">
                  <el-tag :type="row.type === 1 ? 'primary' : 'success'" size="small">{{ row.type === 1 ? '单选题' : '多选题' }}</el-tag>
                  <span class="selected-question-card-creator">{{ row.createBy }}</span>
                  <span class="selected-question-card-time">{{ row.createTime }}</span>
                </div>
              </div>
              <el-button type="text" class="selected-question-card-remove" @click="removeSelectedQuestion(row)">移除</el-button>
            </div>
          </div>

        </div>

        <div v-if="watchRewardForm.participateCondition === '3'">
          <div class="section-title">直播红包设置</div>
          <!-- 红包金额 -->
          <el-form-item label="红包金额" prop="redPacketAmount" v-if="watchRewardForm.participateCondition === '3'">
            <el-input-number v-model="watchRewardForm.redPacketAmount" :min="0.1" :max="10" :step="0.1"></el-input-number>
          </el-form-item>
          <!--   红包余额是否扣减开关      -->
          <el-form-item label="红包余额是否扣减开关">
            <el-radio-group v-model="watchRewardForm.isRedPackageBalanceDeduction">
              <el-radio label="1">开</el-radio>
              <el-radio label="2">关</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <div v-if="watchRewardForm.participateCondition === '3'">
          <div class="section-title">录播奖励设置</div>
          <!-- 是否录播可领取奖励 -->
          <el-form-item label="录播可领取奖励">
            <el-switch v-model="watchRewardForm.recordRedPacketEnabled"></el-switch>
          </el-form-item>
          <!-- 录播奖励配置列表 -->
          <div v-if="watchRewardForm.recordRedPacketEnabled">
            <div v-for="(item, index) in watchRewardForm.recordTimeRanges" :key="index" class="record-reward-item">
              <el-time-picker
                is-range
                v-model="item.range"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 280px;"
                @change="onTimeRangeChange(index)"
              ></el-time-picker>
              <el-checkbox-group v-model="item.rewardTypes" style="margin-left: 15px; flex-shrink: 0; width: 200px;">
                <el-checkbox label="1">红包</el-checkbox>
                <el-checkbox label="2">积分</el-checkbox>
                <el-checkbox label="3">核销卷</el-checkbox>
              </el-checkbox-group>
              <el-input-number v-if="item.rewardTypes.includes('1')" v-model="item.redPacketAmount" :min="0.1" :max="10" :step="0.1" style="width: 140px; margin-left: 15px;"></el-input-number>
              <el-input v-if="item.rewardTypes.includes('2')" v-model="item.scoreAmount" placeholder="积分值" style="width: 140px; margin-left: 15px;"></el-input>
              <el-select v-if="item.rewardTypes.includes('3')" v-model="item.couponIds" placeholder="请选择核销卷" clearable multiple style="width: 200px; margin-left: 15px;">
                <el-option
                  v-for="c in couponList"
                  :key="c.id"
                  :label="c.title + ' (' + c.id + ')'"
                  :value="c.id"
                ></el-option>
              </el-select>
              <el-button type="danger" icon="el-icon-delete" circle style="margin-left: 10px;" @click="removeRecordTimeRange(index)" v-if="watchRewardForm.recordTimeRanges.length > 1"></el-button>
            </div>
            <div v-if="timeRangeOverlap" style="color: #F56C6C; font-size: 12px; margin-top: -5px; margin-bottom: 10px;">时间段之间存在重叠，请重新选择</div>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="addRecordTimeRange">添加时间段</el-button>
          </div>
        </div>


        <!-- 红包设置（仅在达到指定观看时长时显示） -->
        <div v-if="watchRewardForm.participateCondition === '1'">
          <div class="section-title">红包设置</div>

          <!-- 根据实施动作类型显示不同的表单内容 -->
          <template v-if="watchRewardForm.action === '1'">
            <!-- 现金红包设置 -->
            <!-- 红包发放方式   1固定金额 2随机金额 -->
            <el-form-item label="红包发放方式" prop="redPacketType">
              <el-radio-group v-model="watchRewardForm.redPacketType">
                <el-radio label="1">固定金额</el-radio>
                <el-radio label="2">随机金额</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 红包金额 -->
            <el-form-item label="红包金额" prop="redPacketAmount">
              <el-input v-model="watchRewardForm.redPacketAmount" placeholder="请输入红包金额"></el-input>
            </el-form-item>

            <!-- 红包发放数量 -->
            <el-form-item label="红包发放数量" prop="redPacketCount">
              <el-input v-model="watchRewardForm.redPacketCount" placeholder="红包数量+28888人数"></el-input>
            </el-form-item>

            <!-- 红包领取方式  1二维码核销 2微信提现 -->
            <el-form-item label="红包领取方式" prop="receiveMethod">
              <el-radio-group v-model="watchRewardForm.receiveMethod">
                <el-radio label="1">二维码领取</el-radio>
                <el-radio label="2">微信发放</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>

          <template v-else>
            <!-- 积分红包设置 -->
            <!-- 积分值 -->
            <el-form-item label="积分值" prop="scoreAmount">
              <el-input
                v-model="watchRewardForm.scoreAmount"
                placeholder="请输入积分值"                style="width: 300px;"
              ></el-input>
            </el-form-item>

            <!-- 最大领取人数 -->
<!--            <el-form-item label="最大领取人数" prop="maxReceivers">-->
<!--              <el-input-->
<!--                v-model="watchRewardForm.maxReceivers"-->
<!--                placeholder="请输入最大领取人数"                style="width: 300px;"-->
<!--              ></el-input>-->
<!--            </el-form-item>-->
          </template>
        </div>

        <!-- 其他设置（仅在达到指定观看时长时显示） -->
        <div v-if="watchRewardForm.participateCondition === '1'">
          <div class="section-title">其他设置</div>

          <template v-if="watchRewardForm.action === '1'">
            <!-- 客服引导  1跟进企业微信 2不设置 -->
            <el-form-item label="客服引导" prop="showGuide">
              <el-radio-group v-model="watchRewardForm.showGuide">
                <el-radio label="1">跟进企业微信</el-radio>
                <el-radio label="2">不设置</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 客服引导语 -->
            <el-form-item label="客服引导语" prop="guideText">
              <el-input
                v-model="watchRewardForm.guideText"
                placeholder="请输入客服引导语"                style="width: 300px;"
              ></el-input>
            </el-form-item>
          </template>

          <template v-else>
            <!-- 积分使用引导语 -->
            <el-form-item label="积分使用引导语" prop="scoreGuideText">
              <el-input
                v-model="watchRewardForm.scoreGuideText"
                placeholder="请输入积分使用引导语"                style="width: 300px;"
              ></el-input>
            </el-form-item>

            <!-- 积分使用引导链接 -->
            <el-form-item label="积分使用引导链接" prop="scoreGuideLink">
              <el-input
                v-model="watchRewardForm.scoreGuideLink"
                placeholder="请输入积分使用引导链接"                style="width: 300px;"
              ></el-input>
            </el-form-item>

            <!-- 引导语 -->
<!--            <el-form-item label="引导语" prop="guideText">-->
<!--              <el-input-->
<!--                v-model="watchRewardForm.guideText"-->
<!--                placeholder="请输入引导语"                style="width: 300px;"-->
<!--              ></el-input>-->
<!--            </el-form-item>-->
          </template>
        </div>

        <!-- 保存按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="saveWatchReward">保存</el-button>
        </div>
      </el-form>
    </div>

    <!-- 选择今日问题弹窗 -->
    <el-dialog
      title="选择今日问题"
      :visible.sync="questionDialogVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      custom-class="question-select-dialog"
    >
      <div style="text-align: right; margin-bottom: 16px;">
        <el-input
          v-model="questionSearchTitle"
          placeholder="请输入题干搜索"
          style="width: 300px;"
          clearable
          @keyup.enter.native="handleQuestionSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleQuestionSearch"></el-button>
        </el-input>
      </div>
      <div v-loading="questionLoading" class="question-card-list">
        <div
          v-for="row in questionOptionList"
          :key="row.id"
          class="question-card"
          :class="{ 'is-selected': isQuestionSelected(row.id) }"
          @click="toggleQuestionCard(row)"
        >
          <div class="question-card-check">
            <i v-if="isQuestionSelected(row.id)" class="el-icon-success" style="color: #409EFF; font-size: 20px;"></i>
            <span v-else class="question-card-check-empty"></span>
          </div>
          <div class="question-card-body">
            <div class="question-card-title">{{ row.title }}</div>
            <div v-if="row.answer" class="question-card-answer">答案：{{ row.answer }}</div>
            <div class="question-card-meta">
              <el-tag :type="row.type === 1 ? 'primary' : 'success'" size="small">{{ row.type === 1 ? '单选' : '多选' }}</el-tag>
              <span class="question-card-creator">{{ row.createBy }}</span>
              <span class="question-card-time">{{ row.createTime }}</span>
            </div>
          </div>
        </div>
        <div v-if="!questionLoading && questionOptionList.length === 0" class="question-card-empty">暂无数据</div>
      </div>
      <pagination
        v-show="questionOptionTotal > 0"
        :total="questionOptionTotal"
        :page.sync="questionQueryParams.pageNum"
        :limit.sync="questionQueryParams.pageSize"
        @pagination="loadQuestionOptions"
        style="margin-top: 16px;"
      />
      <div slot="footer">
        <span style="float: left; line-height: 32px; color: #606266;">
          已选择 <span style="color: #409EFF;">{{ tempSelectedQuestions.length }}</span> 题
        </span>
        <el-button @click="questionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmQuestionSelection">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {addConfig, getConfig, updateConfig} from "@/api/live/liveQuestionLive";
import { listStoreCouponIssue } from "@/api/live/liveCouponIssue";
import { options as courserCouponOptions } from '@/api/his/courserCoupon'
import { getCourseQuestionBank, listCourseQuestionBank } from '@/api/course/courseQuestionBank'

export default {
  data() {
    return {
      projectFrom:process.env.VUE_APP_TITLE_INDEX,
      loading: true,
      liveId: null,
      // 完整配置缓存，保存时保留回放推送等其它模块字段
      configCache: {},
      watchRewardForm: {
        id: null,
        liveId: null,
        // 是否启用观看奖励
        enabled: false,
        // 参与条件 1:达到指定观看时长 2:启用完课积分
        participateCondition: '1',
        // 观看时长
        watchDuration: '',
        // 实施动作
        action: '2',
        // 领取提示语
        receivePrompt: '',
        // 红包发放方式（固定金额/随机金额）
        redPacketType: '1',
        // 红包金额
        redPacketAmount: '',
        //是否开启红包扣减
        isRedPackageBalanceDeduction: '2',
        // 红包发放数量
        redPacketCount: '',
        // 红包领取方式
        receiveMethod: '1',
        // 是否显示客服引导
        showGuide: '1',
        // 客服引导语
        guideText: '',
        // 积分值
        scoreAmount: '',
        // 是否录播可领取奖励
        recordRedPacketEnabled: false,
        // 录播奖励配置列表（前端展示用）
        recordTimeRanges: [{ range: null, rewardTypes: ['1'], redPacketAmount: '', scoreAmount: '', couponIds: [] }],
        // 录播奖励配置字符串（提交后端用）
        recordTimeRangeStr: '',
        // // 最大领取人数
        // maxReceivers: '',
        // 积分使用引导语
        scoreGuideText: '',
        // 积分使用引导链接
        scoreGuideLink: '',
        // 完课积分相关配置（participateCondition为2时使用）
        // 完课率要求（1-100）
        completionRate: 90,
        // 连续完课积分配置（第1-10天）
        pointsConfig: [100, 110, 120, 130, 140, 150, 160, 170, 180, 200],
        // 可答题次数
        answerAttempts: 3,
        // 今日问题ID（逗号分隔）
        finishQuestionIds: '',
      },
      rules:{
        participateCondition:[
          { required: true, message: '请选择参与条件', trigger: 'change'}
        ],
        watchDuration:[
          {
            validator: (rule, value, callback) => {
              if (this.watchRewardForm.participateCondition === '1') {
                if (!value) {
                  callback(new Error('请输入观看时长'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        completionRate:[
          {
            validator: (rule, value, callback) => {
              if (this.watchRewardForm.participateCondition === '2') {
                if (!value && value !== 0) {
                  callback(new Error('请输入完课率要求'));
                } else if (value < 1 || value > 100) {
                  callback(new Error('完课率要求范围为1-100'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        action:[
          {
            validator: (rule, value, callback) => {
              if (this.watchRewardForm.participateCondition === '1') {
                if (!value) {
                  callback(new Error('请选择实施动作'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        // receivePrompt:[
        //   { required: true, message: '请输入领取提示语', trigger: 'blur'}
        // ],
        redPacketType:[
          { required: true, message: '请选择红包发放方式', trigger: 'blur'}
        ],
        redPacketAmount:[
          { required: true, message: '请输入红包金额', trigger: 'blur'}
        ],
        scoreAmount:[
          { required: true, message: '请输入积分数量', trigger: 'blur'}
        ],
        receiveMethod:[
          { required: true, message: '请选择红包领取方式', trigger: 'blur'}
        ],
        // guideText:[
        //   { required: true, message: '请输入客服引导语', trigger: 'blur'}
        // ],
        showGuide:[
          { required: true, message: '请选择是否显示客服引导', trigger: 'blur'}
        ]
      },
      // 添加实施动作选项
      actionOptions: [
        // {
        //   label: '现金红包',
        //   value: '1'
        // },
        {
          label: '积分红包',
          value: '2'
        }
      ],
      timeRangeOverlap: false,
      // 核销卷列表（couponType=3）
      couponList: [],
      //答题
      questionDialogVisible: false,
      questionLoading: false,
      questionSearchTitle: '',
      questionOptionList: [],
      questionOptionTotal: 0,
      questionQueryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        status: 1
      },
      selectedQuestionList: [],
      tempSelectedQuestions: []
    };
  },
  watch: {
    // 监听路由的 query 参数变化
    '$route.query': {
      handler(newQuery) {
        this.liveId = this.$route.params.liveId
        this.watchRewardForm.liveId = this.liveId
        if(this.liveId == null) {
          return;
        }
        this.getLiveConfig();
      },
      // 初始化时立即执行一次
      immediate: true
    },
    // 监听开启观看奖励开关变化
    'watchRewardForm.enabled': {
      handler(newValue, oldValue) {
        // 只有当关闭开关时才自动保存（从 true 变为 false）
        if (oldValue === true && newValue === false && this.liveId) {
          this.autoSaveEnabled();
        }
      }
    }
  },
  created() {
    this.getCouponList();
  },
  methods: {

    // 获取核销卷列表（couponType=3）
    getCouponList() {

      courserCouponOptions().then(res=>{
        this.couponList = res.data;
      }).catch(res=>{

      //     listStoreCouponIssue({ pageNum: 1, pageSize: 999, couponType: '3' }).then(response => {
      //   this.couponList = response.rows || [];
      });
    },
    addRecordTimeRange() {
      this.watchRewardForm.recordTimeRanges.push({ range: null, rewardTypes: ['1'], redPacketAmount: '', scoreAmount: '', couponIds: [] })
    },
    removeRecordTimeRange(index) {
      this.watchRewardForm.recordTimeRanges.splice(index, 1)
      this.checkOverlap()
    },
    onTimeRangeChange(currentIndex) {
      const current = this.watchRewardForm.recordTimeRanges[currentIndex]
      if (!current || !current.range || current.range.length !== 2) {
        this.checkOverlap()
        return
      }
      const currentStart = this.timeToMinutes(current.range[0])
      const currentEnd = this.timeToMinutes(current.range[1])

      const others = this.watchRewardForm.recordTimeRanges
        .filter((item, i) => i !== currentIndex && item.range && item.range.length === 2)
        .map(item => ({
          start: this.timeToMinutes(item.range[0]),
          end: this.timeToMinutes(item.range[1])
        }))

      let overlap = false
      for (const other of others) {
        if (currentStart < other.end && other.start < currentEnd) {
          overlap = true
          break
        }
      }

      if (overlap) {
        this.$set(current, 'range', null)
        this.$message.error('时间重叠，请重新选择')
      }

      this.checkOverlap()
    },
    checkOverlap() {
      const ranges = this.watchRewardForm.recordTimeRanges
        .filter(item => item.range && item.range.length === 2)
        .map(item => ({
          start: this.timeToMinutes(item.range[0]),
          end: this.timeToMinutes(item.range[1])
        }))
      for (let i = 0; i < ranges.length; i++) {
        for (let j = i + 1; j < ranges.length; j++) {
          if (ranges[i].start < ranges[j].end && ranges[j].start < ranges[i].end) {
            this.timeRangeOverlap = true
            return
          }
        }
      }
      this.timeRangeOverlap = false
    },
    timeToMinutes(timeStr) {
      if (!timeStr) return 0
      const parts = timeStr.split(':')
      return parseInt(parts[0]) * 60 + parseInt(parts[1])
    },
    minutesToTime(minutes) {
      const h = Math.floor(minutes / 60).toString().padStart(2, '0')
      const m = (minutes % 60).toString().padStart(2, '0')
      return h + ':' + m
    },
    getLiveConfig(){
      getConfig(this.liveId).then(response => {
        if(response.code === 200 && response.data != null && response.data.length > 0){
          const serverData = JSON.parse(response.data)
          this.configCache = Object.assign({}, serverData)
          this.watchRewardForm = Object.assign({}, this.watchRewardForm, serverData)
          if (this.watchRewardForm.recordTimeRangeStr) {
            this.watchRewardForm.recordTimeRanges = this.watchRewardForm.recordTimeRangeStr.split(',').map(item => {
              const parts = item.split('-')
              return { range: [parts[0], parts[1]], rewardTypes: parts[2] ? parts[2].split('|') : ['1'], redPacketAmount: parts[3] || '', scoreAmount: parts[4] || '', couponIds: parts[5] ? parts[5].split('~').filter(Boolean).map(Number) : [] }
            })
          } else {
            this.watchRewardForm.recordTimeRanges = [{ range: null, rewardTypes: ['1'], redPacketAmount: '', scoreAmount: '', couponIds: [] }]
          }
          if(this.watchRewardForm.isRedPackageBalanceDeduction == null){
            this.watchRewardForm.isRedPackageBalanceDeduction = '1'
          } else {
            this.watchRewardForm.isRedPackageBalanceDeduction = String(this.watchRewardForm.isRedPackageBalanceDeduction)
          }
          if(this.watchRewardForm.answerAttempts == null){
            this.watchRewardForm.answerAttempts = 3
          }
          this.loadSelectedQuestions();
        } else {
          this.configCache = {}
        }
        this.loading = false
      })
    },
    // 合并提交：保留 config 中 playback* 等非本页字段
    buildWatchSubmitData() {
      const submitData = Object.assign({}, this.configCache, this.watchRewardForm)
      if (submitData.recordTimeRanges && submitData.recordTimeRanges.length > 0) {
        submitData.recordTimeRangeStr = submitData.recordTimeRanges
          .filter(item => item.range && item.range.length === 2)
          .map(item => item.range[0] + '-' + item.range[1] + '-' + (item.rewardTypes || []).join('|') + '-' + (item.redPacketAmount || '') + '-' + (item.scoreAmount || '') + '-' + (item.couponIds || []).join('~'))
          .join(',')
      } else {
        submitData.recordTimeRangeStr = ''
      }
      delete submitData.recordTimeRanges
      return submitData
    },
    // 自动保存开关状态
    autoSaveEnabled() {
      const submitData = this.buildWatchSubmitData()
      if (this.watchRewardForm.id == null) {
        addConfig(submitData, this.liveId).then(res => {
          if (res.code == 200) {
            this.msgSuccess("已关闭观看奖励");
            // 更新 id，下次修改时使用 update
            if (res.data && res.data.id) {
              this.watchRewardForm.id = res.data.id;
            }
            this.configCache = Object.assign({}, submitData)
          }
        }).catch(() => {
          // 如果保存失败，恢复开关状态
          this.watchRewardForm.enabled = true;
        });
      } else {
        updateConfig(submitData, this.liveId).then(response => {
          if (response.code == 200) {
            this.msgSuccess("已关闭观看奖励");
            this.configCache = Object.assign({}, submitData)
          }
        }).catch(() => {
          // 如果保存失败，恢复开关状态
          this.watchRewardForm.enabled = true;
        });
      }
    },
    saveWatchReward() {
      this.$refs["watchRewardForm"].validate(valid => {
        if (valid) {
          if (this.timeRangeOverlap) {
            this.$message.error('时间段之间存在重叠，请重新选择')
            return
          }
          // 录播奖励必填校验
          if (this.watchRewardForm.recordRedPacketEnabled) {
            for (let i = 0; i < this.watchRewardForm.recordTimeRanges.length; i++) {
              const item = this.watchRewardForm.recordTimeRanges[i]
              if (!item.range || item.range.length !== 2) {
                this.$message.error('请选择第' + (i + 1) + '个时间段')
                return
              }
              if (!item.rewardTypes || item.rewardTypes.length === 0) {
                this.$message.error('第' + (i + 1) + '个时间段请至少选择一个奖励类型')
                return
              }
              if (item.rewardTypes.includes('1') && !item.redPacketAmount) {
                this.$message.error('第' + (i + 1) + '个时间段选择了红包，请填写红包金额')
                return
              }
              if (item.rewardTypes.includes('2') && !item.scoreAmount) {
                this.$message.error('第' + (i + 1) + '个时间段选择了积分，请填写积分值')
                return
              }
              if (item.rewardTypes.includes('3') && (!item.couponIds || item.couponIds.length === 0)) {
                this.$message.error('第' + (i + 1) + '个时间段选择了核销卷，请选择核销卷')
                return
              }
            }
          }
          const submitData = this.buildWatchSubmitData()
          if (this.watchRewardForm.id == null) {
            addConfig(submitData,this.liveId).then(res => {
              if (res.code == 200) {
                this.msgSuccess("修改成功");
                this.configCache = Object.assign({}, submitData)
              }
            })
          } else {
            updateConfig(submitData,this.liveId).then(response => {
              this.msgSuccess("修改成功");
              this.configCache = Object.assign({}, submitData)
            });
          }
        }
      })
    },
    openQuestionDialog() {
      this.questionDialogVisible = true;
      this.questionSearchTitle = '';
      this.questionQueryParams.pageNum = 1;
      this.questionQueryParams.title = null;
      this.tempSelectedQuestions = [...this.selectedQuestionList];
      this.loadQuestionOptions();
    },
    loadQuestionOptions() {
      this.questionLoading = true;
      listCourseQuestionBank(this.questionQueryParams).then(response => {
        this.questionOptionList = response.rows || [];
        this.questionOptionTotal = response.total || 0;
        this.questionLoading = false;
      }).catch(() => {
        this.questionLoading = false;
      });
    },
    handleQuestionSearch() {
      this.questionQueryParams.pageNum = 1;
      this.questionQueryParams.title = this.questionSearchTitle;
      this.loadQuestionOptions();
    },
    isQuestionSelected(id) {
      return this.tempSelectedQuestions.some(item => item.id === id);
    },
    toggleQuestionCard(row) {
      const idx = this.tempSelectedQuestions.findIndex(item => item.id === row.id);
      if (idx > -1) {
        this.tempSelectedQuestions.splice(idx, 1);
      } else {
        this.tempSelectedQuestions.push(row);
      }
    },
    confirmQuestionSelection() {
      if (this.tempSelectedQuestions.length === 0) {
        this.$message.warning('请至少选择一题');
        return;
      }
      this.selectedQuestionList = [...this.tempSelectedQuestions];
      this.syncFinishQuestionIds();
      this.questionDialogVisible = false;
    },
    removeSelectedQuestion(row) {
      this.selectedQuestionList = this.selectedQuestionList.filter(item => item.id !== row.id);
      this.syncFinishQuestionIds();
    },
    syncFinishQuestionIds() {
      this.watchRewardForm.finishQuestionIds = this.selectedQuestionList.map(item => item.id).join(',');
    },
    loadSelectedQuestions() {
      if (!this.watchRewardForm.finishQuestionIds) {
        this.selectedQuestionList = [];
        return;
      }
      const ids = this.watchRewardForm.finishQuestionIds.split(',').filter(Boolean);
      if (ids.length === 0) {
        this.selectedQuestionList = [];
        return;
      }
      Promise.all(ids.map(id => getCourseQuestionBank(id))).then(results => {
        this.selectedQuestionList = results
          .filter(res => res.code === 200 && res.data)
          .map(res => res.data);
      });
    }
  }
};
</script>

<style scoped>
.watch-reward-page {
  min-height: 100%;
  padding-bottom: 40px;
}


/* 录播奖励配置项样式 */
.record-reward-item {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 10px;
  padding: 10px 0;
  border-top: 1px dashed #dcdfe6;
}
.record-reward-item:first-child {
  border-top: none;
  padding-top: 0;
}

/* 提示信息样式 */
.tip-message {
  padding: 12px 16px;
  background-color: #FFF6F2;
  border-radius: 4px;
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}


/* 开关容器样式 */
.reward-switch {
  margin-left: 200px;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

/* 开关标签样式 */
.reward-switch .switch-label {
  margin-right: 10px;
  font-size: 14px;
  color: #333;
  margin-left: 50px;
}

/* 表单区块样式 */
.section-block {
  width: 100%;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-left: 50px;
  margin-bottom: 20px;
}

/* 标题样式 */
.section-block .section-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 20px;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
  line-height: 1;
}

/* 表单样式 */
.reward-form {
  margin-top: 20px;
}

/* 表单项样式 */
.reward-form .el-form-item {
  margin-bottom: 22px;
  padding-left: 50px;
}

.reward-form .el-form-item:last-child {
  margin-bottom: 0;
}

/* 表单标签样式 */
.reward-form .el-form-item .el-form-item__label {
  color: #606266;
}

/* 输入框统一宽度 */
.reward-form .el-form-item .el-input {
  width: 300px;
}

/* 必填项星号样式 */
.reward-form .el-form-item.is-required .el-form-item__label:before {
  color: #F56C6C;
}

/* 观看时长输入框样式 */
.reward-form .el-form-item .duration-input {
  width: 300px;
}

.reward-form .el-form-item .duration-input .el-input__inner {
  text-align: left;
}

/* 保存按钮样式 */
.form-actions {
  width: 600px;
  text-align: center;
  margin-top: 30px;
}

.form-actions .el-button {
  padding: 8px 20px;
  font-size: 13px;
}

/* 题目卡片列表 */
.question-card-list {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 4px;
}
.question-card {
  display: flex;
  align-items: flex-start;
  padding: 14px 16px;
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.2s, background-color 0.2s;
}
.question-card:hover {
  border-color: #c0c4cc;
  background-color: #f5f7fa;
}
.question-card.is-selected {
  border-color: #409EFF;
  background-color: #ecf5ff;
}
.question-card-check {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  margin-right: 12px;
  margin-top: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.question-card-check-empty {
  width: 18px;
  height: 18px;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
}
.question-card-body {
  flex: 1;
  min-width: 0;
}
.question-card-title {
  font-size: 14px;
  color: #303133;
  line-height: 1.5;
  margin-bottom: 8px;
  word-break: break-all;
}
.question-card-answer {
  font-size: 12px;
  color: #67C23A;
  margin-bottom: 8px;
  word-break: break-all;
}
.question-card-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}
.question-card-creator {
  color: #909399;
}
.question-card-time {
  color: #909399;
  margin-left: auto;
}
.question-card-empty {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

/* 已选题目卡片列表 */
.selected-question-card-list {
  margin-bottom: 12px;
  max-width: 600px;
}
.selected-question-card {
  display: flex;
  align-items: flex-start;
  padding: 10px 14px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafbfc;
  transition: border-color 0.2s;
}
.selected-question-card:hover {
  border-color: #c0c4cc;
}
.selected-question-card-body {
  flex: 1;
  min-width: 0;
}
.selected-question-card-title {
  font-size: 14px;
  color: #303133;
  line-height: 1.5;
  margin-bottom: 6px;
  word-break: break-all;
}
.selected-question-card-answer {
  font-size: 12px;
  color: #67C23A;
  margin-bottom: 6px;
  word-break: break-all;
}
.selected-question-card-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}
.selected-question-card-creator {
  color: #909399;
}
.selected-question-card-time {
  color: #909399;
  margin-left: auto;
}
.selected-question-card-remove {
  flex-shrink: 0;
  color: #F56C6C !important;
  margin-left: 12px;
  padding: 0;
}
</style>
