<template>
  <div class="partake-challenge-page">
    <Title class="page-title" title="　" v-on:goback="goback" show_back="true" v-if="currentPage()==='PartakeChallenge'"></Title>
    <!-- 每日运动打卡耐力赛 -->
    <div class="game-partake-container">
      <div class="game-partake-title">每日运动打卡耐力赛</div>
      <div class="game-choose-section">
        <div class="choose-title">每日达标</div>
        <div class="choose-content">
          <div v-for="(item, index) in partakeStepList" :class="['choose-option', index===partakeStepIndex?'check':'']" @click="chooseAttribute('partakeStepIndex', index)" :key ="index">{{item.step}}步</div>
        </div>
      </div>
      <div class="game-choose-section">
        <div class="choose-title">挑战天数</div>
        <div class="choose-content">
          <div v-for="(item, index) in partakeDayList" :class="['choose-option', index===partakeDayIndex?'check':'']" @click="chooseAttribute('partakeDayIndex', index)" :key ="index">{{item.days}}天</div>
        </div>
      </div>
      <div class="game-choose-section">
        <div class="choose-title">每日契约金</div>
        <div class="choose-content">
          <div v-for="(item, index) in partakeMoneyList" :class="['choose-option', index===partakeMoneyIndex?'check':'']" @click="chooseAttribute('partakeMoneyIndex', index)" :key ="index">{{item.money}}元</div>
        </div>
      </div>
      <div class="game-total-fee-container">
        <div class="game-fee-section">
          <div class="game-fee-title">需支付金额(元)</div>
          <div class="game-fee-amount">{{payMoney|moneyFormatter}}</div>
        </div>
        <div class="game-fee-section">
          <div class="game-fee-title">预计收益(元)</div>
          <div class="game-fee-amount">{{preMinMoney|moneyFormatter}}-{{preMaxMoney|moneyFormatter}}</div>
        </div>
      </div>
      <div class="game-partake-time">比赛时间：{{startTime}} 00:00 — {{endTime}} 24:00</div>
      <div class="game-partake-btn" @click="payToSign()">立即报名</div>
      <div class="game-auth-container" @click="bindArgeement()">
        <img class="auth-checked" src="../images/PartakeChallenge/ic_choose.png" v-if="argeement">
        <div class="auth-uncheck" v-else></div>
        <div class="text1">我同意</div>
        <div class="text2" @click.stop="goOtherPage('Rule')">《步数打卡的挑战规则协议》</div>
      </div>
    </div>
    <!-- 3步赚取运动奖励金 -->
    <div class="game-introduce-container" :style="currentPage()!=='PartakeChallenge'?'margin-bottom: 1.4rem;':''">
      <div class="game-introduce-title">
        <img src="../images/PartakeChallenge/ic_3.png">
        步赚取运动奖励金
      </div>
      <div class="game-introduce-section">
        <img class="section-icon" src="../images/PartakeChallenge/q1.png">
        <div class="section-content">
          <div class="content-title">报名参赛</div>
          <div class="content-text">支付{{payMoney|moneyFormatter}}元运动契约金，即可加入{{partakeStepList.length&&partakeStepList[partakeStepIndex].step}}步日耐力赛，契约金平均分配到每个比赛日，每日结算1次。</div>
        </div>
      </div>
      <div class="game-introduce-section">
        <img class="section-icon" src="../images/PartakeChallenge/q2.png">
        <div class="section-content">
          <div class="content-title">运动达标</div>
          <div class="content-text">每日走满{{partakeStepList.length&&partakeStepList[partakeStepIndex].step}}步即可达标，获得当日奖励资格；</div>
          <div class="content-text">未达标的用户将失去后续比赛的参赛资格，平台将没收用户后续天数的契约金。</div>
        </div>
      </div>
      <div class="game-introduce-section">
        <img class="section-icon" src="../images/PartakeChallenge/q3.png">
        <div class="section-content">
          <div class="content-title">获得奖励</div>
          <div class="content-text">次日结算前日比赛，达标者将获得对应奖励金；总奖励金为用户每日达标奖金之和。</div>
        </div>
      </div>
    </div>
    <!-- 支付失败弹框 -->
    <PayFailModal v-if="isShowPayFail" @close="togglePayFail()"></PayFailModal>
    <!-- 通用弹框 -->
    <div class="modal" v-if="modalShown">
      <Modal v-on:close="closeModal" v-on:confirmModal="confirmModal" v-bind:title="modalTitle" v-bind:desc="modalDesc" :option="modalOption"></Modal>
    </div>
    <!-- 没有关注公众号弹窗 -->
    <div class="game-auth-popup" v-if="needFollow">
      <div class="game-auth-container">
        <img class="bg-img" src="../images/common/focus_gzh.png">
        <img class="close-btn" src="../images/common/pop_ic_close.png" @click="closePopup()">
      </div>
    </div>
  </div>
</template>

<script>
import Title from "@/components/Title.vue";
import PayFailModal from "@/components/PayFailModal.vue";
import Modal from "@/components/Modal.vue";
import { daka_info,select_follow } from "@/components/axios/api";
import { dakaPay } from "@/components/axios/api";

export default {
  name: "PartakeChallenge",
  components: {
    Title,
    PayFailModal,
    Modal
  },
  data() {
    return {
      isShowPayFail: false,
      modalTitle: "",
      modalDesc: "",
      modalShown: false,
      argeement: true,
      startTime: '',
      endTime: '',
      partakeStepList: [],
      partakeStepIndex: 0,
      partakeDayList: [],
      partakeDayIndex: 0,
      partakeMoneyList: [],
      partakeMoneyIndex: 0,
      payMoney: 0,
      preMinMoney: 0,
      preMaxRate: 0,
      preMaxMoney: 0,
      startTimeStamp: 0,
      followInfo: {},
      needFollow: false
    };
  },
  created() {
    this.getPageData();
    this.getFollowInfo()
    // let followInfo = sessionStorage.getItem('followInfo')
    // if(followInfo){
    //   this.followInfo = JSON.parse(followInfo)
    // }
  },
  methods: {
    getFollowInfo() {
      select_follow().then(res => {
        console.log(res);
        if (res.code == 0) {
          this.followInfo = res.data
          // sessionStorage.setItem('followInfo',JSON.stringify(res.data))
        }
      });
    },
    // 加载页面数据
    getPageData() {
      daka_info().then(res => {
        const resData = res.data;
        if (res.code === 0) {
          this.startTimeStamp = resData.period;
          this.partakeStepList = resData.config.step;
          this.partakeDayList = resData.config.days;
          this.partakeMoneyList = resData.config.money;
          this.preMaxRate = resData.bet_rate;
          // 计算格式化开始日期
          const startDate = new Date(this.startTimeStamp * 1000);
          this.startTime = (startDate.getMonth() + 1) + '月' + startDate.getDate() + '日';
          this.calcMoney();
          this.calcDate();
        }
      });
    },
    // 选择参赛信息
    chooseAttribute(type, index) {
      this[type] = index;
      this.calcMoney();
      if (type === 'partakeDayIndex') {
        this.calcDate();
      }
    },
    // 计算金额和收益
    calcMoney() {
      this.payMoney = this.partakeDayList[this.partakeDayIndex].days * this.partakeMoneyList[this.partakeMoneyIndex].money;
      this.preMinMoney = this.payMoney * (((this.partakeStepList[this.partakeStepIndex].rate1 + this.partakeDayList[this.partakeDayIndex].rate1 + this.partakeMoneyList[this.partakeMoneyIndex].rate1) / 100) + 1);
      this.preMaxMoney = this.payMoney * (this.preMaxRate + 1);
    },
    // 计算格式化结束日期
    calcDate() {
      const endDate = new Date(this.startTimeStamp * 1000 + (86400000 * (this.partakeDayList[this.partakeDayIndex].days - 1)));
      this.endTime = (endDate.getMonth() + 1) + '月' + endDate.getDate() + '日';
    },
    // 返回上一页
    goback() {
      history.go(-1);
    },
    // 页面跳转
    goOtherPage(pageName) {
      this.$router.push({ name: pageName });
    },
    // 当前页面是否是tabbar页
    currentPage() {
      return this.$router.history.current.name;
    },
    // 弹框
    togglePayFail() {
      this.isShowPayFail = !this.isShowPayFail;
    },
    // 立即报名
    payToSign() {
      if(!this.followInfo.follow){
        this.needFollow = true
        return 
      } 
      if (!this.argeement) {
        return this.showModal("温馨提示", "请先同意协议");
      }
      let nextGame = 0;
      if (this.$route.query.nextGame) {
        nextGame = 2;
      }
      const paramStep = this.partakeStepList[this.partakeStepIndex].step;
      const paramDay = this.partakeDayList[this.partakeDayIndex].days;
      const paramMoney = this.partakeMoneyList[this.partakeMoneyIndex].money;
      dakaPay(paramStep, paramDay, paramMoney, nextGame).then(response => {
        if (response.code == 1) {
          return this.showModal("温馨提示", response.msg);
        }
        const result = response.data;
        if (result) {
          WeixinJSBridge.invoke(
            "getBrandWCPayRequest",
            {
              appId: result.appId, //公众号名称，由商户传入
              timeStamp: result.timeStamp, //时间戳，自1970年以来的秒数
              nonceStr: result.nonceStr, //随机串
              package: result.package,
              signType: result.signType, //微信签名方式：
              paySign: result.paySign //微信签名
            },
            res => {
              console.log("支付调用结果", res);
              if (res.err_msg === "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示：
                // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                // 支付成功后的回调函数
                console.log("支付成功");
                sessionStorage.setItem("userHaveJoinGame", "true");
                sessionStorage.setItem("userHavePaidGame", "true");
                this.$router.push({ name: "HaveJoinedGame" });
              } else if (res.err_msg === "get_brand_wcpay_request:fail" || res.err_msg === "get_brand_wcpay_request:cancel") {
                // 支付服务繁忙，请稍后重试 || 支付取消
                this.togglePayFail();
              }
            }
          );
        }
      });
    },
    // 弹窗
    showModal(title, desc, option) {
      this.modalTitle = title || "";
      this.modalDesc = desc || "";
      this.modalOption = option || {};
      this.modalShown = true;
    },
    // 弹窗
    closeModal() {
      this.modalShown = false;
    },
    // 弹窗
    confirmModal(scb) {
      scb && scb();
      this.modalShown = false;
    },
    // 同意规则协议
    bindArgeement() {
      this.argeement = !this.argeement;
    },
    
    closePopup() {
        this.needFollow = false;
    },
  },
  filters: {
    moneyFormatter(val) {
      if (val && !isNaN(val)) {
        return Number(val).toFixed(2);
      } else {
        return "0.00";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.partake-challenge-page {
  min-height: 100vh;
  background-color: rgb(70, 88, 149);
  background-image: url(../images/SignUp/sy_beijing.png);
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: center top;
  display: flex;
  flex-direction: column;
  align-items: center;
  .page-title {
    position: fixed;
    left: 0;
    top: 0;
  }
  .game-partake-container {
    width: 7.1rem;
    border-radius: 0.08rem;
    padding: 0.3rem 0 0.4rem;
    box-sizing: border-box;
    background: #fff;
    margin-top: 1.96rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    .game-partake-title {
      font-size: .36rem;
      line-height: 1;
      color: #333;
      font-weight: bold;
      margin-bottom: .1rem;
    }
    .game-choose-section {
      width: 6.3rem;
      padding: .3rem 0;
      box-sizing: border-box;
      border-top: .01rem solid #ccc;
      display: flex;
      align-items: center;
      &:nth-child(2) {
        border-top: none;
      }
      .choose-title {
        font-size: .3rem;
        line-height: 1;
        color: #333;
        flex: 1;
      }
      .choose-content {
        width: 4.6rem;
        flex-shrink: 0;
        display: flex;
        .choose-option {
          flex: 1;
          height: .54rem;
          font-size: .3rem;
          line-height: .54rem;
          color: #888;
          text-align: center;
          border: .01rem solid #888;
          box-sizing: border-box;
          margin-left: .2rem;
          &:first-child {
            margin-left: 0;
          }
          &.check {
            background: #07C9D1;
            border-color: #07C9D1;
            color: #fff;
          }
        }
      }
    }
    .game-total-fee-container {
      background: rgba(250, 189, 33,.04);
      border: .01rem solid #FFCE51;
      margin-top: .1rem;
      display: flex;
      .game-fee-section {
        width: 3rem;
        padding: .4rem 0;
        box-sizing: border-box;
        text-align: center;
        .game-fee-title {
          font-size: .26rem;
          line-height: 1;
          color: #A5A5A5;
        }
        .game-fee-amount {
          font-size: .42rem;
          line-height: .8;
          color: #FABD21;
          margin-top: .2rem;
        }
      }
    }
    .game-partake-time {
      font-size: .24rem;
      line-height: 1;
      color: #5A5A5A;
      margin-top: .4rem;
    }
    .game-partake-btn {
      width: 5.6rem;
      height: 0.88rem;
      border-radius: 0.88rem;
      background: #fabd21;
      font-size: 0.36rem;
      line-height: 0.88rem;
      color: #fff;
      font-weight: bold;
      text-align: center;
      margin-top: .2rem;
    }
    .game-auth-container {
      margin-top: 0.2rem;
      display: flex;
      align-items: center;
      .auth-checked {
        width: 0.24rem;
        height: 0.24rem;
      }
      .auth-uncheck {
        width: 0.24rem;
        height: 0.24rem;
        border: 0.01rem solid #bfbfbf;
        box-sizing: border-box;
        border-radius: 50%;
      }
      .text1 {
        font-size: 0.24rem;
        line-height: 1;
        color: #999;
        margin-left: .1rem;
      }
      .text2 {
        font-size: 0.24rem;
        line-height: 1;
        color: #576b95;
      }
    }
  }
  .game-introduce-container {
    width: 7.1rem;
    border-radius: 0.08rem;
    padding: 0.36rem 0.28rem 0.3rem;
    box-sizing: border-box;
    background: #fff;
    margin: .2rem 0 .4rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    .game-introduce-title {
      display: flex;
      align-items: flex-end;
      font-size: 0.3rem;
      line-height: 1;
      color: #333;
      margin-bottom: 0.24rem;
      flex-shrink: 0;
      img {
        width: 0.26rem;
        height: 0.35rem;
        margin-right: 0.08rem;
      }
    }
    .game-introduce-section {
      width: 100%;
      margin-top: 0.34rem;
      display: flex;
      align-items: flex-start;
      flex-shrink: 0;
      &:last-of-type .section-content {
        border-bottom: none;
      }
      .section-icon {
        width: 0.8rem;
        height: 0.8rem;
        flex-shrink: 0;
        margin-right: 0.3rem;
      }
      .section-content {
        flex: 1;
        border-bottom: 0.01rem solid #e5e5e5;
        .content-title {
          font-size: 0.3rem;
          line-height: 1;
          color: #333;
        }
        .content-text {
          font-size: 0.24rem;
          line-height: 0.36rem;
          color: #999;
          margin: 0.16rem 0 0.14rem;
        }
      }
    }
  }
}
.game-auth-popup {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 998;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  .game-auth-container {
    border-radius: 0.08rem;
    padding-bottom: 0.4rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    .bg-img {
      width: 6.4rem;
      height: 7.08rem;
      display: block;
    }
    .close-btn {
      width: 0.58rem;
      height: 0.58rem;
      position: absolute;
      top: -.88rem;
      right: 0
    }
  }
}
</style>
