<template>
    <el-dialog title="首次获奖策略管理" :visible.sync="show" width="40%" :before-close="close" v-loading="loading">
       <el-form ref="form" :model="form" :rules="rules" label-width="90px">
              <el-form-item label="策略名称" prop="strategyName">
                <el-input v-model="form.strategyName" class="w300"></el-input>
              </el-form-item>
              <el-form-item label="会员等级">
                <el-select v-model="form.gradeLevel" multiple placeholder="请选择" class="w300">
                  <el-option v-for="v in gradeList" :key="v.gradeId" :label="v.gradeName" :value="v.gradeId" :disabled="!v.isShow"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="最近消费">
                <el-date-picker class="w300" :pickerOptions="pickerOptions" v-model="form.lastCostTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="消费总额">
                <el-input-number class="w150" :min="0" size="medium" v-model="form.costAllBegin"></el-input-number> 至
                <el-input-number class="w150" :min="parseInt(form.costAllBegin)" size="medium" v-model="form.costAllEnd"></el-input-number> 元
              </el-form-item>
              <el-form-item label="消费次数">
                <el-input-number class="w150" :min="0" size="medium" v-model="form.costTimesBegin"></el-input-number> 至
                <el-input-number class="w150" :min="parseInt(form.costTimesBegin)" size="medium" v-model="form.costTimesEnd"></el-input-number> 次
              </el-form-item>
              <el-form-item label="客单价">
                <el-input-number class="w150" :min="0" size="medium" v-model="form.avgCostBegin"></el-input-number> 至
                <el-input-number class="w150" :min="parseInt(form.avgCostBegin)" size="medium" v-model="form.avgCostEnd"></el-input-number> 元
              </el-form-item>
              <el-form-item label="连带率">
                <el-input-number class="w150" :min="0" size="medium" v-model="form.avgNumberBegin"></el-input-number> 至
                <el-input-number class="w150" :min="parseInt(form.avgNumberBegin)" size="medium" v-model="form.avgNumberEnd"></el-input-number> 元
              </el-form-item>
              <el-form-item label="奖品设置" prop="prizeReferType">
                <el-select class="w300" v-model="form.prizeReferType" placeholder="请选择" @change="cardCheck">
                  <el-option v-for="v in prizeReferTypeOptions" :key="v.value" :label="v.label" :value="v.value"></el-option>
                </el-select>
                <span v-if="form.prizeReferType === 3" class="fz12 gray">已选中：{{prizeSetInfo.proGiftName}}</span>
                <span v-if="form.prizeReferType === 2" class="fz12 gray">已选中：{{cardObj.cardName}}</span>
              </el-form-item>
              <el-form-item label="积分设置" v-if="form.prizeReferType === 1">
                <el-input-number :precision="0" :min="0" v-model="form.prizeIntegral" placeholder="请输入积分" class="w300"></el-input-number>
              </el-form-item>
              <el-form-item label="奖品数量" prop="prizeCount" v-if="strategyType === 'edit'">
                {{form.prizeCount}} <i class="el-icon-edit blue" @click="calculateShow = true"></i>
                （已领取{{form.prizeCount-form.prizeStock}}件）
              </el-form-item>
               <el-form-item label="奖品数量" prop="prizeCount" v-if="strategyType === 'add'">
                  <el-input-number :precision="0" :min="0" v-model="form.prizeStock" placeholder="请输入奖品数量" class="w300"></el-input-number>
              </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="close">关 闭</el-button>
            <el-button type="primary" @click="submit('form')">保 存</el-button>
        </span>
        <prize-set :info.sync="prizeSetInfo" :show.sync="prizeSetShow"></prize-set>
        <calculate :show.sync="calculateShow" :prizeId="dataId" :prizeReferId="form.prizeReferType === 2?cardObj.coupCardId:form.proGiftId" :prizeReferType="form.prizeReferType" :totalCount="parseInt(form.prizeCount)" @countRefresh="countRefresh"></calculate>
    </el-dialog>
</template>
<script>
import {klflStrategy,klflStrategySave,saveGift} from '@/service/api/gameApi.js';
import {formateDateTimeByType,resetParams} from '@/utils/index.js'
import calculate from '@/components/calculate'
import prizeSet from './prizeSet';


  export default {
    props:{
        show:{
          type:Boolean,
          default:false
        },
        dataId:{
          type:String,
          default:''
        },
        gameActivityId:{
          type:String,
          default:''
        },
        strategyType:{
          type:String,
          default:'add'
        },
        cardObj:{
          type:Object,
          default() {
            return {}
          }
        }
    },
    watch: {
        show(val) {
          if (val) {
              this.klflStrategy();
          } else {
            this.cardObj = {}
          }
        },
        prizeSetInfo:{
          handler(val) {
            console.log(val)
          },
          deep:true
        }
    },
    components:{
      calculate,
      prizeSet
    },
    data() {
      return {
        count:0,
        calculate:true,
        loading:false,
        form: {
          strategyName:'',
          gradeLevel:[],
          avgNumberBegin:null,
          avgNumberEnd:null,
          avgCostBegin:null,
          avgCostEnd:null,
          costTimesBegin:null,
          costTimesEnd:null,
          costAllBegin:null,
          costAllEnd:null,
          lastCostTime:['',''],
          prizeReferId:'',
          cardStatus:-1,
          prizeReferType:1,
          prizeCount:0,
          prizeStock:0,
          prizeIntegral:0,
          prizeImage: {imgUrl:'',code:''},
          giftName:'',
          proGiftId:''
        },
        rules:{
          strategyName:{required:true,message:'请填写策略名称',trigger:'blur'},
          prizeReferType:{required:true,message:'请选择奖品类型',trigger:'blur'},
          prizeCount:{required:true,message:'请填写奖品数量',trigger:'blur'},
        },
        gradeList: [],
        pickerOptions: {
          // disabledDate(time) {
          //     return time.getTime() > Date.now();
          // }
        },
        showCardDialog:false,
        cardLimit: 1, //卡券限制类型 1-限制领取1张的卡券 2- 限制领取 1~100的卡券 3-限制领取>=100 的卡券
        cardType: null, //卡券类型集合（0：抵金券，1：折扣券，2：兑换券）null-为全部类型 逗号分隔
        prizeReferTypeOptions:[{value:1,label:'积分'},{value:2,label:'卡券'},{value:3,label:'礼品'}],
        calculateShow:false,
        //设置为奖品
        prizeSetInfo:{
            prizeImage:{imgUrl:'',code:''},
            proGiftId:'',
            giftStock:'',
            proGiftName:''
        },
        prizeSetShow:false
      };
    },
    created() {
      // $bus.$on('game-klfl-prize-refrsh',val => {
      //   console.log(val)
      //   this.form.prizeReferType = 3;
      //   if (val) {
      //     this.form.giftName = val.giftName;
      //     this.form.prizeImage.imgUrl = val.mainPicUrl;
      //     this.form.prizeImage.code = val.mainPicFieldCode;
      //     this.form.proGiftId = val.proGiftId;
      //   }
      // });
    },
    methods: {
      cardCheck(){
        if(this.form.prizeReferType === 2) {
          this.$emit('set-data','strategyDialog');
        } else if (this.form.prizeReferType === 3) {
          this.prizeSetShow = true;
        }
      },
      countRefresh(val){
        this.form.prizeStock = val.calc ? (parseInt(this.form.prizeStock) + parseInt(val.num)) : (parseInt(this.form.prizeStock) - parseInt(val.num));
        this.form.prizeCount = val.calc ? (parseInt(this.form.prizeCount) + parseInt(val.num)) : (parseInt(this.form.prizeCount) - parseInt(val.num));
      },
      async klflStrategy() {
        this.loading = true;
        let res = await klflStrategy({gamePrizeStrategyId:this.dataId || ''});
        this.loading = false;
        console.log(res)
        this.gradeList = res.result.gradeList;
        const strategy = res.result.dto;
        if (strategy) {
          this.form.strategyName = strategy.strategyName;
          this.form.gamePrizeStrategyId =  strategy.gamePrizeStrategyId;
          this.form.gameActivityId  = strategy.gameActivityId;
          this.form.prizeReferId = strategy.prizeReferId;
          this.form.prizeReferType = strategy.prizeReferType;
          this.form.prizeIntegral = strategy.prizeIntegral;
          this.form.strategyType = strategy.strategyType;
          this.form.prizeStock = strategy.prizeStock;
          this.form.prizeCount = strategy.prizeCount;
          this.form.status = strategy.status;
          this.cardObj.cardName = strategy.proTitle;
          this.cardObj.coupCardId = strategy.prizeReferId;
          if (strategy.proGift) {
            this.prizeSetInfo = {
              prizeImage:{imgUrl:'',code:''},
              proGiftId:strategy.proGift.proGiftId,
              giftStock:strategy.proGift.giftStock,
              proGiftName:strategy.proGift.giftName
            }
          }
          if (strategy.crowdFilter) {
            const obj = JSON.parse(strategy.crowdFilter);
            this.form.gradeLevel = obj.gradeLevel.split(',').filter(v => v != '');
            this.form.cardStatus = obj.cardStatus;
            this.form.avgNumberBegin = parseInt(obj.avgNumberBegin);
            this.form.avgNumberEnd = parseInt(obj.avgNumberEnd);
            this.form.avgCostBegin = parseInt(obj.avgCostBegin);
            this.form.avgCostEnd = parseInt(obj.avgCostEnd);
            this.form.costTimesBegin = parseInt(obj.costTimesBegin);
            this.form.costTimesEnd = parseInt(obj.costTimesEnd);
            this.form.costAllBegin = parseInt(obj.costAllBegin);
            this.form.costAllEnd = parseInt(obj.costAllEnd);
            this.form.lastCostTime = [obj.lastCostTimeBeginStr,obj.lastCostTimeEndStr]
          }
          if (strategy.proGift) {
            this.form.prizeImage = {
              imgUrl:'',
              code:''
            }
            this.form.proGiftId = strategy.proGift.proGiftId;
            this.form.giftName = strategy.proGift.giftName;
            this.form.prizeStock = strategy.proGift.giftStock;
          }
        } else {
          resetParams(this.form);
          this.form.prizeReferType = 1
        }
      },
      close() {
          this.$emit('update:show',false);
      },
      submit(formName){
        if (!this.cardObj.coupCardId && this.form.prizeReferType === 2) {
          this.$tips({type:'warning',message:'请选择卡券'});
          return;
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              gamePrizeStrategyId: this.form.gamePrizeStrategyId,
              gameActivityId: this.form.gameActivityId || this.$route.params.id || this.gameActivityId,
              strategyName: this.form.strategyName,
              prizeReferId: this.form.prizeReferType === 2? this.cardObj.coupCardId:(this.form.prizeReferType === 3?this.prizeSetInfo.proGiftId:null),
              prizeReferType: this.form.prizeReferType,
              prizeStock: this.form.prizeStock,
              prizeCount: this.form.prizeStock,
              prizeIntegral : this.form.prizeIntegral,
              strategyType:'2',
              status:this.form.status
            }
            let _data = {
              gradeLevel:this.form.gradeLevel.join(','),
              cardStatus:'1',
              //连带率
              avgNumberBegin: '' + this.form.avgNumberBegin,
              avgNumberEnd: '' + this.form.avgNumberEnd,
              //客单价
              avgCostBegin: '' + this.form.avgCostBegin,
              avgCostEnd: '' + this.form.avgCostEnd,
              //消费次数
              costTimesBegin: '' + this.form.costTimesBegin,
              costTimesEnd: '' + this.form.costTimesEnd,
              //消费总额
              costAllBegin: '' + this.form.costAllBegin,
              costAllEnd: '' + this.form.costAllEnd,
              //最近消费
              lastCostTimeBeginStr: formateDateTimeByType(this.form.lastCostTime[0],'yyyy-MM-dd'),
              lastCostTimeEndStr: formateDateTimeByType(this.form.lastCostTime[1],'yyyy-MM-dd')
            }
            data.crowdFilter = JSON.stringify(_data);
            klflStrategySave(data).then(res => {
              this.$tips({type:'success',message:'操作成功'});
              this.$emit('update:show',false);
              this.$emit('refesh');
            })
          } else {
            this.$tips({type:'warning',message:'表单填写不完整'});
            return false;
          }
        });
      }
    },
  };
</script>
