<template>
  <el-form ref="form" :model="form" label-width="100px" :rules="rules"  v-loading="loading" element-loading-text="拼命加载中" >
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">游戏内容</h3>
      <el-form-item label="游戏名称" class="width50" prop="gameName">
        <dm-input v-model="form.gameName" class="w400" :disabled="infoFlag" :maxlength="25"></dm-input>
      </el-form-item>
      <el-form-item label="游戏时间" class="width50" prop="dateTime">
        <el-date-picker class="w400"
          v-model="form.dateTime" :disabled="infoFlag" :default-time="['00:00:00', '23:59:59']"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="皮肤设置">
          <el-radio v-model="form.skinType" :label="0" :disabled="infoFlag">自定义</el-radio>
          <el-radio v-model="form.skinType" :label="1" :disabled="infoFlag">黑金</el-radio>
          <el-radio v-model="form.skinType" :label="2" :disabled="infoFlag">红色</el-radio>
          <el-radio v-model="form.skinType" :label="3" :disabled="infoFlag">霓虹灯</el-radio>
      </el-form-item>
      <el-form-item label="banner图片" class="width50" prop="gameImage">
        <dm-upload-avatar v-if="form.skinType === 0" :model.sync="form.gameImage" :disabled="infoFlag" width="220" height="103" label="上传图片" tips="图片建议尺寸：750*350"></dm-upload-avatar>
          <img class="skin-box" v-if="form.skinType===1" src="../../../assets/img/2.1.jpg" alt="" srcset="">
          <img class="skin-box" v-if="form.skinType===2" src="../../../assets/img/2.2.jpg" alt="" srcset="">
          <img class="skin-box" v-if="form.skinType===3" src="../../../assets/img/2.3.jpg" alt="" srcset="">
      </el-form-item>
      <el-form-item label="背景颜色" prop="background" class="width50" v-if="form.skinType === 0">
        <el-color-picker class="vertical-middle" :disabled="infoFlag" v-model="form.background"></el-color-picker>
        {{form.background}}
      </el-form-item>
      <el-form-item label="游戏说明" class="width50" prop="gameIntroduction">
        <dm-input type="textarea" class="w400" :rows="4" v-model="form.gameIntroduction" :disabled="infoFlag" :maxlength="200"></dm-input>
      </el-form-item>
    </section>
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">抽奖机制</h3>
      <el-form-item label="抽奖消耗" class="width50" prop="gameIntegral">
        <el-input-number controls-position="right" class="w400" :min="0" v-model="form.gameIntegral" :precision="0" :disabled="infoFlag"></el-input-number> 积分
        <p class="fz12 gray">0表示免费抽奖</p>
      </el-form-item>
      <el-form-item label="中奖几率" class="width50" prop="gameWinningRate">
        <el-input-number controls-position="right" class="w400" :min="0" :max="100" :precision="2" v-model="form.gameWinningRate" :disabled="infoFlag"></el-input-number> %
      </el-form-item>
      <el-form-item label="限制抽奖" class="width50" prop="gameLimitDay">
        <el-input-number controls-position="right" :min="0" class="w400" v-model="form.gameLimitCount" :precision="0" :disabled="infoFlag"></el-input-number> 次
        <p class="fz12 gray">
        <el-checkbox class="pl10" v-model="form.gameLimitDay" :disabled="infoFlag" :true-label="1" :false-label="0">每天</el-checkbox>
          不填表示限制抽奖次数</p>
      </el-form-item>
      <el-form-item label="免费抽奖" class="width50" prop="gameFreeDay">
        <el-input-number controls-position="right" :min="0" class="w400" v-model="form.gameFreeCount" :precision="0" :disabled="infoFlag"></el-input-number> 次
        <p class="fz12 gray">
        <el-checkbox class="pl10" v-model="form.gameFreeDay" :disabled="infoFlag" :true-label="1" :false-label="0">每天</el-checkbox>
          0表示无免费抽奖次数</p>
      </el-form-item>
      <el-form-item label="奖品设置" class="el-form-item__margin-top14">
        <el-table tooltipEffect="light" :data="tableList" style="width: 100%">
          <el-table-column prop="awardName" label="序号" align="left" width="90">
            <template slot-scope="scope">
            {{scope.$index+1}}
            </template>
          </el-table-column>
          <el-table-column prop="prizeType" label="奖品类型" align="left" :min-width="150">
            <template slot-scope="scope">
              <el-select size="small" v-model="scope.row.prizeType" class="width50" placeholder="选择奖品类型" :disabled="infoFlag" @change="resetCount(scope.$index)">
                <el-option v-for="item in prizeReferTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="ranprizeIntegralkEnd" label="奖项设置" align="left" :min-width="160">
            <template slot-scope="scope">
                <div v-if="scope.row.prizeType === 1"><el-input-number controls-position="right" v-model="scope.row.prizeIntegral" :disabled="infoFlag" :min="0" class="width50" size="small"></el-input-number> 积分</div>
                <el-button v-if="scope.row.prizeType === 2" size="small" :disabled="infoFlag" @click="setPrizeCard(scope.$index)">{{scope.row.cardName || '选择卡券'}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prizeQuantity" label="商品数量" align="left" :min-width="160">
            <template slot-scope="scope" v-if="scope.row.prizeType !== 3">
              <el-input-number controls-position="right" v-model="scope.row.prizeCount" type="number" :min="0" :disabled="infoFlag" class="width50" size="small"></el-input-number> 件
            </template>
          </el-table-column>
          <el-table-column prop="date"  :render-header="labelTips" align="left" width="100">
            <template slot-scope="scope" v-if="scope.row.prizeType !== 3">
            {{(totalCount*scope.row.prizeCount || 0).toFixed(2)}}%
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" align="left" width="80">
            <template slot-scope="scope">
            <el-button v-if="scope.$index !== 0" type="text" @click="delPrize(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="dm-button--add" @click="addPrize">
          <i class="el-icon-plus">新增奖项</i>
        </div>
      </el-form-item>
    </section>
   <div class="btn-wrap_fixed" :class="{'on':asideShow}">
      <el-button type="primary" @click="saveLottery('form')" v-if="!infoFlag">保 存</el-button>
      <el-button @click="$router.go(-1)">返 回</el-button>
    </div>
    <vue-gic-card :showCardDialog="showCardDialog" @selectCard="selectCard" :cardLimit="3" :cardType="null"></vue-gic-card>
  </el-form>
</template>

<script>
import {detailLottery,saveLottery} from '@/service/api/gameApi.js';
import {numberToChinese,formateDateTimeByType} from '@/utils/index.js';
import dmUploadAvatar from '@/components/upload/avatar';
import nonnegative from '@/mixins/nonnegative.js'
let result = {};
export default {
  mixins:[nonnegative],
  data () {
    return {
      loading:false,
      form:{
        gameId:'',
        gameName : '',
        dateTime : [],
        gameImage : {
          code:'',
          imgUrl:'',
        },
        background: '',
        gameIntroduction: '',
        gameIntegral: '',
        gameWinningRate: '',
        gameLimitCount: '',
        gameLimitDay: '',
        gameFreeCount: '',
        gameFreeDay: '',
        skinType:0
      },
      prizeReferTypeOptions:[{value:1,label:'积分'},{value:2,label:'卡券'},{value:3,label:'谢谢参与'}],
      dataTest:{
        code:'',
        url:''
      },
      sortList:[{label:'奖品1',value:1},
      {label:'奖品2',value:2},
      {label:'奖品3',value:3},
      {label:'奖品4',value:4},
      {label:'奖品5',value:5},
      {label:'奖品6',value:6},
      {label:'奖品7',value:7},
      {label:'奖品8',value:8},
      {label:'随机',value:null}],
      tableList: [{"prizeId": "", "prizeType": '',"prizeCount": null,"prizeIntegral": null,"prizeCardId": "","gameId": "","prizeStatus": 0,"prizeSort":null,"prizeRate": 0,"cardName": "","cardType": null,"cardDenomination": null,"cardImageUrl": "","cardStock": null,"wechatCardId": null,"winRecordCode": 0,"receiveCount": 0}],
      prizeIndex:0,
      showCardDialog:false,
      rules:{
        gameName:{type:'string', required: true, message: '游戏标题不能为空', trigger: 'blur' },
        dateTime:{type:'array', required: true, message: '游戏时间不能为空', trigger: 'blur' },
        skinType:{type:'number', required: true, message: '请选择皮肤', trigger: 'blur' },
        gameIntegral:{type:'number', required: true, message: '请输入消耗积分', trigger: 'blur' },
        gameIntroduction:{type:'string', required: true, message: '游戏说明不能为空', trigger: 'blur' },
        gameLimitCount:{type:'number', required: true, message: '限制次数不能为空', trigger: 'blur' },
        gameFreeCount:{type:'number', required: true, message: '免费次数不能为空', trigger: 'blur' },
        gameWinningRate:{type:'number', required: true, message: '中奖概率不能为空', trigger: 'blur' }
      },
      infoFlag:this.$route.meta.type === 'detail',
    }
  },
  watch:{
    'form.gameFreeCount'(val){
      if (this.form.gameFreeCount>this.form.gameLimitCount) {
        this.$tips({type:'warning',message:'免费次数不能大于限制次数'});
        this.form.gameFreeCount = this.form.gameLimitCount;
      }
    }
  },
  components:{
    dmUploadAvatar
  },
  created(){
    if (this.$route.meta.type === 'edit' || this.$route.meta.type === 'detail') {
      this.detailLottery();
      this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'游戏营销',path:'/game'},{name:'刮刮卡',path:'/game/ggk'},{name:'刮刮卡详情',path:''}])
    } else {
      this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'游戏营销',path:'/game'},{name:'刮刮卡',path:'/game/ggk'},{name:'刮刮卡新增',path:''}])
    }
  },
  computed:{
    totalCount(){
      let result = 0;
      this.tableList.forEach(v => {
        if (v.prizeCount) {
          result += parseInt(v.prizeCount)
        }
      })
      console.log(result)
      return (parseInt(this.form.gameWinningRate)/result);
    },
    asideShow() {
      return this.$store.state.marketing.asideShow
    }
  },
  methods: {
    // 当奖品为类型3 谢谢参与时 数量置为0
    resetCount(index) {
      this.tableList[index].prizeCount = 0;
    },
    addPrize() {
      this.tableList.push({"prizeId": "", "prizeType": '',"prizeCount": null,"prizeIntegral": null,"prizeCardId": "","gameId": "","prizeStatus": 0,"prizeSort":null,"prizeRate": 0,"cardName": "","cardType": null,"cardDenomination": null,"cardImageUrl": "","cardStock": null,"wechatCardId": null,"winRecordCode": 0,"receiveCount": 0})
    },
    delPrize(i) {
      this.tableList.splice(i,1);
    },
    //选择卡券前置
    setPrizeCard(index) {
      this.prizeIndex = index;
      this.showCardDialog = true;
    },
    //选择卡券后置
    selectCard(val){
      if (val) {
        this.tableList[this.prizeIndex].prizeCardId = val.coupCardId;
        this.tableList[this.prizeIndex].cardName = val.cardName;
      }
      this.showCardDialog = false
    },
    async detailLottery() {
      this.loading = true;
      let res = await detailLottery({gameId:this.$route.params.id,gameType:2});
      this.loading = false;
      result = res.result;
      this.form.gameId = result.gameId;
      this.form.gameName = result.gameName; //1
      this.form.dateTime = [result.gameStartTime||'',result.gameEndTime||'']; //2
      this.form.gameImage = { //3
        code:result.gameImageFieldCode,
        imgUrl:result.gameImageUrl,
      };
      this.form.skinType = result.skinType;
      this.form.background = result.background; //4
      this.form.gameIntroduction = result.gameIntroduction; //5
      this.form.gameIntegral =  result.gameIntegral || 0; //6.1
      this.form.gameWinningRate = result.gameWinningRate || ''; //2
      this.form.gameLimitCount = result.gameLimitCount || '';    // 6.3 限制抽奖 次数
      this.form.gameLimitDay = result.gameLimitDay || '';
      this.form.gameFreeCount = result.gameFreeCount || '';     // 6.4 免费抽奖
      this.form.gameFreeDay = result.gameFreeDay || '';
      result.prizeList.map((v,i) => {
        this.tableList.splice(i,1,v);
      })
    },
    //提交保存
    saveLottery (formName) {
      if (this.form.gameFreeCount>this.form.gameLimitCount) {
        this.$tips({type:'warning',message:'免费次数不能大于限制次数'});
        return;
      }
      let flag = false;
      this.tableList.forEach((v,i) => {
        if ( v.prizeType === 1 && (!v.prizeIntegral || !v.prizeCount)){
          this.$tips({type:'warning',message:`第${i+1}个奖品未填写`});
          flag = true;
          return;
        }
        if ( v.prizeType === 2 && (!v.prizeCardId || !v.prizeCount)){
          this.$tips({type:'warning',message:`第${i+1}个奖品未填写`});
          flag = true;
          return;
        }
        if (flag) return;
      });
      this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = {
                gameId:this.form.gameId,        // 游戏主键ID (新建传空, 修改必传)
                gameName:this.form.gameName,        // 1.游戏名称
                gameStartTimeStr:this.form.dateTime ? formateDateTimeByType(this.form.dateTime[0], 'yyyy-MM-dd-HH-mm-ss'):'',      // 2.游戏时间 startDate
                gameEndTimeStr:this.form.dateTime ? formateDateTimeByType(this.form.dateTime[1], 'yyyy-MM-dd-HH-mm-ss'):'',     // 2.游戏时间 endDate
                skinType:this.form.skinType,     // 1.皮肤模板: 0-自定义 1-黑金 2-红色 3- 霓虹灯 (不为0时, banner图标和 背景颜色隐藏, 对应属性不用传值)
                gameImageFieldCode:this.form.skinType === 0 ? this.form.gameImage.code : '',    // 3.上传后返回的banner图标 code (skinType!=0 时为空)
                gameImageUrl:this.form.skinType === 0 ? this.form.gameImage.imgUrl : '',   // 3.上传后返回的banner图标 URL (skinType!=0为空)
                background:this.form.skinType === 0 ? this.form.background : '',               // 4.背景颜色 (skinType!=0为空)
                gameIntroduction:this.form.gameIntroduction,        // 5.游戏说明
                gameIntegral:this.form.gameIntegral,               // 6.1 抽奖消耗
                gameWinningRate:this.form.gameWinningRate,           // 6.2 中奖几率
                gameLimitCount:this.form.gameLimitCount,          // 6.3 限制抽奖 次数
                gameLimitDay:this.form.gameLimitDay,          // 6.3 限制抽奖 每天的选择  1: 选择; 0: 不选
                gameFreeCount:this.form.gameFreeCount,              // 6.4 免费抽奖次数 (免费次数<限制抽奖次数)
                gameFreeDay:this.form.gameFreeDay,             // 6.4 免费抽奖 每天的选择  1: 选择; 0: 不选
                gameStatus:this.form.gameStatus,
                gameType:2   // 活动类型，1：刮刮卡，2：刮刮卡
            }
            let list = [];
            this.tableList.forEach((v,i) => {
              if (v.prizeType === 1 ) {
                list.push({
                  "prizeIntegral":v.prizeIntegral,
                  "prizeCount":v.prizeCount,            // 奖品数量
                  "prizeRate":0,
                  "prizeSort":i+1,                // 排序值
                  "prizeStatus":1,
                  "prizeType":v.prizeType,                // 奖品类型  1: 积分;  2: 卡券;  3: 谢谢参与
                  "receiveCount":0,
                  "winRecordCode":0
                })
              } else if (v.prizeType === 2) {
                list.push({
                  "prizeCardId":v.prizeCardId,            // 奖项设置: 所选卡券的主键ID coupCardId
                  "prizeCount":v.prizeCount,            // 奖品数量
                  "prizeRate":0,
                  "prizeSort":i+1,                // 排序值
                  "prizeStatus":1,
                  "prizeType":v.prizeType,                // 奖品类型  1: 积分;  2: 卡券;  3: 谢谢参与
                  "receiveCount":0,
                  "winRecordCode":0
                })
              } else {
                list.push({
                  "prizeCount":v.prizeCount,            // 奖品数量
                  "prizeRate":0,
                  "prizeSort":i+1,                // 排序值
                  "prizeStatus":1,
                  "prizeType":v.prizeType,                // 奖品类型  1: 积分;  2: 卡券;  3: 谢谢参与
                  "receiveCount":0,
                  "winRecordCode":0
                })
              }
            });
            params.prizeList = list;
            saveLottery({gameDetail:JSON.stringify(params)}).then(res => {
              if (res.errorCode === 0) {
                this.$tips({type: 'success', message: this.$route.meta.type === 'add'?'新增成功':'编辑成功'});
                if (this.$route.meta.type === 'add') {
                  this.$router.push('/game/ggk');
                } else {
                  this.$confirm('操作成功，是否返回列表?', '提示', {
                    confirmButtonText: '返回列表',
                    cancelButtonText: '留在本页',
                    type: 'warning'
                  }).then(() => {
                    this.$router.push('/game/ggk');
                  }).catch(() => {
                    this.detailLottery(); //先刷新页面
                  });
                }
              } else {
                this.$tips({type:'error',message:res.message || '操作失败'});
              }
            })
          } else {
            this.$tips({type:'warning',message:'表单填写不完整'});
            return false;
          }
        });
    },
    labelTips(h, { column, $index }) {
      return ( <el-tooltip class="item" effect="dark" content="中奖几率=奖品总几率*（该奖品数/所有有效的奖品总数）" placement="top-start">
      <span class="fw500">中奖几率 <i class="iconfont icon-xinxixianshi minor-font-color fz14"></i></span>
      </el-tooltip>)
    }
  },
  filters: {
    numberToChinese(val) {
      return numberToChinese(val);
    }
  }
}
</script>

<style lang="scss" scoped>

.skin-box{
    display: block;
    width: 220px;
    height: 103px;
    &.active{
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.5);
    }
  }

</style>
