<template>
  <div>
    <div class="navtop">
      <div class="gameName">
        <img src="../../../assets/img/幸运盲盒.png" alt="" />
        <span>幸运盲盒</span>
      </div>
      <div class="rightBtn">
        <el-button @click="returnNext" v-if="!isInfo">退出</el-button>
        <el-button @click="$router.go(-1)" v-else>返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="isCopy || isEdit">发布并预览</el-button>
      </div>
    </div>
    <div class="content">
      <div class="left-content">
        <el-menu class="dm-aside-menu" ref="asideMenu" :default-active="menuActive" @select="handleMenuSelect">
          <el-menu-item class="dm-sub-menu" v-for="(el, index) in menuList" :key="index" :index="index">
            {{ el }}
          </el-menu-item>
        </el-menu>
        <div class="iphone" v-if="menuActive == 0">
          <span class="gameTitle">{{ gameName }}</span>
          <img src="../../../assets/img/Navbar.png" alt="" />
          <gameTemplate :bgImg="bgImg" :tipsImg="tipsImg" :boxImg="boxImg" :adImg="adImg" />
        </div>
        <div class="iphone" v-else>
          <img :src="computedImg" />
        </div>
      </div>
      <div class="rightForm" v-show="!isInfo">
        <dm-steps :active="active" simple>
          <dm-step title="1.基础配置"></dm-step>
          <dm-step title="2.奖项配置"></dm-step>
          <dm-step title="3.规则配置"></dm-step>
        </dm-steps>
        <div class="formContent">
          <baseConfig ref="baseConfig" :gameStatus="gameStatus" :templateArr="templateData" :echoData="baseForm" v-show="active == 0" @change="handleBaseConfigChange" @nextStep="nextStep" />
          <prizeConfig ref="prizeConfig" :gameStatus="gameStatus" :invalidCard="invalidCard" :prizeMax="prizeMax" :echoData="prizeForm" :prizeMin="prizeMin" v-show="active == 1" @nextStep="nextStep" @prevStep="step => active--" />
          <ruleConfig ref="ruleConfig" :gameStatus="gameStatus" :gameTime="gameTime" :shareImgData="shareImgData" :echoData="ruleForm" v-show="active == 2" @nextStep="nextStep" @prevStep="step => active--" @submit="submitForm" :btnLoading="btnLoading" />
        </div>
      </div>
      <info :data="echoData" :invalidCard="invalidCard" v-if="isInfo" />
    </div>
    <links :show.sync="linkShow" :obj="linksObj" gameTypeName="幸运盲盒" :isNew="true" :showFooter="true" :showClose="false">
      <el-button @click="editRenew">重新编辑</el-button>
      <el-button type="primary" @click="$router.push('/game/cmh')">进入游戏列表</el-button>
    </links>
  </div>
</template>

<script>
import steps from '@/views/game/dm-steps/steps';
import step from '@/views/game/dm-step/step';
import baseConfig from './base-config.vue';
import prizeConfig from './prize-config.vue';
import ruleConfig from './rule-config.vue';
import { getGameTemplateByType, initActivity, getGameDetail, cardView } from '@/service/api/gameApi.js';
import gameTemplate from './gameTemplate';
import info from './info.vue';
import links from '../common/links';
export default {
  data() {
    return {
      linkShow: false,
      linksObj: {},
      active: 0,
      menuActive: 0,
      templateData: [],
      prizeMax: 10,
      prizeMin: 1,
      gameName: '游戏名称',
      templateId: '',
      menuList: ['首页', '活动规则', '我的奖品', '中奖', '未中奖', '分享效果'],
      bgImg: '',
      tipsImg: '',
      boxImg: '',
      adImg: '',
      btnLoading: false,
      submitData: {},
      isEdit: this.$route.meta.type === 'edit',
      isAdd: this.$route.meta.type === 'add',
      isCopy: this.$route.meta.type === 'copy',
      isInfo: this.$route.meta.type === 'info',
      baseForm: {},
      prizeForm: {},
      ruleForm: {},
      gameId: '',
      gameStatus: 0,
      invalidCard: {},
      gameTime: [],
      echoData: {},
      shareImgData: {}
    };
  },
  computed: {
    computedImg() {
      const bcImg = {
        1: require(`@/assets/img/template${this.templateId}/mould_rule_page.png`),
        2: require(`@/assets/img/template${this.templateId}/mould_prize_page.png`),
        3: require(`@/assets/img/template${this.templateId}/mould_success_page.png`),
        4: require(`@/assets/img/template${this.templateId}/mould_fail_page.png`),
        5: require(`@/assets/img/template${this.templateId}/mould_share_page.png`)
      };
      return bcImg[this.menuActive];
    }
  },
  components: {
    'dm-steps': steps,
    'dm-step': step,
    baseConfig,
    gameTemplate,
    prizeConfig,
    ruleConfig,
    links,
    info
  },
  mounted() {
    this.getGameTemplateByType();
  },
  watch: {
    templateId(val) {
      const data = this.templateData.filter(item => item.templateId == val)[0];
      console.log(data);
      const { prizeMax, prizeMin } = data;
      this.prizeMax = prizeMax;
      this.prizeMin = prizeMin;
    }
  },
  methods: {
    getGameDetail(id) {
      getGameDetail({ gameId: id }).then(async res => {
        const { result } = res;
        if (this.isInfo) {
          const templateData = this.templateData.filter(item => item.templateId == result.templateId)[0];
          this.echoData = JSON.parse(JSON.stringify(result));
          this.echoData.templateName = templateData.templateName;
        }

        let {
          gameRuleInfo, // 游戏规则信息
          gameRuleConditionList, // 游戏规则-参与门槛
          gamePrizeList, //游戏奖品信息
          gameExt,
          prizeNoticeStock,
          prizeNoticeFlag,
          adsFlag,
          bulletFlag,
          backMusicFlag,
          templateId,
          gameRule,
          startDate,
          endDate,
          gameName,
          memberWeightView,
          creatorId,
          gameId,
          status
        } = result;
        if (this.isEdit) {
          this.gameId = gameId;
          this.gameStatus = status;
        }
        const { ruleId, winChance, filterJson, filterJsonView, memberDesc, memberType, playConditionFlag, playTimes, shareFlag, shareImageUrl, shareRuleDesc } = gameRuleInfo;
        if (playConditionFlag == 1) {
          gameRuleConditionList.forEach(item => {
            item.conditionJson = JSON.parse(item.conditionJson);
          });
        }
        let cardIdArr = [];
        gamePrizeList.forEach(item => {
          if (item.prizeType == 2) {
            cardIdArr.push(item.prizeRelationId);
          }
          if (this.isEdit) {
            item.isOld = 1;
          }
        });
        if (cardIdArr.length) {
          const { result } = await cardView({ ids: cardIdArr.join(',') });
          this.invalidCard = result; // 1删除 2失效
        }
        if (this.isCopy) {
          let invalidCard = [];
          gamePrizeList.forEach(item => {
            if (item.prizeType == 2 && this.invalidCard[item.prizeRelationId].invalid != 0) {
              invalidCard.push(item.prizeRelationId);
            }
          });
          if (invalidCard.length) {
            gamePrizeList = gamePrizeList.filter(item => item.prizeType != 2 || !invalidCard.includes(item.prizeRelationId));
            this.$message.info('已过滤被删除奖项');
          }
        }
        this.baseForm = { adsFlag, backMusicFlag, bulletFlag, templateId, gameTime: [startDate, endDate], gameName, gameRule, gameExt };
        this.prizeForm = { winChance, prizeNoticeStock, gamePrizeList, prizeNoticeFlag };
        this.ruleForm = { ruleId, filterJson, gameRuleConditionList, memberDesc, memberType, playConditionFlag, playTimes, shareFlag, shareImageUrl, shareRuleDesc, memberWeightView, creatorId, filterJsonView };
      });
    },
    handleBaseConfigChange(data) {
      console.log('handleBaseConfigChange----->');
      console.log(data);
      const { backImageUrl, noticeImageUrl, adsImageUrl, gameName, templateId, shareCard, shareReport, gameTime, shareCardSize0, shareCardSize1, shareReportSize1, shareReportSize0 } = data;
      this.bgImg = backImageUrl;
      this.tipsImg = noticeImageUrl;
      this.boxImg = data.prizeStyleJson[0].imageNoSelectUrl;
      this.adImg = adsImageUrl;
      this.gameName = gameName;
      this.templateId = templateId;
      this.shareImgData = {
        shareCard,
        shareReport,
        shareCardSize0,
        shareCardSize1,
        shareReportSize1,
        shareReportSize0
      };

      this.gameTime = gameTime;
    },
    returnNext() {
      this.$confirm('退出后，当前编辑没有保存的数据会丢失，确认要退出吗?', {
        type: 'warning'
      })
        .then(() => {
          this.$router.push('/game/cmh');
        })
        .catch(() => {});
    },
    handleMenuSelect(index) {
      this.menuActive = index;
    },
    async getGameTemplateByType() {
      const res = await getGameTemplateByType({ templateType: 1 });
      this.templateData = res.result;
      if (this.isAdd) {
        this.$route.meta.refresh = false;
        const { templateId } = res.result[0];
        this.templateId = templateId;
        // res.result[0].gameTemplateMaterialList.forEach(item => {
        //   if (item.materialKey == 'shareCard') {
        //     this.shareCard = item.materialValue;
        //   }
        //   if (item.materialKey == 'shareReport') {
        //     this.shareReport = item.materialValue;
        //   }
        // });
      } else {
        const { id } = this.$route.params;
        this.getGameDetail(id);
      }
    },
    nextStep(data, noNext) {
      if (!noNext) {
        this.active++;
      } else {
        this.submitData = { ...this.submitData, ...data };
      }
    },
    async handleSubmitData() {
      this.submitData = JSON.parse(JSON.stringify(this.submitData));
      console.log(this.submitData);
      const { ruleId, winChance, filterJson, filterJsonView, memberDesc, memberType, playConditionFlag, playTimes, shareFlag, shareImageUrl, gameRuleConditionList, gameName, gamePrizeList, prizeNoticeStock, prizeNoticeFlag, adsFlag, bulletFlag, backMusicFlag, templateId, gameRule, gameTime, gameExt } = this.submitData;
      const gameRuleInfo = { ruleId, winChance, filterJson, filterJsonView, memberDesc, memberType, playConditionFlag, playTimes, shareFlag, shareImageUrl, shareRuleDesc: gameName };
      let cardIdArr = [];
      let zeroStock = [];
      gamePrizeList.forEach(item => {
        if (item.prizeType == 2) {
          cardIdArr.push(item.prizeRelationId);
        }
        if (item.prizeStock == 0) {
          zeroStock.push(item);
        }
      });
      if (cardIdArr.length) {
        const { result } = await cardView({ ids: cardIdArr.join(',') });
        this.invalidCard = result; // 1删除 2失效
        if (
          Object.values(result)
            .map(item => item.invalid != 0)
            .includes(true) &&
          this.gameStatus == 0
        ) {
          this.$message.error('存在异常状态的卡券,请返回上一步修改卡券后再提交');
          return;
        }
        let invalidCardName = [];
        gamePrizeList.forEach(item => {
          if (item.prizeType == 2 && !item.isOld && item.prizeStock > result[item.prizeRelationId].stock) {
            invalidCardName.push(item.prizeName);
          }
        });
        if (invalidCardName.length) {
          this.$message.error(`${invalidCardName.join(',')}奖品数量高于关联库存，请修改奖品数量`);
          return;
        }
      }
      gameRuleConditionList.forEach(item => {
        item.conditionJson = JSON.stringify(item.conditionJson);
      });
      if (this.isCopy) {
        Object.values(gameExt).forEach(item => {
          delete item.gameExtId;
          delete item.gameId;
        });
        gamePrizeList.forEach(item => {
          delete item.prizeId;
          delete item.gameId;
        });
        gameRuleConditionList.forEach(item => {
          if (this.isCopy) {
            delete item.conditionId;
            delete item.gameId;
          }
        });
        delete gameRuleInfo.ruleId;
        delete gameRuleInfo.gameId;
      }

      this.$confirm(`${zeroStock.length ? '有奖品数量为0，该奖项将不会被抽中。确认保存?' : '确认发布游戏?'}`, {
        type: 'warning'
      }).then(() => {
        let submitData = {
          gameRuleInfo, // 游戏规则信息
          gameRuleConditionList, // 游戏规则-参与门槛
          gamePrizeList, //游戏奖品信息
          gameExt,
          templateType: 1, // 1盲盒
          prizeNoticeStock,
          prizeNoticeFlag,
          adsFlag,
          bulletFlag,
          backMusicFlag,
          templateId,
          gameRule,
          startDate: gameTime[0],
          endDate: gameTime[1],
          gameName
        };
        if (this.isEdit) {
          submitData.gameId = this.gameId;
        }
        this.btnLoading = true;
        initActivity(submitData)
          .then(res => {
            if (res) {
              const { result } = res;
              this.$message.success('发布成功');
              this.getLink(result);
              this.$route.meta.refresh = true;
            }
          })
          .finally((this.btnLoading = false));
      });
    },
    validator() {
      // 校验必填
      return Promise.all([this.$refs.baseConfig.nextStep('noNext'), this.$refs.prizeConfig.nextStep('noNext'), this.$refs.ruleConfig.nextStep('noNext')]).then(val => {
        if (!val.includes(false)) {
          return true;
        } else {
          this.$message.error('请确认必填字段都已填写且通过校验');
          return false;
        }
      });
    },
    submitForm() {
      this.validator().then(val => {
        if (!val) return;
        this.handleSubmitData();
      });
    },
    getLink(row) {
      const { startDate, gameId, gameName } = row;
      this.gameId = gameId;
      this.linksObj = { gameName, gameId, gameStartTime: startDate };
      this.linkShow = true;
    },
    editRenew() {
      window.location.href = window.location.origin + `/marketing/#/game/cmh/edit/${this.gameId}`;
      window.location.reload();
      // this.$router.push(`/game/cmh/edit/${this.gameId}`);
    }
  }
};
</script>

<style lang="scss" scoped>
.navtop {
  width: 100%;
  height: 52px;
  background: #ffffff;
  box-shadow: 0px 4px 8px 0px rgba(220, 223, 230, 0.4);
  border-radius: 4px 0px 0px 0px;
  display: flex;
  padding: 10px 20px;
  justify-content: space-between;
  box-sizing: border-box;
  position: relative;
  .gameName {
    align-items: center;
    display: flex;
    img {
      width: 30px;
    }
    span {
      color: #303133;
      font-weight: 600;
      font-size: 17px;
      margin-left: 12px;
    }
  }
}
.content {
  display: flex;
  overflow: hidden;
}
.left-content {
  width: 520px;
  height: calc(100vh - 52px);
  background: #f7f8fa;
  box-sizing: border-box;
  padding: 30px 0 20px 20px;
  display: flex;
}
.dm-aside-menu {
  width: 90px;
  height: 100%;
  border-right: none;
  background-color: #f7f8fa;
  box-sizing: border-box;
  overflow-y: auto;
  /deep/ .el-menu {
    background-color: transparent;
  }
  /deep/ .el-menu-item {
    padding-left: 10px !important;
    height: 32px;
    width: auto;
    font-size: 14px;
    font-weight: 400;
    color: #303133;
    line-height: 34px;
    border-radius: 4px;
    &:hover {
      background: #ebeffe;
    }
    &.is-active {
      font-weight: 500;
      color: #2f54eb;
      background: #ebeffe;
    }
    + .el-menu-item {
      margin-top: 8px;
    }
  }
}
.iphone {
  width: 375px;
  background: #ffffff;
  border-radius: 8px 8px 0px 0px;
  margin: 0 20px 0 13px;
  position: relative;
  img {
    width: 375px;
  }
}
.gameTitle {
  font-size: 17px;
  position: absolute;
  color: #000000;
  font-weight: 600;
  z-index: 100;
  top: 56px;
  left: 154px;
}
.rightForm {
  padding: 30px 20px 0 30px;
  box-sizing: border-box;
  width: calc(100vw - 520px);
  height: calc(100vh - 108px);
  background: #ffffff;
  .formContent {
    margin-top: 20px;
    overflow-y: auto;
    height: 90%;
  }
}
</style>
