<template>
  <div class="app-container">
    <el-dialog title="调整奖品" :close-on-click-modal="false" :visible.sync="open" width="1000px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="prizeOnlineList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="奖品类型" align="center" prop="prizeType" >
          <template v-slot="scope">
            <cai-dict-tag :options="prizeTypeList" :value="scope.row.prizeType" />
          </template>
        </el-table-column>
        <el-table-column label="奖品名称" align="center" prop="prizeName" />
        <el-table-column label="奖品描述" align="center" prop="prizeDesc" />
        <el-table-column label="奖品图片" align="center" prop="prizeImg" >
          <template v-slot="scope">
            <image-avatar :src="scope.row.prizeImg"/>
          </template>
        </el-table-column>
        <el-table-column label="中奖率" align="center" prop="winProbability" />
        <el-table-column label="保底抽数" align="center" prop="guaranteeDraws" />
        <el-table-column label="最低抽数" align="center" prop="minWinDraws" />
        <el-table-column label="奖品价值" align="center" prop="prizePrice" />
        <el-table-column label="自动兑奖" align="center" prop="autoGive" >
          <template v-slot="scope">
            <cai-dict-tag :options="prizeAutoGiveList" :value="scope.row.autoGive" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                v-if="scope.row.prizeId != 1"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['cai:prizeInfo:edit']"
            >修改</el-button>
            <el-button
                v-if="scope.row.prizeId != 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['cai:prizeInfo:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增奖品" :close-on-click-modal="false" :visible.sync="addOpen" width="700px" append-to-body>
      <el-form ref="addForm" :model="addForm" label-width="80px" >
        <el-form-item label="奖品模板" prop="prizeInfoTemplate">
          <el-select v-model="addForm.prizeInfoTemplate" size="small">
            <el-option
                v-for="dict in prizeInfoSelectList"
                :key="dict.id"
                :label="dict.prizeName"
                :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="addSubmitForm">确 定</el-button>
        <el-button @click="addOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改奖品" :close-on-click-modal="false" :visible.sync="updateOpen" width="700px" append-to-body>
      <el-form ref="updateForm" :model="updateForm" :rules="updateRules" label-width="80px">
        <el-form-item label="奖品类型" prop="prizeType">
          <el-select v-model="updateForm.prizeType" size="small">
            <el-option
                v-for="dict in prizeTypeList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="奖品名称" prop="prizeName">
          <el-input v-model="updateForm.prizeName" placeholder="请输入奖品名称" />
        </el-form-item>
        <el-form-item label="奖品描述" prop="prizeDesc">
          <el-input v-model="updateForm.prizeDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="奖品图片" prop="prizeImg">
          <image-upload2 v-model="updateForm.prizeImg"/>
        </el-form-item>
        <el-form-item label="中奖率" prop="winProbability">
          <el-input-number v-model="updateForm.winProbability" placeholder="请输入中奖率" min="0" max="1" />
        </el-form-item>
        <el-form-item label="保底抽数" prop="guaranteeDraws" v-if="updateForm.prizeType == 3">
          <el-input v-model="updateForm.guaranteeDraws" placeholder="请输入保底抽数" />
        </el-form-item>
        <el-form-item label="最低中奖抽数" prop="minWinDraws" v-if="updateForm.prizeType == 3" >
          <el-input v-model="updateForm.minWinDraws" placeholder="请输入最低中奖抽数" />
        </el-form-item>
        <el-form-item label="奖品价值" prop="prizePrice">
          <el-input v-model="updateForm.prizePrice" placeholder="请输入奖品价值估算" />
        </el-form-item>
        <el-form-item label="自动兑奖" prop="autoGive">
          <el-select v-model="updateForm.autoGive" size="small">
            <el-option
                v-for="dict in prizeAutoGiveList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
<!--        <el-button :loading="buttonLoading" type="primary" @click="updateSubmitForm">确 定</el-button>-->
        <el-button @click="updateOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listPrizeOnline, resetPrizeOnline} from "@/api/cai/prizeOnline";
import {prizeAutoGiveList, prizeTypeList} from "@/constant/statusMap";
import {prizeInfoAll} from "@/api/cai/prizeInfo";

export default {
  props: {
    gender: {
      type: Number,       // 参数类型
      required: true     // 是否必传
    },
  },
  name: "PrizeOnline",
  data() {
    return {
      prizeTypeList, prizeAutoGiveList,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 已发布奖品表格数据
      prizeOnlineList: [],
      // 查询参数
      queryParams: {
        gender: this.gender
      },
      open: false,
      // add
      addOpen: false,
      addForm:{
        prizeInfoTemplate: undefined
      },
      prizeInfoSelectList: [],
      // update
      updateOpen: false,
      updateForm: {},
      updateRules: {
        prizeName: [
          { required: true, message: "奖品名称不能为空", trigger: "blur" }
        ],
        prizeDesc: [
          { required: true, message: "奖品描述不能为空", trigger: "blur" }
        ],
        prizeImg: [
          { required: true, message: "奖品图片不能为空", trigger: "blur" }
        ],
        winProbability: [
          { required: true, message: "中奖率不能为空", trigger: "blur" }
        ],
        guaranteeDraws: [
          { required: true, message: "保底抽数不能为空", trigger: "blur" }
        ],
        minWinDraws: [
          { required: true, message: "中奖抽数不能为空", trigger: "blur" }
        ],
        prizeType: [
          { required: true, message: "奖品类型不能为空", trigger: "change" }
        ],
        prizePrice: [
          { required: true, message: "奖品价值不能为空", trigger: "blur" }
        ],
        autoGive: [
          { required: true, message: "自动兑奖不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {

  },
  methods: {
    init (id) {
      this.open = true;
      this.$nextTick(() => {
        this.getList();
      })
    },
    /** 查询已发布奖品列表 */
    getList() {
      this.loading = true;
      listPrizeOnline(this.queryParams).then(response => {
        this.prizeOnlineList = response.data;
        this.prizeOnlineList.forEach(item => {
          item.uuid = item.id;
        })
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addOpen = true;
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields();
        this.refreshPrizeInfoAll();
      })
    },
    handleUpdate(row){
      this.updateOpen = true;
      this.$nextTick(() => {
        this.updateForm = row;
      })
    },
    handleDelete(row){
      // 找到目标项的索引
      const index = this.prizeOnlineList.findIndex(item => item.uuid === row.uuid);
      // 只有找到索引（index !== -1）时才执行删除
      if (index !== -1) {
        // splice(起始索引, 删除数量)，返回被删除的项
        return this.prizeOnlineList.splice(index, 1);
      }
    },
    refreshPrizeInfoAll(){
      prizeInfoAll().then(response => {
        this.prizeInfoSelectList = response.data;
      })
    },
    addSubmitForm(){
      let find = this.prizeInfoSelectList.find(item => item.id === this.addForm.prizeInfoTemplate);
      if(find){
        const newObj = Object.assign({}, find);
        newObj.uuid = this.generateUUID()
        newObj.prizeId = newObj.id
        newObj.id = undefined
        this.prizeOnlineList.push(newObj);
      }
    },
    submitForm() {
      resetPrizeOnline(this.gender,this.prizeOnlineList).then(response => {
        this.$modal.msgSuccess("调整成功");
        this.$modal.buttonLoading = false;
        this.open = false
        this.$emit('refreshDataList')
      }).finally(() => {
        this.buttonLoading = false;
      })
    },
    generateUUID() {
      // UUID v4 的格式为：xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
      // 其中 4 是版本号固定位，y 只能是 8/9/a/b 中的一个
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0; // 生成 0-15 的随机数
        const v = c === 'x' ? r : (r & 0x3 | 0x8); // 处理 y 位的规则
        return v.toString(16); // 转换为 16 进制字符串
      });
    },
  }
};
</script>
