<template>
  <div class="container wash-car-page">
    <div class="poster-panel" :style="{'background-image':bgimg  }">
      <div>
        <div class="share-user-panel">
          <img :src="shareUser.headImageUrl" class="share-user-img">
        </div>
        <div class="poster-desc">
          {{shareUser.nickName || '丘比养车'}}邀请您{{info.title}}
        </div>
        <div class="receive-btn">
          <van-button v-if="!isLogin" round block type="danger" size="small" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">立即领取</van-button>
          <van-button v-if="isLogin" round block type="danger" size="small" @click="toGrantCoupon">立即领取</van-button>
        </div>
        <div>
          点击立即领取 <span class="import-text">{{info.title}}</span>
        </div>
        <div class="remarks-text">
          {{info.detail}}
        </div>
      </div>
    </div>
    <div class="rule-panel">
      <div class="rule-info">
        <div class="art-title">活动规则说明 {{shareData}}</div>
        <div v-for="(remark, index) in info.remarks" :key="index" class="remark-row">
          {{remark}}
        </div>
      </div>
    </div>
    <van-popup :show="sucPopupStatus">
      <div class="popup-panel">
        <div class="popup-bar">
          <van-icon name="cross" @click="closeSucPopup" />
        </div>
        <div class="popup-content">
          <div class="status-icon">
            <van-icon name="passed" size="3.5em" color="#19be6b" />
          </div>
          恭喜您成功领取9.9元秒杀券, <br />
          已经入您 {{userPhone}}账户
          <p class="warning-text">此券请在 {{expiryDate}} 之前使用</p>
        </div>
        <div class="popup-btn">
          <van-button size="small" round block type="danger" @click="toUseCoupon">立即使用</van-button>
        </div>

      </div>
    </van-popup>
    <van-popup :show="failPopupStatus">
      <div class="popup-panel">
        <div class="popup-bar">
          <van-icon name="cross" @click="closeFailPopup" />
        </div>
        <div class="popup-content">
          <div class="status-icon">
            <van-icon name="info-o" size="3.5em" color="#ff9900" />
          </div>
          您已经领取过9.9 秒杀券了,<br /> 不能重复领取
        </div>
        <div class="popup-btn">
          <van-button size="small" round block plain @click="toShare">邀请更多好友获取9.9元秒杀券</van-button>
        </div>

      </div>
    </van-popup>
     <van-popup :show="otherPopupStatus">
      <div class="popup-panel">
        <div class="popup-bar">
          <van-icon name="cross" @click="closeOtherPopup" />
        </div>
        <div class="popup-content">
          <div class="status-icon">
            <van-icon name="info-o" size="3.5em" color="#ff9900" />
          </div>
          您已经领取过9.9 秒杀券了,<br /> 不能重复领取
          <div v-if="status === 'UNPA'||status === 'unused'">
             <p class="warning-text">此券请在 {{expiryDate}} 之前使用</p>
          </div>
        </div>
        <div class="popup-btn">
          <!-- <van-button size="small" round block plain @click="toShare">邀请更多好友获取15元洗车</van-button> -->
          <van-button size="small" round block plain v-if="status === 'unused'" @click="toUseCoupon">立即使用</van-button>
          <van-button size="small" round block plain v-if="status === 'exceed'" @click="toExceed">查看详情</van-button>
          <van-button size="small" round block plain v-if="status === 'PAED'" @click="toPAED">查看详情</van-button>
          <van-button size="small" round block plain v-if="status === 'UNPA'" @click="toUsed">立即使用</van-button>
        </div>

      </div>
    </van-popup>

  </div>
</template>

<script>
/** saveCode, */
import { code2Session, zyycLogin, getShareUser, grantCoupon, checkLogin } from '@/api/login';
import { getCouponPageData } from '@/api/api';
import { formatTime } from '@/utils/index';
export default {
  name: 'activity',

  data() {
    return {
      uid: null,
      isLogin: false,
      sucPopupStatus: false,
      failPopupStatus: false,
      shareUser: {
        headImageUrl: 'https://zyyc.oss-cn-beijing.aliyuncs.com/shop_mini/icons/logo.png'
      },
      shareUserId: '',
      userPhone: '',
      expiryDate: '',
      bundleLimitList: [],
      info: {},
      otherPopupStatus: false,
      bundId: '',
      couponId: '',
      orderBundleId: '',
      customerCouponId: '',
      status: '' // exceed 过期
    };
  },
  computed: {
    bgimg() {
      if (this.info.backgroundPic) {
        return `url(${this.info.backgroundPic})`;
      } else {
        return '';
      }
    }
  },
  methods: {
    toUseCoupon() {
      console.log('toUseCoupon-------')
      console.log(this.bundId)
      console.log(this.couponId)
      if (this.bundId && this.couponId) {
        wx.navigateTo({
          // url: `/pages/bundleDetail/main?id=${this.bundleLimitList[0].bundId}`
          url: `/pages/placeOrder/main?id=${this.bundId}&couponId=${this.couponId}&customerCouponId=${this.customerCouponId}`
        });
      } else {
        wx.reLaunch({ url: '/pages/bundle/main' });
      }
    },
    toExceed() {
      // 过期
      wx.navigateTo({
        url: `/pages/couponList/main?tab=2`
      });
    },
    toPAED() {
      wx.navigateTo({
        url: `/pages/couponList/main?tab=1`
      });
    },
    toShare() {
      wx.navigateTo({
        url: `/pages/shareActivity/main`
      });
    },
    toUsed() {
      wx.navigateTo({
        url: `/pages/orderDetail/main?id=${this.orderBundleId}`
      });
    },
    getPhoneNumber(e) {
      const _this = this;
      if (e.target.errMsg === 'getPhoneNumber:ok') {
        wx.showLoading({
          mask: true,
          title: '加载中'
        });
        zyycLogin({
          openid: wx.getStorageSync('openid'),
          encryptedData: e.target.encryptedData,
          iv: e.target.iv
        }).then(res => {
          wx.hideLoading();
          if (res.status === '200') {
            wx.setStorageSync('token', res.data.token);
            wx.setStorageSync('phone', res.data.phone);
            wx.setStorageSync('userId', res.data.userId);
            wx.removeStorageSync('openid');
            _this.userPhone = res.data.phone;
            // 调用领取优惠券后台服务
            _this.toGrantCoupon();
            _this.isLogin = true;
          }
        });
      } else {
        wx.showToast({
          title: '您没有授权, 无法领取优惠券',
          icon: 'none',
          duration: 2500
        });
      }
    },
    toGrantCoupon() {
      const _this = this;
      const _data = {
        couponId: '900009'
      };
      if (_this.shareUserId) {
        _data.inviterId = _this.shareUserId;
      }
      wx.showLoading({
        mask: true,
        title: '加载中'
      });
      grantCoupon(_data).then(res2 => {
        console.log(res2,'grantCoupon-----')
        wx.hideLoading();
        if (res2.status === '200') {
          _this.userPhone = wx.getStorageSync('phone');
          _this.sucPopupStatus = true;
          _this.failPopupStatus = false;
          if (res2.data.expiryDate) {
            const _data = formatTime(res2.data.expiryDate);
            _this.expiryDate = `${_data.year}-${_data.month}-${_data.day} ${_data.hour}:${_data.minute}`;
          }
          // this.bundleLimitList = res2.data.bundleLimitList;
          _this.couponId = res2.data.couponId;
          _this.bundId = res2.data.bundleLimitList[0].bundId;
          _this.customerCouponId = res2.data.id;
        } else if (res2.status === 'COUP_0030') {
          if (res2.data) {
            // 过期
            // res2.data.status = '0';
            if (res2.data.status + '' === '0') {
              _this.otherPopupStatus = true;
              _this.status = 'exceed';
            } else if (res2.data.orderFlag === 'UNPA') {
            // 已使用，未支付
              _this.orderBundleId = res2.data.id;
              _this.otherPopupStatus = true;
              _this.status = 'UNPA';
              if (res2.data.expiryDate) {
                const _data = formatTime(res2.data.expiryDate);
                _this.expiryDate = `${_data.year}-${_data.month}-${_data.day} ${_data.hour}:${_data.minute}`;
              }
            } else if (res2.data.orderFlag === 'PAED') {
            // 已经支付
              _this.otherPopupStatus = true;
              _this.status = 'PAED';
            } else {
              // 未使用
              _this.status = 'unused';
              _this.otherPopupStatus = true;
              _this.couponId = res2.data.couponId;
              _this.bundId = res2.data.bundleLimitList[0].bundId;
              _this.customerCouponId = res2.data.id;
              if (res2.data.expiryDate) {
                const _data = formatTime(res2.data.expiryDate);
                _this.expiryDate = `${_data.year}-${_data.month}-${_data.day} ${_data.hour}:${_data.minute}`;
              }
            };
          } else {
            _this.sucPopupStatus = false;
            _this.failPopupStatus = true;
          }
        } else {
          wx.showToast({
            title: res2.message,
            icon: 'none',
            duration: 1500
          });
        }
      });
    },
    // 获取邀请人信息
    getShareUserInfo(uid){
      if(uid){
        this.shareUserId = uid;
        getShareUser({
          userId: uid
        }).then(res => {
          this.shareUser = res.data;
        });
      }else{
        this.shareUser = {
          headImageUrl: 'https://zyyc.oss-cn-beijing.aliyuncs.com/shop_mini/icons/logo.png'
        }
      }
    },
    closeSucPopup() {
      this.sucPopupStatus = false;
    },
    closeOtherPopup() {
      this.otherPopupStatus = false;
    },
    closeFailPopup() {
      this.failPopupStatus = false;
    }
  },
  onShow() {
    this.otherPopupStatus = false;
    this.sucPopupStatus = false;
    this.failPopupStatus = false;
    const _this = this;
    checkLogin().then(res => {
      if (res.status === '200') {
        // 调用领取优惠券后台服务
        _this.isLogin = true;
      } else {
        _this.isLogin = false;
        wx.login({
          success(result) {
            if (result.code) {
              code2Session({
                code: result.code
              }).then(res => {
                if (res.status === '200') {
                  wx.setStorageSync('openid', res.data);
                };
              });
            }
          }
        });
      }
    });
  },
  onLoad(options) {
    console.log(options,'options')
    let uid = null
    // 扫描二维码打开的
    if (options.q) {
      let scene = decodeURIComponent(options.q);
      let id = scene.split('?')[1]
      uid = id.split('=')[1]
    }
    // 点击转发连接打开的
    if (options.uid){
      this.uid = options.uid
      uid = options.uid
    }
    console.log(uid,'uid')
    this.getShareUserInfo(uid)

    // 设置标题
    wx.setNavigationBarTitle({
        title: options.title ? options.title : '车领主'
    })

    // 获取优惠卷信息
    wx.showLoading({
      mask: true,
      title: '加载中'
    });
    this.otherPopupStatus = false;
    getCouponPageData().then(res => {
      if (res.status === '200') {
        wx.hideLoading();
        const result = res.data.filter(item => Math.round(item.couponId) === 900009);
        if (result && result.length > 0) {
          let info = result[0];

          info.remarks = info.remarks.split('$$');
          this.info = info;
        }
      }
    });
  },
  onShareAppMessage: function () {

  }
};
</script>

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

.wash-car-page {
  .poster-panel {
    height: 55vh;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    text-align: center;
    color: #fff;
    font-size: 28rpx;
    > div{
      padding: 30rpx 20rpx;
    }
    .share-user-panel {
      text-align: center;
    }

    .share-user-img {
      width: 52px;
      height: 52px;
      border-radius: 50%;
      text-align: center;
    }

    .poster-desc {
      font-size: 28rpx;
    }

    .receive-btn {
      padding: 0.5em 35%;
      font-size: 28rpx;
    }

    .import-text {
      color: yellow;
    }

    .remarks-text {
      font-size: 28rpx;
    }
  }

  .rule-panel {
    min-height: 45vh;
    box-sizing: border-box;
    padding: 1em;

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

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

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

      .art-title {
        color: #17233d;
        padding-bottom: 1.5em;
        font-size: 1.2em;
        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;
      }
    }
  }

  .popup-panel {
    width: 70vw;
    padding: 20rpx 25rpx 40rpx 25rpx;
    text-align: center;

    .status-icon {
      margin-bottom: 0.2em;
    }

    .popup-bar {
      text-align: right;
    }

    .warning-text {
      font-size: 0.8em;
      padding-top: 1em;
      color: #f44;
    }

    .popup-content {
      font-size: 0.95em;
    }

    .popup-btn {
      margin-top: 1em;
      padding: 0 20%;
    }
  }
}
.text-red {
  font-size: 0.8em;
  color: #ed3f14;
}
</style>
