<template>
  <div v-loading="loading">
    <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="goBack" 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 style="margin: 0 20px 0 13px;">
          <div class="nav">
            <span class="gameTitle">{{ gameName }}</span>
            <img src="../../../assets/img/Navbar.png" class="braImg" alt="" />
          </div>
          <div class="iphone">
            <gameTemplate :ruleData="ruleData" :templateId="templateId" :basicData="previewData" v-show="menuActive == 0" />
            <img :src="computedImg" v-show="menuActive != 0" style="min-height:724px; " />
          </div>
        </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" id="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" :templateId="templateId" :gameTime="gameTime" :shareImgData="shareImgData" :echoData="ruleForm" v-show="active == 2" @nextStep="nextStep" @prevStep="step => active--" @submit="submitForm" :btnLoading="btnLoading" @change="handleRuleConfigChange" />
        </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="goList">进入游戏列表</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: 1,
      menuList: ['首页', '活动规则', '我的奖品', '中奖', '未中奖', '分享效果'],
      bgImg: '',
      tipsImg: '',
      boxImg: '',
      adImg: '',
      bulletImage: '',
      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: {},
      loading: false,
      ruleData: {
        0: {},
        1: {}
      },
      previewData: {},
      documentTitle: {
        edit: '幸运盲盒编辑',
        add: '幸运盲盒新建',
        copy: '幸运盲盒复制',
        info: '幸运盲盒查看'
      }
    };
  },
  computed: {
    computedImg() {
      if (!['1', '2', '3', '5'].includes(this.templateId)) {
        return '';
      }
      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();
    document.title = this.documentTitle[this.$route.meta.type];
  },
  watch: {
    templateId(val) {
      const data = this.templateData.filter(item => item.templateId == val)[0];
      const { prizeMax, prizeMin } = data;
      this.prizeMax = prizeMax;
      this.prizeMin = prizeMin;
    }
  },
  methods: {
    getGameDetail(id) {
      this.loading = true;
      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 => {
              if (item.conditionType == 0) {
                this.ruleData[0] = { val: item.value, type: 0 };
              }
              item.conditionJson = JSON.parse(item.conditionJson);
            });
          }
          this.previewData = Object.assign(this.previewData, { bulletFlag, bulletImageUrl: gameExt.bulletImageUrl });
          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 };
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleBaseConfigChange(data) {
      const { backMusicFlag, adsFlag, backImageUrl, noticeImageUrl, adsImageUrl, bulletImageUrl, bulletFlag, gameName, templateId, shareCard, shareReport, gameTime, shareCardSize0, shareCardSize1, shareReportSize1, shareReportSize0 } = data;
      this.previewData = { backMusicFlag, backImageUrl, noticeImageUrl, adsImageUrl, bulletImageUrl, bulletFlag, adsFlag };
      this.previewData.boxImg = data.prizeStyleJson[0].imageNoSelectUrl;
      this.previewData = Object.assign({}, this.previewData);
      this.gameName = gameName;
      this.templateId = templateId;
      this.shareImgData = {
        shareCard,
        shareReport,
        shareCardSize0,
        shareCardSize1,
        shareReportSize1,
        shareReportSize0
      };
      this.gameTime = gameTime;
    },
    handleRuleConfigChange(data) {
      this.ruleData[data.id] = data;
      this.ruleData = Object.assign({}, this.ruleData);
    },
    returnNext() {
      this.$confirm('退出后，当前编辑没有保存的数据会丢失，确认要退出吗?', {
        type: 'warning'
      })
        .then(() => {
          window.close();
        })
        .catch(() => {});
    },
    goBack() {
      window.close();
    },
    handleMenuSelect(index) {
      this.menuActive = index;
    },
    async getGameTemplateByType() {
      this.loading = true;
      const res = await getGameTemplateByType({ templateType: 1 });
      this.templateData = res.result;
      if (this.isAdd) {
        this.$route.meta.refresh = false;
        const { templateId } = this.templateData.filter(item => item.statusFlag == 1)[0];
        this.templateId = templateId;
        this.loading = false;
      } 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 };
      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 => {
        if (item.conditionType == 1) {
          gameExt.shareCard.materialValue = item.conditionJson.shareCard;
          gameExt.shareReport.materialValue = item.conditionJson.shareReport;
          gameRuleInfo.shareRuleDesc = item.conditionJson.shareTitle;
        }
        item.conditionJson = JSON.stringify(item.conditionJson);
      });
      if (!gameRuleConditionList.filter(item => item.conditionType == 1).length) {
        gameRuleInfo.shareRuleDesc = gameName;
      }
      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);
            }
          })
          .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 => {
        console.log(val);
        if (!val.includes(false)) {
          return true;
        } else {
          return false;
        }
      });
    },
    submitForm() {
      this.validator().then(val => {
        console.log(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();
    },
    goList() {
      if (this.isAdd) {
        this.$route.meta.refresh = true;
      }
      this.$router.push('/game/cmh');
    }
  }
};
</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;
    }
  }
}
.nav {
  height: 83px;
  img {
    width: 375px;
    border-radius: 8px 8px 0px 0px;
  }
}
.iphone {
  width: 375px;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;
  img {
    width: 375px;
  }
}
.gameTitle {
  font-size: 17px;
  position: sticky;
  color: #000000;
  font-weight: 600;
  z-index: 101;
  top: 82px;
  width: 100%;
  height: 20px;
  display: flex;
  justify-content: center;
}
.braImg {
  position: fixed;
  z-index: 100;
  top: 76px;
}
.rightForm {
  padding: 30px 20px 0 20px;
  box-sizing: border-box;
  width: calc(100vw - 520px);
  height: calc(100vh - 108px);
  background: #ffffff;
  .formContent {
    margin-top: 20px;
    overflow-y: auto;
    height: calc(100% - 66px);
  }
}
</style>
