<template>
  <div class="container">
    <!-- :style="{ paddingBottom: $config.userCardBottom }" -->
    <div class="user-section">
      <div v-if="isInfoLogin" class="bg" :style="initByType === 0 ? maxBg : normalBg" />
      <div class="user-info-box">
        <!-- <div class="user-info" @click="handleLogin" /> -->
        <div class="user-config" @click="handleLogin">
          <div class="head">
            <img
              :src="(userInfo && userInfo.avatar) || 'https://img.lkbang.net/avatar.18dd2e2a.png'"
              alt=""
            />
          </div>
          <div v-if="!isInfoLogin" class="go-login">
            点击登录
          </div>
          <div v-if="isInfoLogin" class="info-code">
            <div class="info-code-top">
              <div class="phone">{{ userInfo.phoneNumber }}</div>
              <img v-if="maxMemberInfo.iconUrl" :src="maxMemberInfo.iconUrl" alt="" />
              <img :src="memberInfo.userLevelPic" alt="" />
            </div>
            <div class="info-code-bottom" @click="jumpUrl('memberPoint')">
              <div class="growth-value">
                成长值
                <span>{{ currentPoint }}/</span>
                {{ nextLevelPoint }}
                &nbsp; <i class="iconfont icon-arrow" />
              </div>
              <div class="growth-value-progress">
                <cr-progress
                  width="84px"
                  :show-pivot="false"
                  :percentage="progressLine"
                  track-color="#E5B4C1"
                  color="linear-gradient(to right, #FF1900, #FF651F)"
                />
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="memberType === 'normal' && memberInfo && isInfoLogin"
          class="member-info"
          :style="{ marginRight: memberType === 'max' ? 0 : '12px' }"
        >
          <!-- 只有普通会员状态 -->
          <NormalMember
            :style="{ height: '88px' }"
            :member-info="memberInfo"
            show-type="normalMember"
          />
        </div>
        <div class="member-info member-info-max">
          <!-- max会员和普通会员切换融合 -->
          <cr-swipe
            :loop="false"
            :width="290"
            :show-indicators="false"
            @change="onChangePage($event)"
          >
            <cr-swipe-item class="member-info-item">
              <div v-if="memberType === 'max'" :style="{ width: '280px' }">
                <MaxMember :style="{ height: '88px' }" :max-member-info="maxMemberInfo" />
              </div>
            </cr-swipe-item>
            <cr-swipe-item class="member-info-item">
              <div v-if="memberType === 'max'" :style="{ width: '280px' }">
                <normalMember
                  show-type="mixTogether"
                  :member-info="memberInfo"
                  :style="{ height: '88px' }"
                />
              </div>
            </cr-swipe-item>
          </cr-swipe>
        </div>
        <div v-if="$config.qinghai" class="user-config">
          <img
            v-if="(userInfo.nickName || userInfo.phoneNumber) && !$config.qinghai"
            class="coupon"
            :src="couponRoot"
            alt=""
            @click="handleToCoupon"
          />
          <i
            v-if="
              (userInfo.nickName || userInfo.phoneNumber) && ($config.xincheng || $config.qinghai)
            "
            class="iconfont icon-setting-line config"
            @click="handleToRouter('set')"
          />
        </div>
      </div>
      <GiftCard
        v-if="(userInfo.nickName || userInfo.phoneNumber) && $config.qinghai"
        :gift-info="giftInfo"
      />
    </div>
    <div class="cover-container">
      <div class="main-list" :style="{ marginTop: $config.cardTop }">
        <UserQuota
          v-if="xhkInfo.show && $config.xincheng"
          :xhk-opened="xhkOpened"
          :xhk-info="xhkInfo"
          :xhk-btn-state="xhkBtnState"
          :xhk-btn-text="xhkBtnText"
        />
        <!-- 订单 -->
        <div class="card-box card-box-top">
          <div class="card-title">
            <span>我的订单</span>
            <div class="card-info" @click="handleToRouter('orderList', {}, { state: 0 }, true)">
              全部订单 &nbsp; <i class="iconfont icon-arrow" />
            </div>
          </div>
          <div class="card-main">
            <div class="order-section">
              <div class="order-item" @click="handleToRouter('orderList', {}, { state: 1 }, true)">
                <span v-if="paidOrderNum !== 0" class="num">{{ paidOrderNum }}</span>
                <img class="paid-order" src="https://img.lkbang.net/xcx/paid-order-v1.png" />
                <span>待付款</span>
              </div>
              <div class="order-item" @click="handleToRouter('orderList', {}, { state: 2 }, true)">
                <span v-if="preSendNum !== 0" class="num">{{ preSendNum }}</span>
                <img class="goods-order" src="https://img.lkbang.net/xcx/goods-pre-send.png" />
                <span>待发货</span>
              </div>
              <div class="order-item" @click="handleToRouter('orderList', {}, { state: 3 }, true)">
                <span v-if="logicNumber !== 0" class="num">{{ logicNumber }}</span>
                <img class="goods-order" src="https://img.lkbang.net/xcx/goods-order-v1.png" />
                <span>待收货</span>
              </div>
              <div class="order-item" @click="handleToRouter('orderList', {}, { state: 4 }, true)">
                <img
                  class="completed-order"
                  src="https://img.lkbang.net/xcx/completed-order-v1.png"
                />
                <span>已完成</span>
              </div>
              <div
                v-if="$config.yxm"
                class="order-item"
                @click="handleToRouter('refundList', {}, {}, true)"
              >
                <img class="service-order" src="https://img.lkbang.net/xcx/service-order-v1.png" />
                <span>退款/售后</span>
              </div>
            </div>
          </div>
        </div>

        <div class="card-box card-box-top">
          <div class="card-main">
            <div class="order-section serve">
              <div class="order-item" @click="handleToCoupon">
                <!-- <img class="goods-order" :src="couponImg" /> -->
                <div class="coupon-desc">
                  <span class="coupon-num">{{ couponInfo.count || '0' }}</span>
                  <span class="coupon-unit">{{ couponInfo.unit || '张' }}</span>
                </div>
                <span>优惠券</span>
              </div>
              <div class="order-item" @click="handleToGiftcard">
                <!-- <img class="goods-order" :src="couponImg" /> -->
                <div class="giftcard-desc">
                  <span class="giftcard-num">
                    <span class="int">{{ giftcardInt }}</span
                    ><span v-if="giftcardFloat" class="float">.{{ giftcardFloat }}</span>
                  </span>
                  <span class="giftcard-unit">{{ giftcardInfo.unit }}</span>
                </div>
                <span>礼品卡</span>
              </div>
              <!-- 我的卡包 start -->
              <div
                v-if="cardBagInfo && isLogin"
                class="card-bag"
                @click="handleToCardBag(cardBagInfo.jumpUrl)"
              >
                <div class="card-bag-info">
                  <img class="goods-order" :src="cardBagInfo.icon" />
                  <p v-if="cardBagInfo.bubbleView" class="bubble" />
                </div>
                <span>我的卡包</span>
                <div v-if="cardBagInfo.bubbleView" class="superscript">
                  <div v-if="cardBagInfo.angleMark" class="desc">{{ cardBagInfo.angleMark }}</div>
                  <p v-else class="bubble" />
                </div>
              </div>
              <!-- 我的卡包 end -->
            </div>
          </div>
        </div>
        <!-- 综合应用服务 -->
        <div class="card-box card-box-top">
          <div class="card-title">
            <span>综合应用服务</span>
          </div>
          <div class="card-main">
            <div class="order-section serve">
              <div class="order-item" @click="handleToIm">
                <img class="goods-order" src="https://img.lkbang.net/xcx/IM.png" />
                <span>{{ $config.customerServiceName }}</span>
              </div>
              <div class="order-item" @click="handleToRouter('address', {}, {}, true)">
                <img class="goods-order" src="https://img.lkbang.net/xcx/address.png" />
                <span>我的地址</span>
              </div>
              <div class="order-item" @click="handleToRouter('set', {}, {}, true)">
                <img class="goods-order" src="https://img.lkbang.net/setting.b33ff04b.png" />
                <span>设置</span>
              </div>
              <div class="occupy" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <cr-dialog
      v-model="showTelephone"
      show-cancel-button
      confirm-button-text="去拨打"
      @onConfirm="handleTel"
    >
      <div class="content">
        <a ref="tel" class="js-tel" :href="`tel:${$config.telephone}`">{{ $config.telephone }}</a>
      </div>
    </cr-dialog>
    <tip-modal :value.sync="isTipShow" />
  </div>
</template>
<script>
import cfg from '@/config';
import order from '@/api/order.api';
import user, { getGiftCard, myWallet, mineInfo } from '@/api/user.api';
import tipModal from '@/components/tip-modal.vue';
import couponRoot from '@/assets/images/coupon/coupon_root.png';
import { mapState } from 'vuex';
import localStorage from '@/service/localStorage.service';
import { getPublicConfig } from '@/customize';
import { getUserInfo, getVccChannel } from '@/service/userInfo.service';
import UserQuota from './components/userQuota';
import GiftCard from './components/GiftCard';
import userInfoBg from '@/assets/images/user/user-info-bg.png';
import historyRecordMixins from '@/mixins/historyRecord.mixins';
import NormalMember from './components/MemberInfo/normalMember';
import MaxMember from './components/MemberInfo/maxMember.vue';
import localStorageService from '@/service/localStorage.service';
// import couponImg from '@/assets/images/coupon/coupon.png';
export default {
  name: 'User',
  components: {
    tipModal,
    UserQuota,
    GiftCard,
    NormalMember,
    MaxMember
  },
  mixins: [historyRecordMixins],
  data() {
    return {
      normalBg: { background: `linear-gradient(to bottom, #FBF5EE, #F7F8FA)` },
      maxBg: { background: `linear-gradient(to bottom, rgb(209,220,244), rgb(244,246,248)` },
      initByType: 1,
      couponRoot,
      showTelephone: false,
      xhkInfo: {
        show: false
      },
      xhkOpened: false,
      userInfoBg,
      xhkBtnState: false,
      xhkBtnText: '立即开通',
      cashOutRaise: '',
      cashOutReturn: '',
      isTipShow: false,
      allLoading: true,
      paidOrderNum: 0,
      preSendNum: 0,
      goodsOrderNum: 0,
      giftInfo: {},
      telReg: new RegExp('^(\\d{3})\\d{4}(\\d{4})$'),
      cardBagInfo: null, // 卡包信息
      isChannelId: false,
      couponInfo: {}, // 优惠券相关信息
      giftcardInfo: {}, // 礼品卡相关信息
      userBenefits: {} // 用户数据
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.pay.userInfo || {}
    }),
    giftcardInt() {
      let str = '0';
      try {
        str = this.giftcardInfo.count && this.giftcardInfo.count.toString().split('.')[0];
      } catch (err) {
        console.log(err);
      }
      return str;
    },
    giftcardFloat() {
      let str = '00';
      try {
        str = this.giftcardInfo.count && this.giftcardInfo.count.toString().split('.')[1];
      } catch (err) {
        console.log(err);
      }
      return str;
    },
    nickname() {
      return (this.userInfo.phoneNoMask || '').replace(this.telReg, '$1****$2');
    },
    cardBagShow() {
      if (+this.cardBagInfo.isLogin === 2) {
        if (this.isLogin) return true;
        else return false;
      } else {
        return true;
      }
    },
    logicNumber() {
      const num = this.goodsOrderNum;
      return num <= 0 ? 0 : parseInt(num) <= 99 ? num : '99+';
    },
    isInfoLogin() {
      return this.userInfo.nickName || this.userInfo.phoneNumber;
    },
    isLogin() {
      // const vccToken = localStorage.get('vccToken');
      // if (vccToken) this.getCardInfo();
      return localStorage.get('vccToken');
    },
    // 当前成长值
    currentPoint() {
      return (
        (this.userBenefits &&
          this.userBenefits.memberInfo &&
          this.userBenefits.memberInfo.currentPoint) ||
        0
      );
    },
    // 下一阶段成长值
    nextLevelPoint() {
      return (
        (this.userBenefits &&
          this.userBenefits.memberInfo &&
          this.userBenefits.memberInfo.nextLevelPoint) ||
        0
      );
    },
    // 成长值进度
    progressLine() {
      if (this.currentPoint && this.nextLevelPoint) {
        return Math.min((this.currentPoint / this.nextLevelPoint) * 100, 100);
      }
      return 0;
    },
    // max 会员信息
    maxMemberInfo() {
      return (this.userBenefits && this.userBenefits.maxMemberInfo) || {};
    },
    // 普通会员信息
    memberInfo() {
      return (this.userBenefits && this.userBenefits.memberInfo) || {};
    },
    memberType() {
      return Object.keys(this.maxMemberInfo).length > 0 ? 'max' : 'normal';
    }
  },
  watch: {
    memberType(val) {
      if (val === 'max') {
        this.initByType = 0;
      }
    }
  },
  created() {},
  mounted() {
    this.allLoading = false;
    if (this.isLogin) {
      if (this.$config.qinghai) {
        this.getGiftInfo();
      }
      if (this.$config.xincheng) {
        this.getXhkInfo();
      }
      this.getOrderInfo();
      getUserInfo();
      this.queryMineInfo();
      this.getWalletInfo();
    }
    this.$track.registeredEvents('H5_2B_MyPageExposure');

    // 立即授权 去除卡包入口
    const channelId = localStorage.get('vccChannel');
    if (this.$config.channelId && channelId == this.$config.channelId.id) {
      this.isChannelId = true;
    } else {
      this.isChannelId = false;
    }
  },
  methods: {
    jumpUrl(path) {
      const vccToken = this.$route.query.vccToken || localStorageService.get('vccToken');
      const jumpLink = `${cfg.vipHost}/${path}?vccToken=${vccToken}`;
      window.location.href = jumpLink;
    },
    // 切换swiper
    onChangePage(e) {
      this.initByType = e;
    },
    // 获取我的数据
    async queryMineInfo() {
      const res = await mineInfo();
      if (res && res[0]) {
        const { userBenefits } = res[0];
        this.userBenefits = userBenefits;
      }
    },
    /**
     * 获取卡包配置信息
     */
    async getWalletInfo() {
      const res = await myWallet();
      this.cardBagInfo =
        res[0].serviceList.filter(item => {
          return item.type === 'cardbag';
        })[0] || null;
      this.couponInfo =
        res[0].serviceList.filter(item => {
          return item.type === 'coupon';
        })[0] || {};
      this.giftcardInfo =
        res[0].serviceList.filter(item => {
          return item.type === 'giftcard';
        })[0] || {};
    },
    handleLogin() {
      if (!this.userInfo.phoneNumber && (this.$config.qinghai || this.$config.yxm)) {
        this.$router.push({ name: 'Login', query: { backUrl: location.href } });
      }
    },
    xhkRepayment(val) {
      console.log(val);
    },
    handleTel() {
      this.$refs.tel?.click();
    },
    handleToIm() {
      if (!this.$config.yxm) {
        this.showTelephone = true;
        return;
      }
      cfg.SOBOT_URL.replace('{userId}', localStorage.get('userId') || Math.random() * 100);
      window.location.href = cfg.SOBOT_URL;
    },
    handleToRouter(name, query, params, needLogin) {
      if (needLogin && !this.isLogin) {
        this.$router.push({ name: 'Login', query: { backUrl: location.href } });
        return;
      }
      this.$router.push({ name, query, params });
    },
    handleToCoupon() {
      this.$router.push({ name: 'coupon' });
    },
    handleToGiftcard() {
      this.$track.registeredEvents('H5_MyPageGiftCardsClick', {}, () => {
        this.$router.push({ name: 'giftCardList' });
      });
    },
    handleToCardBag(url) {
      const publicConfig = getPublicConfig();
      url = url.replace('{token}', localStorage.get('vccToken'));
      url = url.replace('{tchannel}', getVccChannel() || publicConfig.vccChannel || '');
      window.location.href = url;
    },
    // handleToNectar() {
    //   const url = `${cfg.nectarHost}?token=${localStorage.get('vccToken')}`;
    // },
    async getGiftInfo() {
      const [res] = await getGiftCard();
      this.giftInfo = res || {};
    },
    async getOrderInfo() {
      // 我的 查询各状态订单数量
      const [getData] = await order.orderInfo();
      if (getData) {
        (getData.statusNumList || []).forEach(item => {
          if (item.status === 11) {
            this.paidOrderNum = parseInt(item.number) <= 99 ? item.number : '99+';
          }
          if (item.status === 21) {
            this.preSendNum = item.number;
          }
          if (item.status === 31) {
            this.goodsOrderNum = item.number;
          }
        });
      }
    },

    async getXhkInfo() {
      // 获取信用钱包用户信息
      const [getData] = await user.getXhkInfo();
      if (getData) {
        this.xhkInfo = getData;
        switch (parseInt(getData.accountStatus)) {
          case 1: // 未申请
            this.xhkBtnText = '立即开通';
            break;
          case 2: // 审核中
            this.xhkBtnText = '正在审核';
            this.xhkBtnState = false;
            break;
          case 3: // 审核失败
            this.xhkBtnText = '立即开通';
            this.xhkBtnState = true;
            this.$forceUpdate();
            break;
          case 4: // 审核成功未开户（包含开户失败）
            this.xhkBtnText = '立即激活';
            this.xhkBtnState = true;
            break;
          case 5: // 已开户
            this.xhkOpened = false;
            break;
        }
      }
    }
  }
};
</script>
<style lang="less" scoped src="./index.less"></style>
