<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="直播间ID" prop="liveId">
        <el-input
          v-model="queryParams.liveId"
          placeholder="请输入直播间ID"
          clearable
          size="small"
          :disabled="canLiveId"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参与方式" prop="require">
        <el-select v-model="queryParams.require" placeholder="请输入参与抽奖方式">
          <el-option v-for="(item,index) in requireOptions" :key="item.dictValue+index" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="抽奖状态" prop="require">
        <el-select v-model="queryParams.lottery_status" placeholder="请输入参与抽奖方式">
          <el-option v-for="(item,index) in lotteryStatusOptions" :key="item.dictValue+index" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="抽奖标题" prop="desc">
        <el-input
          v-model="queryParams.desc"
          placeholder="请输入描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['live:liveLotteryConf:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['live:liveLotteryConf:edit']"
        >修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['live:liveLotteryConf:remove']"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['live:liveLotteryConf:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="liveLotteryConfList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="抽奖ID" align="center" prop="lotteryId" />
      <el-table-column label="操作商品" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.lotteryStatus+'' === '0'" @click="handleUpdateProduct(scope.row)">编辑商品</el-button>
          <el-button v-else @click="handleDetailProduct(scope.row)">查看商品</el-button>
        </template>
      </el-table-column>
      <el-table-column label="直播间ID" align="center" prop="liveId" />
      <el-table-column label="参与方式" align="center" prop="require" :formatter="requireFormatter"/>
      <el-table-column label="抽奖状态" align="center" prop="lotteryStatus" :formatter="lotteryStatusFormatter"/>
      <el-table-column label="配置" align="center" prop="requireConf" />
      <el-table-column label="持续时间" align="center" prop="duration" />
      <el-table-column label="抽奖标题" align="center" prop="desc" />
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['live:liveLotteryConf:edit']"
            style="margin-left: 10px"
          >修改</el-button>
          <!-- 开始 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleStatusChange(scope.row,'1')"
            v-hasPermi="['live:liveLotteryConf:edit']"
          >开始</el-button>
          <!-- 暂停 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleStatusChange(scope.row,'3')"
            v-hasPermi="['live:liveLotteryConf:edit']"
          >暂停</el-button>
          <!-- 结算 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleStatusChange(scope.row,'2')"
            v-hasPermi="['live:liveLotteryConf:edit']"
          >结算</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['live:liveLotteryConf:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改直播抽奖配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="直播间ID" prop="liveId">
          <el-input v-model="form.liveId" placeholder="请输入直播间ID"
                    :disabled="canLiveId"/>
        </el-form-item>
        <el-form-item label="参与方式" prop="require">
          <el-select v-model="form.require" placeholder="请输入参与抽奖方式">
            <el-option v-for="(item,index) in requireOptions" :key="item.dictValue+index" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="方式配置" prop="requireConf">
          <el-input v-model="form.requireConf" placeholder="请输入参与抽奖方式" />
          <span style="font-size: 10px; font-family: Arial,serif">当参与方式选择为“送礼参与”或“下单参与”时，此处填写商品ID及数量</span>
        </el-form-item>
        <el-form-item label="持续时间" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入持续时间 单位：分" />
        </el-form-item>
        <el-form-item label="抽奖标题" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="titleProduct" :visible.sync="openProduct" width="800px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="100px" :disabled="isDetail">
        <!-- 基础信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="抽奖ID" prop="lotteryId">
              <el-input v-model="form1.lotteryId" placeholder="请输入抽奖ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
<!--            <el-form-item label="直播间ID" prop="liveId">
              <el-input v-model="form1.liveId" placeholder="请输入直播间ID" />
            </el-form-item>-->
          </el-col>
        </el-row>

        <!-- 动态奖品配置 -->
        <el-divider content-position="left">奖品配置</el-divider>

        <el-card v-for="(prize, index) in form1.prizes" :key="index" class="prize-card" shadow="hover">
          <div slot="header" class="prize-header">
            <span><b>奖品等级 :{{ prize.prizeLevel }}</b></span>
            <el-button
              v-if="form1.prizes.length > 1"
              @click="removePrize(index)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
            ></el-button>
          </div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="商品ID"
                :prop="'prizes.' + index + '.productId'"
                :rules="[{ required: true, message: '请输入商品', trigger: 'blur' }]">
<!--                <el-input v-model="prize.productId" placeholder="请输入商品ID" />-->
                <el-select
                  v-model="prize.productId"
                  filterable
                  clearable
                  remote
                reserve-keyword
                placeholder="请输入关键字搜索"
                :remote-method="fetchProducts"
                :loading="loadingProducts"
                size="small"
                style="width: 180px"
                >
                <el-option
                  v-for="product in productOptions"
                  :key="product.goodsId"
                  :label="product.productName"
                  :value="product.goodsId"
                />
                <span style="float: left">{{ product.goodsId }}</span>
                <span style="margin-left: 30px ;">{{product.productName}}</span>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="奖品等级"
                :prop="'prizes.' + index + '.prizeLevel'"
                :rules="[{ required: true, message: '请输入奖品等级', trigger: 'blur' }]">
                <el-input v-model="prize.prizeLevel" placeholder="请输入奖品等级" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="单奖数量"
                :prop="'prizes.' + index + '.perLotteryNum'"
                :rules="[
                { required: true, message: '请输入单次中奖数量', trigger: 'blur' },
                { type: 'number', message: '必须为数字值' }
              ]">
                <el-input-number
                  v-model="prize.perLotteryNum"
                  :min="1"
                  :max="100"
                  controls-position="right"
                  placeholder="单次中奖数量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="奖励总份数"
                :prop="'prizes.' + index + '.totalLots'"
                :rules="[
                { required: true, message: '请输入奖励总份数', trigger: 'blur' },
                { type: 'number', message: '必须为数字值' }
              ]">
                <el-input-number
                  v-model="prize.totalLots"
                  :min="1"
                  controls-position="right"
                  placeholder="奖励总份数" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="实发份数"
                :prop="'prizes.' + index + '.totalSend'"
                >
                <el-input-number
                  v-model="prize.totalSend"
                  :min="0"
                  :max="prize.totalLots"
                  controls-position="right"
                  placeholder="实际发放份数"
                  :disabled="true"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <div class="add-prize-btn">
          <el-button
            @click="addPrize"
            type="primary"
            icon="el-icon-plus"
            plain
            size="small">
            添加奖品配置
          </el-button>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel1">取 消</el-button>
        <el-button type="primary" @click="submitForm1">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLiveLotteryConf, getLiveLotteryConf, delLiveLotteryConf, addLiveLotteryConf, updateLiveLotteryConf, exportLiveLotteryConf } from "@/api/live/liveLotteryConf";
import LiveLotteryProductConf from '@/views/live/liveLotteryProductConf/index.vue'
import {
  listStoreProduct,
  updateLiveLotteryProductConf
} from '@/api/live/liveLotteryProductConf'
import { listLiveGoods } from '@/api/live/liveGoods'

export default {
  name: "LiveLotteryConf",
  components: { LiveLotteryProductConf },
  data() {
    return {
      //字典
      requireOptions: [],
      // 抽奖状态
      lotteryStatusOptions: [],
      //加载商品
      loadingProducts: false,
      //
      productOptions: [],
      isDetail: false,
      canLiveId:false,
      //parentLiveId
      parentLiveId : null,
      liveId: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 直播抽奖配置表格数据
      liveLotteryConfList: [],
      // 弹出层标题
      title: "",
      titleProduct: "编辑抽奖商品",
      // 是否显示弹出层
      open: false,
      openProduct: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: null,
        require: null,
        desc: null,
        createTime: null,
        lottery_status: null
      },
      //商品信息列表
      productList: [],
      // 商品信息
      product: {
        productId: null,
        prizeLevel: null,
        perLotteryNum: null,
        totalLots: null,
        totalSend: null
      },
      // 表单参数
      form:{
        lotteryId: '',
        liveId: '',
        require: '',
        requireConf: '',
        duration: null,
        desc: null
      },
      // 表单参数
      form1: {
        liveId: '',
        lotteryId: '',
        prizes: [this.getDefaultPrize()]
      },
      // 表单校验
      rules: {
        liveId: [
          { required: true, message: "直播间ID不能为空", trigger: "blur" }
        ],
        require: [
          { required: true, message: "参与抽奖方式", trigger: "blur" }
        ],
        //如果require为2或3，requireConf不能为空
        requireConf: [
          { validator: this.validRequireConf,message: "当参与方式选择为“送礼参与”或“下单参与”时，对应的配置:送礼数量/指定商品Id及数量不能为空", trigger: "blur" }
        ],
        duration: [
          { required: true, message: "持续时间 单位：分不能为空", trigger: "blur" }
        ],
        desc: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
      },
      //抽奖商品表单
      rules1: {
        lotteryId: [
          { required: true, message: '请输入抽奖ID', trigger: 'blur' }
        ],
        liveId: [
          { required: true, message: '请输入直播间ID', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getDicts("sys_live_lottery_require").then(response => {
      this.requireOptions = response.data;
    });
    this.getDicts("sys_live_lottery_status").then(response => {
      this.lotteryStatusOptions = response.data;
    });
    this.liveId = this.$route.query.liveId;
    this.parentLiveId = this.liveId;
    this.queryParams.liveId = this.parentLiveId;
    if(this.queryParams.liveId){
      this.form.liveId = this.parentLiveId;
      //设置查询条件直播间ID不可修改
      this.canLiveId = true;
    }
    this.getList();
  },
  mounted() {
    this.$watch(
      () => this.form.require,
      (newVal) => {
        this.$refs.form.validateField('requireConf');
      }
    );
  },
  methods: {
    async fetchProducts(query) {
      if (!query) {
        this.productOptions = [];
        return;
      }
      const queryParam = {
        liveId : this.liveId,
        keywords: query
      }
      this.loadingProducts = true;
      try {
        listLiveGoods(queryParam).then(response => {
          this.productOptions = response.rows;
        })
      } catch (err) {
        console.error('查询商品失败:', err);
        this.productOptions = [];
      } finally {
        this.loadingProducts = false;
      }
    },
    // 获取默认奖品配置
    getDefaultPrize() {
      return {
        productId: '',
        prizeLevel: '',
        perLotteryNum: 1,
        totalLots: 1,
        totalSend: 0
      }
    },
    // 添加奖品配置
    addPrize() {
      this.form1.prizes.push(this.getDefaultPrize())
    },

    // 删除奖品配置
    removePrize(index) {
      if (this.form1.prizes.length <= 1) {
        this.$message.warning('至少需要保留一个奖品配置')
        return
      }
      this.form1.prizes.splice(index, 1)
    },

    requireFormatter(row, column) {
      return this.selectDictLabel(this.requireOptions, row.require);
    },
    lotteryStatusFormatter(row, column) {
      return this.selectDictLabel(this.lotteryStatusOptions, row.lotteryStatus);
    },
    validRequireConf(rule, value, callback) {
      if(this.form.require+"" === "2" || this.form.require+"" === "3"){
        if(!value){
          callback(new Error());
          return false;
        }
      }
      callback();
      return true;
    },
    /** 查询直播抽奖配置列表 */
    getList() {
      this.loading = true;
      listLiveLotteryConf(this.queryParams).then(response => {
        this.liveLotteryConfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消
    cancel1() {
      this.openProduct = false;
    },

    // 重置表单
    resetForm1() {
      this.form1 = {
        lotteryId: '',
        liveId: '',
        prizes: [this.getDefaultPrize()]
      }
    },
    // 表单重置
    reset() {
      this.form = {
        lotteryId: null,
        liveId: null,
        require: null,
        requireConf: null,
        duration: null,
        desc: null
      };
      this.resetForm("form");
      this.checkParentLiveId();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.checkParentLiveId();
      this.handleQuery();
    },
    //判断父页面传入参数
    checkParentLiveId(){
      if(this.parentLiveId){
        this.form.liveId = this.parentLiveId;
        this.queryParams.liveId = this.parentLiveId;
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lotteryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加直播抽奖配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lotteryId = row.lotteryId || this.ids
      //只能对未开始或暂停的抽奖进行修改
      if(row.lotteryStatus+"" !== "0" && row.lotteryStatus+"" !== "3"){
        this.msgError("只能对未开始或暂停的抽奖进行修改");
        return;
      }
      getLiveLotteryConf(lotteryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改直播抽奖配置";
      });
    },
    /** 修改按钮操作 */
    handleUpdateProduct(row) {
      this.form1.lotteryId = row.lotteryId;
      //如果状态为已结束，则不能修改
      if(row.lotteryStatus+"" === "2"){
        this.msgError("已结束的抽奖不能修改");
        return;
      }
      this.openProduct = true;
      this.isDetail = false;
      listStoreProduct(row.lotteryId).then(response => {
        this.form1 = response.data;
        if(this.form1.prizes.length === 0)
          this.form1.prizes = [this.getDefaultPrize()]
        this.form1.liveId = row.liveId;
      });
    },
    /** 详情按钮操作 */
    handleDetailProduct(row) {
      this.form1.lotteryId = row.lotteryId;
      //如果状态为已结束，则不能修改
      if(row.status+"" === "2"){
        this.msgError("已结束的抽奖不能修改");
        return;
      }
      this.openProduct = true;
      this.isDetail = true;
      listStoreProduct(row.lotteryId).then(response => {
        this.form1 = response.data;
        this.form1.liveId = row.liveId;
      });
    },
    /** 抽奖状态修改 */
    handleStatusChange(row, status) {
      //结束的抽奖不能进行操作
      if(row.lotteryStatus+"" === "2"){
        this.msgError("已结束的抽奖不能进行操作");
        return;
      }
      switch (status+"") {
        case "1":
          //只能对未开启的抽奖进行操作
          if(row.lotteryStatus+"" !== "0" && row.lotteryStatus+"" !== "3"){
            this.msgError("只能对未开启或暂停的抽奖进行开始操作");
            return;
          }
          break;
        case "2":
          //只能对进行中或暂停的抽奖进行结算
          if(row.lotteryStatus+"" !== "1" && row.lotteryStatus+"" !== "3"){
            this.msgError("只能对进行中或暂停的抽奖进行结算");
            return;
          }
          break;
        case "3":
          //只能对进行中的抽奖执行暂停操作
          if(row.lotteryStatus+"" !== "1"){
            this.msgError("只能对进行中的抽奖执行暂停操作");
            return;
          }
          break;
        default:
          return;
      }
      const doLotteryParam = {
        lotteryId: row.lotteryId,
        lotteryStatus: status
      };
      updateLiveLotteryConf(doLotteryParam).then(response => {
        if(response.code === 200){
          this.$store.state.liveWs[this.liveId].sendWs("lottery",response.msg, row.lotteryId,this.liveId);
          this.getList();
          this.msgSuccess("修改成功");
        }else{
          this.msgError(response.msg);
        }
          this.open = false;
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lotteryId != null) {
            updateLiveLotteryConf(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLiveLotteryConf(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitForm1() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          updateLiveLotteryProductConf(this.form1).then(response => {
            //200 成功
            this.msgSuccess("保存成功");
            this.openProduct = false;
            this.resetForm1();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      //如果抽奖状态不为0，则不能删除
      if(row.lotteryStatus+"" !== "0"){
        this.msgError("只能删除未开始的抽奖配置");
        return;
      }
      const lotteryIds = row.lotteryId || this.ids;
      this.$confirm('是否确认删除直播抽奖配置编号为"' + lotteryIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLiveLotteryConf(lotteryIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有直播抽奖配置数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportLiveLotteryConf(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.prize-card {
  margin-bottom: 20px;
}

.prize-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-prize-btn {
  margin-top: 10px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

</style>
