<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="ptyx-add" v-loading="loading" element-loading-text="拼命加载中" >
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">游戏内容</h3>
      <el-form-item label="游戏名称" prop="gameName" class="width50">
        <dm-input v-model="form.gameName" class="w400" :disabled="queryDisabled" :maxlength="25"></dm-input>
      </el-form-item>
      <el-form-item label="选择拼图" prop="puzzleImg" class="width50 is-required">
        <dm-upload-avatar :model.sync="form.puzzleImg" label="上传图片" tips="图片建议尺寸：510px*680px" :disabled="queryDisabled"></dm-upload-avatar>
      </el-form-item>
      <el-form-item label="游戏时间" prop="dateTime" class="width50">
        <el-date-picker class="w400" :disabled="queryDisabled"
          v-model="form.dateTime"
          type="datetimerange" :default-time="['00:00:00', '23:59:59']"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="游戏说明" prop="gameIntroduction">
        <dm-input type="textarea" class="w400" :rows="4" v-model="form.gameIntroduction" :disabled="queryDisabled" :maxlength="200"></dm-input>
      </el-form-item>
      <el-form-item label="奖品设置" class="el-form-item__margin-top14 pt20">
        <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) | numberToChinese}}等奖
            </template>
          </el-table-column>
          <el-table-column prop="rankEnd" label="名次" align="left" width="220">
            <template slot-scope="scope">
                前 <el-input-number v-model="scope.row.rankEnd" :precision="0" :min="1" @change="comparePre(scope.$index,scope.row.rankEnd)" size="small" class="w150" :disabled="queryDisabled"></el-input-number> 名
            </template>
          </el-table-column>
          <el-table-column prop="prizeName" label="商品名称" align="left" :min-width="180">
            <template slot-scope="scope">
                <dm-input v-model="scope.row.prizeName" size="small" :disabled="queryDisabled" :maxlength="15"></dm-input>
            </template>
          </el-table-column>
          <el-table-column prop="prizeImgFieldCode" label="商品图片(150*150)" align="center" :min-width="100">
            <template slot-scope="scope">
              <dm-upload-avatar :model.sync="scope.row.prizeImg" label="上传图片" width="40" height="40" tips="" class-name="block-center" :disabled="queryDisabled"></dm-upload-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="prizeQuantity" label="商品数量" align="left" width="80">
            <template slot-scope="scope">
              {{
                scope.$index?
                ((tableList[scope.$index].rankEnd-tableList[scope.$index-1].rankEnd)<0?0
                  :(tableList[scope.$index].rankEnd-tableList[scope.$index-1].rankEnd))
                :tableList[scope.$index].rankEnd
                }} 件
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" align="left" width="60">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.$index>2" @click="delItem(scope.$index)" :disabled="queryDisabled">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="tableList.length<10 && !queryDisabled" class="dm-button--add" @click="addPrice">
          <i class="el-icon-plus">添加奖品</i>
        </div>
      </el-form-item>
    </section>
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">页面设置</h3>
      <el-form-item label="品牌logo" class="width50 is-required">
        <dm-upload-avatar :model.sync="form.logoImg" label="上传图片" width="80" height="80" tips="请上传高度为85px的PNG透明背景图片" :disabled="queryDisabled"></dm-upload-avatar>
      </el-form-item>
      <el-form-item label="每次游戏消耗" prop="usedValue" class="width50">
        <el-input-number controls-position="right" v-model="form.usedValue" :precision="0" :min="1" class="w300" placeholder="请输入正整数" @blur="nonnegative(form.usedValue)" :disabled="queryDisabled">
        </el-input-number> 体力
      </el-form-item>
      <el-form-item label="无体力可使用" prop="usedIntegral" class="width50">
        <el-input-number controls-position="right" v-model="form.usedIntegral" :precision="0" :min="1" class="w300" placeholder="请输入正整数"  @blur="nonnegative(form.usedIntegral)" :disabled="queryDisabled">
        </el-input-number> 积分
      </el-form-item>
    </section>
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">分享设置</h3>
      <el-form-item label="分享到朋友圈" class="width50 is-required">
        <el-radio-group v-model="form.shareGroup">
          <el-radio :label="1">可分享</el-radio>
          <el-radio :label="2">不可分享</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分享给朋友" class="width50 is-required">
        <el-radio-group v-model="form.shareFriend">
          <el-radio :label="1">可分享</el-radio>
          <el-radio :label="2">不可分享</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分享图" class="width50 is-required">
        <dm-upload-avatar :model.sync="form.shareImg" fileType="fileShare" label="上传图片" tips="图片建议尺寸：高度200px*200px" :disabled="queryDisabled"></dm-upload-avatar>
      </el-form-item>
      <el-form-item label="分享标题" prop="shareTitle" class="width50">
        <dm-input v-model="form.shareTitle" class="w400" placeholder="请输入分享标题" :disabled="queryDisabled" :maxlength="20"></dm-input>
      </el-form-item>
      <el-form-item label="分享描述" prop="shareTextInfo" class="width50">
        <dm-input type="textarea" class="w400" :rows="4" v-model="form.shareTextInfo" placeholder="请输入分享描述" :disabled="queryDisabled" :maxlength="50"></dm-input>
      </el-form-item>
     </section>
    <div class="btn-wrap_fixed" :class="{'on':asideShow}" v-if="!queryDisabled">
      <el-button type="primary" @click="savePtyx('form')">保 存</el-button>
      <el-button @click="$router.go(-1)">返 回</el-button>
    </div>

  </el-form>
</template>

<script>
import {ptyxDetail,savePtyx} from '@/service/api/gameApi.js';
import {numberToChinese,formateDateTimeByType} from '@/utils/index.js';
import dmUploadAvatar from '@/components/upload/avatar';
import dmUploadImg from '@/components/upload/img';
import nonnegative from '@/mixins/nonnegative.js'
let gameInfo = {};
export default {
  mixins:[nonnegative],
  data () {
    return {
      loading:false,
      form:{gameName:'',puzzleImg:{imgUrl:'',code:''},gameIntroduction:'',dateTime:['',''],logoImg:{imgUrl:'',code:''},usedValue:'',usedIntegral:'',shareImg:{imgUrl:'',code:''},shareTitle:'',shareTextInfo:'',shareGroup:1,shareFriend:1},
      rules:{
        gameName:{required:true,  message: '请输入游戏名', trigger: 'blur' },
        dateTime:{required:true,type:'array',  message: '请选择游戏时间', trigger: 'blur' },
        gameIntroduction:{required:true,  message: '请输入游戏说明', trigger: 'blur' },
        usedValue:{required:true, type:'number',  message: '请输入数值', trigger: 'blur' },
        usedIntegral:{required:true,  type:'number', message: '请输入数值', trigger: 'blur' },
        shareTitle:{required:true,  message: '请输入分享标题', trigger: 'blur' },
        shareTextInfo:{required:true,  message: '请输入分享描述', trigger: 'blur' },
      },
      tableList:[
        {awardName:'',rankEnd:0,prizeName:'', prizeImg: {code:'',imgUrl:''},prizeQuantity:''},
        {awardName:'',rankEnd:0,prizeName:'', prizeImg: {code:'',imgUrl:''},prizeQuantity:''},
        {awardName:'',rankEnd:0,prizeName:'', prizeImg: {code:'',imgUrl:''},prizeQuantity:''},
      ],
      queryDisabled:this.$route.meta.type === 'query',
      editDisabled:this.$route.meta.type === 'edit',
    }
  },
  components:{
    dmUploadAvatar,
    dmUploadImg
  },
  computed: {
    asideShow() {
      return this.$store.state.marketing.asideShow
    }
  },
  created(){
    if (this.$route.meta.type === 'edit') {
      this.ptyxDetail();
      this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'游戏营销',path:'/game'},{name:'拼图游戏',path:'/game/ptyx'},{name:'拼图游戏编辑',path:''}])
    } else if (this.$route.meta.type === 'add') {
      this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'游戏营销',path:'/game'},{name:'拼图游戏',path:'/game/ptyx'},{name:'拼图游戏新增',path:''}])
    } if (this.$route.meta.type === 'query') {
       this.ptyxDetail();
      this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'游戏营销',path:'/game'},{name:'拼图游戏',path:'/game/ptyx'},{name:'拼图游戏详情',path:''}])
    }
  },
  methods: {
    //添加奖品
    addPrice() {
      this.tableList.push({awardName:'',rankEnd:0,prizeName:'', prizeImg: {code:'',imgUrl:''},prizeQuantity:''})
    },
    delItem(index){
      this.tableList.splice(index,1);
    },
    //这里用nextTick下个更新执行
    comparePre(index,val){
      if (this.tableList[index].rankEnd<0) {
        this.$tips({type:'warning',message:'不能为负值'});
        return;
      }
      if (index > 0 && (this.tableList[index].rankEnd - this.tableList[index-1].rankEnd) <= 0 ) {
        this.$tips({type:'warning',message:'必须大于上一个名次'});
        this.$nextTick(_ => {
          this.tableList[index].rankEnd = parseInt(this.tableList[index-1].rankEnd) +1
        })
      }
    },
    async ptyxDetail() {
      this.loading = true;
      let res = await ptyxDetail({gameActivityId:this.$route.params.id});
      this.loading = false;
      gameInfo = res.result.gameInfo;
      this.form = {
        gameActivityId:gameInfo.gameActivityId,
        gameName:gameInfo.gameName,
        puzzleImg:{
          code:gameInfo.puzzleImgFieldCode,
          imgUrl:gameInfo.puzzleImgUrl,
        },
        dateTime:[gameInfo.gameStartTime||'',gameInfo.gameEndTime||''],
        gameIntroduction:gameInfo.gameIntroduction,

        //页面设置
        logoImg:{
          code:gameInfo.logoImgFieldCode,
          imgUrl:gameInfo.logoImgUrl,
        },
        usedValue:gameInfo.usedValue,
        usedIntegral:gameInfo.usedIntegral,

        //分享
        shareTitle:gameInfo.shareTitle,
        shareTextInfo:gameInfo.shareTextInfo,
        shareImg:{
          code:gameInfo.shareImgFieldCode,
          imgUrl:gameInfo.shareImgUrl,
          wxImg:gameInfo.shareImgUrlWX
        },
      }
      gameInfo.prizeList.map(v => {
        v.prizeImg = {
          code:v.prizeImgFieldCode,
          imgUrl:v.prizeImgUrl
        }
      })
      this.tableList = gameInfo.prizeList;
    },
    //提交保存
    savePtyx (formName) {
      if (!this.form.puzzleImg.code) {
        this.$tips({type:'warning',message:'游戏拼图图片不能为空'});
        return;
      }
      if (!this.form.shareImg.code ) {
        this.$tips({type:'warning',message:'分享图不能为空'});
        return;
      }
      if (!this.form.logoImg.code) {
        this.$tips({type:'warning',message:'品牌logo不能为空'});
        return;
      }
      let flag = false;
      this.tableList.forEach((v,i) => {
        if (!v.rankEnd || !v.prizeName || !v.prizeImg.code) {
          this.$tips({type:'warning',message:'奖品设置区名次、名称、商品图不能为空'});
          flag = true;
        }
      })
      if (flag) return;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          gameInfo.gameActivityId = this.form.gameActivityId || ''
          gameInfo.gameName = this.form.gameName || ''
          gameInfo.puzzleImgFieldCode = this.form.puzzleImg.code || ''
          gameInfo.puzzleImgUrl = this.form.puzzleImg.imgUrl || ''
          gameInfo.startTimeStr = formateDateTimeByType(this.form.dateTime[0], 'yyyy-MM-dd-HH-mm-ss') || ''
          gameInfo.endTimeStr = formateDateTimeByType(this.form.dateTime[1], 'yyyy-MM-dd-HH-mm-ss') || ''
          gameInfo.gameIntroduction = this.form.gameIntroduction || ''
          gameInfo.logoImgFieldCode = this.form.logoImg.code || ''
          gameInfo.logoImgUrl = this.form.logoImg.imgUrl || ''
          gameInfo.usedValue = this.form.usedValue || ''
          gameInfo.usedIntegral = this.form.usedIntegral || ''
          gameInfo.shareTitle = this.form.shareTitle || ''
          gameInfo.shareTextInfo = this.form.shareTextInfo || ''
          gameInfo.shareImgFieldCode= this.form.shareImg.code || ''
          gameInfo.shareImgUrl= this.form.shareImg.imgUrl || ''
          gameInfo.shareImgUrlWX = this.form.shareImg.wxImg || ''
          gameInfo.activityStatus = 1
          let list = [];
          this.tableList.forEach((v,i) => {
            list.push({
              prizeImgFieldCode : v.prizeImg.code || '',
              prizeImgUrl : v.prizeImg.imgUrl || '',
              winnerCount : parseInt(v.rankEnd) || '',
              awardName : numberToChinese(i+1)+'等奖',
              prizeType :1,
              prizeName:v.prizeName || '',
              prizeId:v.prizeId || '',
              prizeQuantity:0
            })
          });
          gameInfo.prizeList = list;
          console.log(gameInfo.prizeList)
          savePtyx({gameData:JSON.stringify(gameInfo)}).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/ptyx');
              } else {
                this.$confirm('操作成功，是否返回列表?', '提示', {
                  confirmButtonText: '返回列表',
                  cancelButtonText: '留在本页',
                  type: 'warning'
                }).then(() => {
                  this.$router.push('/game/ptyx');
                }).catch(() => {
                  this.ptyxDetail(); //先刷新页面
                });
              }
            } else {
              this.$tips({type: 'error', message: res.message || '保存失败'});
            }
          })
        } else {
          this.$tips({type: 'success', message: '表单填写不完整或者不规范'});
          return false;
        }
      })
    }
  },
  filters: {
    numberToChinese(val) {
      return numberToChinese(val);
    }
  }
}
</script>
