<template>
  <div class="app-container">
    <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>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleGetEwm"
        >二维码</el-button>
      </el-col>
      <el-col>
        <img :src="ewmImg" style="width: 200px; height: 200px">
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="awwardTempList">
      <el-table-column label="抽奖id" prop="id" align="center" />
      <el-table-column label="抽奖名称" prop="name" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="抽奖描述" prop="desc" align="center" />
      <el-table-column label="人天 限制抽奖次数" prop="curtail" align="center" />
      <el-table-column label="领奖方式" prop="receiveType" align="center" />
      <el-table-column label="生效日期" align="center" prop="effectiveDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectiveDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效日期" align="center" prop="expiryDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expiryDate) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</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="1050px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" inline>
        <el-form-item label="抽奖名称" prop="drawActivity.name">
          <el-input v-model="form.drawActivity.name" placeholder="请输入抽奖名称" />
        </el-form-item>
        <el-form-item label="抽奖描述" prop="drawActivity.desc">
          <el-input v-model="form.drawActivity.desc" placeholder="请输入抽奖描述" />
        </el-form-item>
        <el-form-item label="抽奖次数" prop="drawActivity.curtail">
          <el-input v-model="form.drawActivity.curtail" type="number" placeholder="请输入人天 限制抽奖次数" />
        </el-form-item>
        <el-form-item label="领奖方式" prop="drawActivity.receiveType">
          <el-input v-model="form.drawActivity.receiveType" placeholder="请输入领奖方式" />
        </el-form-item>
        <el-form-item label="生效日期" prop="drawActivity.effectiveDate">
          <el-date-picker
            v-model="form.drawActivity.effectiveDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="生效日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效日期" prop="drawActivity.expiryDate">
          <el-date-picker
            v-model="form.drawActivity.expiryDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="失效日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="抽奖模板" prop="drawActivity.templateId">
          <el-select
            v-model="form.drawActivity.templateId"
            filterable
            clearable
            placeholder="请选择抽奖模板"
            @change="handleCheckTemplate">
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.templateName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配置奖品">
          <el-button type="primary" @click="awardOptionList">添加奖品配置</el-button>
        </el-form-item>
        <el-row v-for="(item, index) in form.awardProbabilityList" :key="index">
          <el-col :span="8">
            <el-form-item label="奖品名称" prop="awardProbabilityList.awardId">
              <el-select
                v-model="item.awardId"
                filterable
                placeholder="请选择奖品">
                <el-option
                  v-for="item in awardList"
                  :key="item.id"
                  :label="item.awardName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="奖品位置" prop="awardProbabilityList.pos">
              <el-input v-model="item.pos" placeholder="请输入奖品位置" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="奖品概率" prop="awardProbabilityList.probability">
              <el-input v-model="item.probability" type="number" :placeholder="'请输入奖品概率 0 ~ ' + allProbability"/>
            </el-form-item>
          </el-col>
        </el-row>
        <p v-show="form.drawActivity.templateId" style="text-align: center;">当前{{ this.awardOptionNum - form.awardProbabilityList.length }}个奖品为谢谢参与，概率为{{ allProbability }}</p>
      </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>
  </div>
</template>

<script>
import {
  getDrawActivityList,
  addDrawActivity,
  getDrawTemplateList,
  awardList,
  delDrawActivity,
  getQrCode
} from "@/api/award/awardList"

import imageUpload from "../../components/ImageUpload/index.vue";

export default {
  name: "Role",
  components: {
    imageUpload
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/',
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      total: 0,
      awwardTempList: [],
      title: "",
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        drawActivity: {},
        awardProbabilityList: [],
      },
      // 表单校验
      rules: {
        'drawActivity.name': [
          { required: true, message: "抽奖活动名称不能为空", trigger: "blur" }
        ],
        'drawActivity.desc': [
          { required: true, message: "抽奖活动描述不能为空", trigger: "blur" }
        ],
        'drawActivity.curtail': [
          { required: true, message: "人天限制抽奖次数不能为空", trigger: "blur" }
        ],
        'drawActivity.templateId': [
          { required: true, message: "抽奖模板不能为空", trigger: "blur" }
        ],
        // 'awardProbabilityList.awardId': [
        //   { required: true, message: "奖品名称不能为空", trigger: "blur" }
        // ],
        // 'awardProbabilityList.pos': [
        //   { required: true, message: "奖品位置不能为空", trigger: "blur" }
        // ],
        // 'awardProbabilityList.probability': [
        //   { required: true, message: "奖品概率不能为空", trigger: "blur" }
        // ],
      },
      templateList: [],
      awardList: [],
      awardOptionNum: 0, // 奖品数量
      ewmImg: '',
    };
  },
  created() {
    this.getList();
    getDrawTemplateList({pageNum: 1, pageSize: 100}).then((res) => {
      this.templateList = res.data.records
    })
    awardList({pageNum: 1, pageSize: 100}).then((res) => {
      this.awardList = res.data.records
    })
  },
  computed: {
    allProbability() {
      let num = 0
      this.form.awardProbabilityList.forEach((val) => {
        num += Number(val.probability)
      })
      if (num <= 100) {
        return 100 - num
      } else {
        return '超出范围'
      }
    },
  },
  methods: {
    // 添加奖品配置项
    awardOptionList() {
      if (!this.form.drawActivity.templateId) {
        this.$message.warning('请选择抽奖模板')
        return
      }
      if(this.form.awardProbabilityList.length < this.awardOptionNum) {
        this.form.awardProbabilityList.push({
          awardId: '',
          pos: this.form.awardProbabilityList.length + 1,
          probability: ''
        })
      } else {
        this.$message.warning('最多只能配置' + this.awardOptionNum + '个奖品')
      }
    },
    // 更改模板
    handleCheckTemplate(data) {
      this.form.awardProbabilityList = []
      this.templateList.forEach((val) => {
        if (val.id == data) {
          this.awardOptionNum = val.templateDrawNumber
        }
      })
    },
    getPhotoUrl(data) {
      this.form.templateDemoImg = data
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getDrawActivityList(this.queryParams).then((res) => {
        this.queryParams.pageNum = res.data.current
        this.total = res.data.total
        this.awwardTempList = res.data.records
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.form = {
        drawActivity: {},
        awardProbabilityList: [],
      }
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        drawActivity: {},
        awardProbabilityList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 二维码
    handleGetEwm() {
      getQrCode({
        userId: '1',
        activityId: '1816742797954846720'
      }).then((res) => {
        let result = res.replace(/[\r\n]/g, "");
        this.ewmImg = `data:image/png;base64,${result}`;
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = row
      this.open = true
      this.title = "编辑";
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          for (let i = 0; i < this.form.awardProbabilityList.length; i++) {
            const element = this.form.awardProbabilityList[i];
            if (!element.probability) {
              this.$message.warning('请输入奖品概率')
              return
            }
          }
          if (!this.form.id) {
            addDrawActivity(this.form).then(res => {
              if(res.code == 200) {
                this.$modal.msgSuccess("添加成功");
                this.open = false;
                this.getList();
              } else {
                this.$message.error(res.msg)
              }
            });
          } else {
            // updateDrawTemplate(this.form).then(response => {
            //   this.$modal.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const awardName = row.name
      this.$confirm('是否确认名称为"' + awardName + '"的抽奖活动？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delDrawActivity({id: row.id}).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        });
    },
  }
};
</script>
<style lang="scss" scoped>
.el-form {
  .el-select, .el-input {
    width: 200px;
  }
}
</style>