<template>
  <div>
    <cr-image
      v-if="loading"
      src="@/assets/images/maxMember/skeleton.png"
      width="100%"
      height="auto"
      :show-loading="false"
      :show-error="false"
      class="max-member__skeleton"
    />
    <div
      v-else
      class="max-member"
      :class="{
        'activated-bg': isActivated,
        'activate-bg': (!isInvite && isActivateStart) || isOutDate,
        invite: isInvite
      }"
    >
      <member-title v-if="!isActivated" :sub-title="maxMemDesc" />
      <member-card
        v-if="isInvite || isActivated"
        :is-invite="isInvite"
        :info="memberShowInfo"
        @show-rule="handleShowRule"
      />
      <member-banner :vcc-jump-url="vccJumpUrl" />
      <activate-card
        v-if="!isInvite && (isActivating || isActivateStart || isOutDate)"
        :current-state="currentState"
        :info="activateShowInfo"
        @show-qrcode="handleShowQrcode"
        @update-state="updateState"
      />
      <coupon :coupons="couponsList" :can-pick="canPick" />
      <template v-if="isInvite">
        <member-list :list="openMemberList" />
        <activate-btn @show-qrcode="handleShowQrcode" />
      </template>
      <goods :category="categoryList" :style="bgChangeStyle" :page-name="pageName" />
      <dialog-qrcode v-model="showQrcode" :qrcode="qrcode" />
      <dialog-rule v-model="showRule" :rule="maxMemRule" />
      <dialog-open-success v-if="!isInvite" v-model="showOpenSuccess" />
      <cr-back-top v-if="!isInvite" />
    </div>
  </div>
</template>

<script>
import wx from 'weixin-js-sdk';
import { isWxMp } from '@/service/validation.service';
import { maxMember } from '@/api/member.api';
import localStorageService from '@/service/localStorage.service';
import ActivateCard from './components/activate-card.vue';
import ActivateBtn from './components/activate-btn.vue';
import MemberBanner from './components/banner.vue';
import MemberCard from './components/card.vue';
import Coupon from './components/coupon.vue';
import DialogQrcode from './components/dialog-qrcode.vue';
import DialogRule from './components/dialog-rule.vue';
import DialogOpenSuccess from './components/dialog-open-success.vue';
import Goods from './components/goods.vue';
import MemberList from './components/member-list.vue';
import MemberTitle from './components/title.vue';

// 邀请页、激活页、会员页三个差别不大，通过路由状态进行区分, 状态统一维护为对应的状态码
const INVITAION = -1; // 邀请页
const ACTIVATE = 0; // 授权页
const NO_INVITE = 1; // 授权未邀请
const NO_ADD_WEIXIN = 2; // 已邀请为加微信
const ACTIVATED = 3; // 已激活
const OUT_DATE = 4; // 过期

const pageNameMap = {
  // 用于埋点
  '-1': {
    name: '限时开通页',
    event: 'H5_MaxMemberOpenPageExposure'
  },
  0: {
    name: '限时开通页',
    event: 'H5_MaxMemberOpenPageExposure'
  },
  1: {
    name: '受邀开通页',
    event: 'H5_MaxMemberInvitedOpenPageExposure'
  },
  2: {
    name: '受邀开通页',
    event: 'H5_MaxMemberInvitedOpenPageExposure'
  },
  3: {
    name: 'MAX会员页',
    event: 'H5_MaxMemberPageExposure'
  },
  4: {
    name: 'MAX会员页',
    event: 'H5_MaxMemberPageExposure'
  }
};

// 默认品类，请求接口转化为''
const DEFAULT_CATEGORY = {
  categroyId: '-1',
  categroyName: '推荐'
};

export default {
  components: {
    ActivateCard,
    ActivateBtn,
    MemberBanner,
    MemberCard,
    Coupon,
    DialogQrcode,
    DialogRule,
    DialogOpenSuccess,
    Goods,
    MemberList,
    MemberTitle
  },
  data() {
    return {
      pageName: '', // 用于埋点的页面名称
      inviteInfo: {}, // 邀请接口信息
      memberInfo: {}, // 激活接口信息
      activateInfo: {}, // 会员接口信息
      couponsList: [], // 优惠券
      categoryList: [], // 品类
      currentState: INVITAION, // 当前的状态
      token: localStorageService.get('vccToken'),
      showQrcode: false, // 控制展示二维码
      showRule: false, // 控制展示规则
      showOpenSuccess: false, // 控制开通成功弹框
      maxMemRule: '', // 规则字段
      maxMemDesc: '', // title底部描述
      qrcode: '', // 二维码地址
      loading: true
    };
  },
  computed: {
    // 邀请页
    isInvite() {
      return !!this.$route.meta.invite;
    },
    // 激活页
    isActivateStart() {
      return this.currentState === ACTIVATE;
    },
    // 激活中状态
    isActivating() {
      return this.currentState === NO_INVITE || this.currentState === NO_ADD_WEIXIN;
    },
    // 已激活状态
    isActivated() {
      return this.currentState === ACTIVATED;
    },
    // 已失效状态
    isOutDate() {
      return this.currentState === OUT_DATE;
    },
    // 根据状态控制商品顶部位移
    bgChangeStyle() {
      return {
        marginTop: !this.isInvite && this.currentState > -1 ? '36px' : 0
      };
    },
    // 是否可领取
    canPick() {
      return !this.isInvite && this.isActivated;
    },
    // 已开通list
    openMemberList() {
      const { num, wxNicks: list } = this.inviteInfo;
      return { num, list };
    },
    // 已开通展示信息
    memberShowInfo() {
      const { mobile, exipreDate, avatarUrl } = this.memberInfo;
      return { mobile, exipreDate, avatarUrl };
    },
    // 激活中展示信息
    activateShowInfo() {
      const { mobile, maxMemberStatus, maxMemberStatusDesc } = this.activateInfo;
      return { mobile, maxMemberStatus, maxMemberStatusDesc };
    }
  },
  // watch: {
  // '$route.meta.invite'(val) {
  //   if (!!val !== this.isInvite) {
  //     this.initPageInfo();
  //     this.$forceUpdate();
  //   }
  // }
  // },
  created() {
    // 非邀请页已url中的token为准
    if (!this.isInvite) {
      this.token = this.$route.query.vccToken;
      localStorageService.set('vccToken', this.token || '');
    }
    this.initPageInfo();
  },
  methods: {
    async initPageInfo() {
      // 邀请状态与其他状态区分
      if (this.isInvite || !this.token) {
        await this.getInvitaionInfo();
      } else {
        await this.getActivateInfo();
      }
    },
    async getInvitaionInfo() {
      const [res] = await maxMember.invitaionInfo();
      if (!res) return;
      this.inviteInfo = res;
      this.updateECInfo(this.token ? INVITAION : ACTIVATE);
    },
    async getActivateInfo() {
      const [res] = await maxMember.activateInfo();
      if (!res) return;
      this.activateInfo = res;
      // 如果已激活，获取激活信息
      if (res.maxMemberStatus === ACTIVATED) {
        this.getMemberInfo();
      } else {
        this.updateECInfo(res.maxMemberStatus);
      }
    },
    async getMemberInfo() {
      const [res] = await maxMember.memberInfo();
      if (!res) return;
      this.memberInfo = res;
      if (this.activateInfo.isFristToMaxMem) {
        this.$nextTick(() => {
          this.showOpenSuccess = true;
        });
      }
      this.updateECInfo(ACTIVATED);
    },
    // 根据状态装载不同的数据
    updateECInfo(state) {
      this.currentState = state;
      const pageNameObj = pageNameMap[state];
      this.pageName = pageNameObj && pageNameObj.name ? pageNameObj.name : '';
      if (pageNameObj && pageNameObj.event) {
        this.$track.registeredEvents(pageNameObj.event);
      }
      const LIST_MAP = {
        [INVITAION]: 'inviteInfo',
        [ACTIVATE]: 'inviteInfo',
        [NO_INVITE]: 'activateInfo',
        [NO_ADD_WEIXIN]: 'activateInfo',
        [ACTIVATED]: 'memberInfo',
        [OUT_DATE]: 'activateInfo'
      };
      this.qrcode = this[LIST_MAP[this.currentState]]?.qrcode || '';
      this.maxMemRule = this[LIST_MAP[this.currentState]]?.maxMemRule || '';
      this.maxMemDesc = this[LIST_MAP[this.currentState]]?.maxMemDesc || '';
      this.vccJumpUrl = this[LIST_MAP[this.currentState]]?.vccJumpUrl || '';
      this.couponsList = (this[LIST_MAP[this.currentState]]?.coupon?.coupons || []).sort(
        (a, b) => a.pickupAble - b.pickupAble
      );
      this.categoryList = [
        DEFAULT_CATEGORY,
        ...(this[LIST_MAP[this.currentState]]?.categoryList || [])
      ];
      this.loading = false;
    },
    // 点击对应
    updateState() {
      this.getActivateInfo();
    },
    handleShowQrcode() {
      // 邀请页，如果不需要校验企业微信，直接跳转到激活页，
      if (!this.inviteInfo.isValidFriends && this.isInvite) {
        window.location.href = `/member/maxMember?vccToken=${this.token}`;
        return;
      }
      //特殊情况，激活页，如果用户状态返回的是2，同时不不需要关注公众号号，那么刷新接口
      if (!this.activateInfo.isValidFriends && !this.isInvite) {
        this.updateState();
        return;
      }
      if (!this.qrcode) {
        this.$toast('无二维码信息，请稍后重试');
        return;
      }
      // 小程序环境跳转到原生页面下载
      if (isWxMp) {
        wx.miniProgram.navigateTo({
          url: `/pages/qrcode/index?url=${decodeURIComponent(this.qrcode)}`
        });
      } else {
        this.showQrcode = true;
      }
    },
    handleShowRule() {
      this.showRule = true;
    }
  }
};
</script>

<style lang="less" scoped>
.max-member {
  font-size: 0;
  padding: @padding-lg @padding-sm 0;
  background-color: #eff6ff;
  background-position: center top;
  background-repeat: no-repeat;
  background-image: url('~@/assets/images/maxMember/max-bg.png');
  background-size: 375px 595px;
  &__skeleton {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 98;
  }
  &.invite {
    padding-bottom: 80px;
  }
  &.activated-bg {
    background-image: url('~@/assets/images/maxMember/max-bg-activated.png');
    background-size: 375px 388px;
  }
  &.activate-bg {
    background-image: url('~@/assets/images/maxMember/max-bg-activate.png');
    background-size: 375px 518px;
  }
}
</style>
