<template>
  <div class="container share-activity-page">
    <div class="poster-panel" :style="{'background-image':bgimg  }"></div>

    <div class="info-panel">
      <div class="title">{{info.detail}}</div>
      <div class="info-text">
        TA 得9.9元秒杀券 <span class="red-text">{{info.title}}</span>
      </div>
      <div class="invite-btn">
        <div>
          <van-button v-if="isLogin&&isUserinfo" round block type="danger" size="small" open-type="share">分享给好友</van-button>
          <van-button v-if="!isLogin||!isUserinfo" round block type="danger" size="small" @click="setAuth()">分享给好友</van-button>
        </div>
        <div>
          <van-button v-if="isLogin&&isUserinfo" round block type="info" size="small" @click="creatShareImage()">分享到朋友圈</van-button>
          <van-button v-if="!isLogin||!isUserinfo" round block type="info" size="small" @click="setAuth()">分享到朋友圈</van-button>
        </div>
      </div>
    </div>
    <div class="coupon-panel" v-if="coupons.length">
      <div class="art-title">我的奖励</div>

      <div class="coupon" v-for="coupon in coupons" :key="coupon.id" :class="{'nuse': coupon.status === '0' , 'paed': coupon.status === '2'}">
        <div class="coupen--status">
          {{coupon.tag}}
        </div>
        <div class="coupen_content">
          <div class="left">
            <div class="title">{{coupon.name}}</div>
            <div class="desc">有效期至{{coupon.expiryDate}}</div>
          </div>
          <div class="right" @click="couponClickHandle(coupon)">
            {{coupon.btnText}}
          </div>
        </div>
      </div>
    </div>
    <div class="rule-panel">
      <div class="rule-info">
        <div class="art-title">活动规则说明</div>
        <div v-for="(remark, index) in info.remarks" :key="index" class="remark-row">
          {{remark}}
        </div>
      </div>
    </div>
    <van-dialog :show="authUser" confirm-button-open-type="getUserInfo" transition="none" confirmButtonText="确认授权" @getuserinfo="onGotUserInfo" message="为了方便领取9.9元秒杀券, 我们需要您得用户信息">
      <div></div>
    </van-dialog>
    <van-dialog :show="authPhone" confirm-button-open-type="getPhoneNumber" transition="none" confirmButtonText="确认授权" @getphonenumber="getPhoneNumber" message="为了方便领取9.9元秒杀券, 我们需要您得手机号码">
      <div></div>
    </van-dialog>
  </div>
</template>

<script>
/**
 * getPhone
 */
import { getUserInfo, zyycLogin, code2Session, checkLogin } from '@/api/login';
import { getCouponPageData, get15CouponList } from '@/api/api';
import { formatTime } from '@/utils/index';
export default {
  name: 'washCar',
  data() {
    return {
      authUser: false,
      authPhone: false,
      isLogin: false,
      isUserinfo: false,
      userName: '丘比养车',
      userId: '',
      coupons: [],
      info: {}
    };
  },
  computed: {
    bgimg() {
      if (this.info.backgroundPic) {
        return `url(${this.info.backgroundPic})`;
      } else {
        return '';
      }
    }
  },
  methods: {
    setAuth(e) {
      if (!this.isLogin) {
        this.authPhone = true;
      } else {
        if (!this.isUserinfo) {
          this.authUser = true;
        }
      }
    },
    // 生成美图
    creatShareImage (){
      wx.navigateTo({
        url: `/pages/pagesA/creatShareImage/main`
      });
    },
    couponClickHandle(item) {
      if (item.status === '1') {
        wx.navigateTo({
          url: `/pages/placeOrder/main?id=${item.bundId}&couponId=${item.couponId}&customerCouponId=${item.id}`
        });
      } else if (item.status === '2' || item.status === '3') {
        wx.navigateTo({
          url: `/pages/orderDetail/main?id=${item.orderBundleId}`
        });
      }
    },
    getCouponList() {
      get15CouponList().then(res => {
        console.log(res,'奖励')
        if (res.status == '200') {
          const dict = {
            '1': ['未使用', '去使用'],
            '2': ['已使用', '去查看'],
            '3': ['已冻结', '去查看'],
            '0': ['已过期', '过期啦']
          };
          if (res.data) {
            let temp = []
            res.data.map(item => {
              let _date = formatTime(item.expiryDate);
              temp.push({
                id: item.id,
                name: item.coupon.name,
                desc: item.coupon.typeName,
                nuse: item.status === '1',
                bundId: item.bundleLimitList[0].bundId,
                tag: dict[item.status][0],
                btnText: dict[item.status][1],
                status: item.status,
                expiryDate: `${_date.year}年${_date.month}月${_date.day}日 ${_date.hour}:${_date.minute}`,
                orderBundleId: item.orderBundleId,
                couponId: item.couponId
              });
            });
            console.log(temp,'00000')
            this.coupons = temp
          }else{
            this.coupons = []
          }
        }
      });
    },
    onGotUserInfo(e) {
      this.authUser = false; // 打开微信授权页面后，关闭弹窗
      if (e.target.errMsg === 'getUserInfo:ok') {
        this.authUser = false;
        this.userName = e.target.userInfo.nickName;
        this.getCurrentUser(e.target);
      } else {
        wx.showToast({
          title: '您没有授权, 无法领取9.9元秒杀券',
          icon: 'none',
          duration: 2500
        });
      }
    },
    getPhoneNumber(e) {
      this.authPhone = false;// 打开微信授权页面后，关闭弹窗
      const _this = this;
      if (e.target.errMsg === 'getPhoneNumber:ok') {
        zyycLogin({
          openid: wx.getStorageSync('openid'),
          encryptedData: e.target.encryptedData,
          iv: e.target.iv
        }).then(res => {
          if (res.status === '200') {
            _this.isLogin = true;
            wx.setStorageSync('token', res.data.token);
            wx.setStorageSync('phone', res.data.phone);
            wx.setStorageSync('userId', res.data.userId);
            wx.removeStorageSync('openid');
            _this.getUserInfoStatus();
            _this.getCouponList();
          }
        });
      } else {
        wx.showToast({
          title: '您没有授权, 无法领取9.9元秒杀券',
          icon: 'none',
          duration: 1500,
          complete: function() {
            _this.getUserInfoStatus();
          }
        });
      }
    },
    getCurrentUser(info) {
      this.isUserinfo = true;
      if (this.isLogin) { // 登录情况下，更新用户微信信息
        getUserInfo(info).then(res => {
          if (res.status === '200') {
            this.userId = res.data;
            this.authUser = false;
          }
        });
      }
    },
    getUserInfoStatus() {
      const _this = this;
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function(res) {
                _this.userName = res.userInfo.nickName;
                _this.getCurrentUser(res);
              }
            });
          } else {
            _this.authUser = true;
          }
        }
      });
    }
  },
  onShareAppMessage() {
    if (!this.isLogin) {
      this.authPhone = true;
    } else {
      const { userName, userId } = this;
      if(!userId||userId==''){
        this.authUser = true;
      }else{
        let result = {
          title: `${userName}邀请您领取9.9元秒杀券`,
          path: '/pages/washCar/main?uid=' + userId,
          success: function(res) {
            wx.showToast({
              title: '分享成功了',
              icon: 'none',
              duration: 2500
            });
          }
        };
        if (this.info.backgroundPic) {
          result.imageUrl = this.info.backgroundPic;
        }
        return result;
      }
    }
  },
  onShow: function() {
    this.authUser = false;
    this.authPhone = false;
    this.isUserinfo = false;
    this.isLogin = false;
    const _this = this;
    checkLogin().then(res => {
      if (res.status === '200') {
        _this.getUserInfoStatus();
        _this.getCouponList();
        _this.isLogin = true;
      } else {
        _this.authPhone = true;
        wx.login({
          success(result) {
            if (result.code) {
              code2Session({
                code: result.code
              }).then(res => {
                wx.hideLoading();
                if (res.status === '200') {
                  wx.setStorageSync('openid', res.data);
                };
              });
            }
          }
        });
      }
    });
  },
  onLoad: function(options) {
    wx.setNavigationBarTitle({
          title: options.title
    })
    wx.showLoading({
      mask: true,
      title: '加载中'
    });
    getCouponPageData().then(res => {
      wx.hideLoading();
      if (res.status === '200') {
        const result = res.data.filter(item => Math.round(item.couponId) === 900015);
        if (result && result.length > 0) {
          let info = result[0];
          info.remarks = info.remarks.split('$$');
          this.info = info;
        }
      }
    });
  }
};
</script>

<style lang="stylus">
.container {
  height: 100%;
  overflow: hidden;
}

.share-activity-page {
  .poster-panel {
    height: 72vw;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    text-align: center;
    color: #fff;
  }

  .info-panel {
    text-align: center;
    border: 2rpx solid #dcdee2;
    margin: 1em;
    padding: 1em 0;

    .info-text {
      padding: 20rpx 0;
      font-size: 0.8em;
    }

    .red-text {
      color: #f44;
    }

    .invite-btn {
      text-align: 'center';
      padding: 0 15%;
      display: flex;
      > div{
        width:50%;
        padding: 0 2%;
        font-size: 1em;
      }
    }
  }

  .coupon-panel {
    border: 2rpx solid #dcdee2;
    margin: 1em;
    padding: 1.2em;
    color: #515a6e;

    .coupen_content {
      display: flex;
      align-items: stretch;
      width: 100%;
    }

    .left, .right {
      display: flex;
      justify-content: center;
      align-items: center;
      padding-top: 12px;
      padding-bottom: 12px;
    }

    .coupon {
      position: relative;
      overflow: hidden;
      border-radius: 0.5em;
    }
    .coupon + .coupon{
      margin-top: 10px;
    }

    .coupen--status {
      font-size: 0.6em;
      color: #fff;
      position: absolute;
      top: 0.75em;
      left: -1.5em;
      padding-bottom: 1rpx;
      transform: rotate(-45deg);
      background-color: #EF0006;
      width: 6em;
      text-align: center;
    }

    .left {
      flex: 1;
      flex-direction: column;
      background-color: #FBEBBA;

      .title {
        font-size: 1.1em;
        font-weight: bold;
        width: 70%;
        border-bottom: 1px solid #d3d3d3;
        text-align: center;
        padding-bottom: 3px;
        margin-bottom: 3px;
      }

      .desc {
        font-size: 0.7em;
      }
    }

    .right {
      color: #fff;
      padding-right: 20px;
      padding-left: 20px;
      box-sizing: border-box;
      background-color: #EF0006;
    }

    .nuse {
      .right, .coupen--status{
        background-color: #c5c8ce;
      }
    }

    .paed {
      .coupen--status{
        background-color: #c5c8ce;
      }
    }
  }

  .rule-panel {
    box-sizing: border-box;
    padding: 0 1em 1em;

    .rule-info {
      border: 2rpx solid #dcdee2;
      padding: 1.2em;
      color: #515a6e;

      .remark-row {
        font-size: 0.9em;

        &:before {
          content: '●';
          font-size: 0.8em;
          transform: scale(0.8);
        }
      }

      .remark-row + .remark-row {
        margin-top: 5rpx;
      }
    }
  }

  .art-title {
    color: #17233d;
    padding-bottom: 1.5em;
    font-size: 1em;
    text-align: center;
    display: flex;
    box-sizing: border-box;
    align-items: center;
  }

  .art-title:before {
    content: ' ';
    height: 0rpx;
    border-bottom: 1px solid #515a6e;
    flex: 1;
    margin-right: 20px;
    position: relative;
    top: 2rpx;
  }

  .art-title:after {
    content: ' ';
    height: 0rpx;
    border-bottom: 1px solid #515a6e;
    flex: 1;
    margin-left: 20px;
    position: relative;
    top: 2rpx;
  }

  .receive-title {
    padding: 0 10%;
    margin-bottom: 20rpx;
  }
}
</style>
