<template>
  <view class="container">
    <view
      v-if="$config('yxm')"
      class="user-section"
      :class="{
        unlogin: !userInfo.hasLogin
      }"
    >
      <image
        v-show="bgType == 'normal'"
        class="bg"
        src="https://img.lkbang.net/xcx/user-bg-v1.png"
      />
      <!-- #ifdef MP-WEIXIN -->
      <image
        v-show="bgType == 'maxMember'"
        class="bg"
        src="https://img.lkbang.net/xcx/user-bg-v2.png"
      />
      <!-- #endif -->
      <user-info-box
        :member-info="memberInfo"
        :user-base-info="userBaseInfo"
        :user-info="userInfo"
        :show-max-member="showMaxMember"
        :max-member-icon-url="maxMemberIconUrl"
        @nav-to="navTo"
        @open-login="loginPopupFn"
      />
    </view>
    <view v-else class="user-qinghai" :style="{ paddingTop: `${navHeight}px` }">
      <view class="user-qinghai-content">
        <user-info-box
          :user-base-info="userBaseInfo"
          :user-info="userInfo"
          @nav-to="navTo"
          @open-login="loginPopupFn"
        />
        <gift-button
          v-if="userInfo.hasLogin"
          class="user-gift"
          :gift-info="giftInfo"
          @nav-to="navTo"
        />
      </view>
    </view>
    <!-- 会员中心 只有羊小咩且登录状态下展示-->
    <member
      v-if="userInfo.hasLogin"
      :show-max-member="showMaxMember"
      :member-info="memberInfo"
      :user-info="userInfo"
      :max-member-info="maxMemberInfo"
      @navigateUrl="navigateToPage"
      @changeBg="changeBg"
    />
    <view class="cover-container">
      <view
        class="main-list"
        :class="{ 'main-qinghai': $config('qinghai'), yxm: $config('yxm') && userInfo.hasLogin }"
      >
        <!-- 青海移动不展示 2021.11.21 -->
        <template v-if="xhkInfo.show && $config('yxm')">
          <view v-if="xhkOpened" class="card-box xhk-state">
            <image class="xhk-icon" src="https://img.lkbang.net/xcx/xhk-icon.png" />
            <view v-if="parseInt(xhkInfo.accountStatus) === 4" class="xhk-title">
              <view class="xhk-bold">激活享花卡</view>
              <text class="display-block"
                >已获得消费额度：¥{{ xhkInfo.creditTotalAmount || 0 }}</text
              >
              <text class="color-gray">激活享花卡，即可使用额度，享最高40天免息</text>
            </view>
            <view v-else class="xhk-title">
              <view class="xhk-bold">开通享花卡</view>
              <text>使用享花卡支付，享最高40天免息！</text>
            </view>
            <button
              :class="[xhkBtnState ? '' : 'disabled']"
              class="card-xhk-btn btn-position"
              @click="handleOpen('xhk-btn-popup')"
            >
              {{ xhkBtnText }}
            </button>
          </view>
          <view v-else class="card-box">
            <view class="card-title">
              <text>我的享花卡</text>
              <!-- <view class="card-info" @click="open('xhk-popup')">查看卡片信息&nbsp; <text class="cell-right iconfont icon-arrow arrows"></text></view> -->
            </view>
            <view class="card-main">
              <view class="tj-sction">
                <view class="tj-item" @click="handleToPayBack">
                  <text class="num">{{ xhkInfo.canUseAmt }}</text>
                  <text>可用额度(元)</text>
                </view>
                <view class="tj-item" @click="handleToPayBack">
                  <text class="num">{{ xhkInfo.repayAmt }}</text>
                  <text>待还款(元)</text>
                </view>
              </view>
              <view v-if="!xhkInfo.faced" class="face-recognition">
                <view class="face-recognition-txt"
                  >因您尚未完成活体认证，最高累计可使用<text>200</text>额度</view
                >
                <button @click="xhkRepayment('appToFace')">
                  去认证<text class="cell-right iconfont icon-arrow arrows" />
                </button>
              </view>
            </view>
            <view class="card-footer">
              <view v-if="xhkInfo.overdue" class="xhk-txt" style="color: #ec1500"
                >您已逾期，以免造成不良影响请尽快还款！</view
              >
              <view v-else-if="parseInt(xhkInfo.repayAmt) > 0" class="xhk-txt">{{
                xhkInfo.repayDesc
              }}</view>
              <view v-else class="xhk-txt">使用享花卡支付，享最高40天免息！</view>
              <button
                v-if="parseInt(xhkInfo.repayAmt) !== 0"
                class="card-xhk-btn"
                :class="!xhkInfo.overdue && parseInt(xhkInfo.repayAmt) == 0 ? 'disabled' : ''"
                @click="handleToPayBack"
              >
                立即还款
              </button>
            </view>
          </view>
        </template>
        <!-- 订单 -->
        <view class="card-box" :class="[xhkInfo.show ? '' : 'card-box-top']">
          <view class="card-title">
            <text>我的订单</text>
            <view class="card-info" @click="setSubMsg('/pages/order/orderList?state=0')"
              >全部订单 &nbsp; <text class="cell-right iconfont icon-arrow arrows"
            /></view>
          </view>
          <view class="card-main">
            <view class="order-section">
              <view class="order-item" @click="setSubMsg('/pages/order/orderList?state=1')">
                <text v-if="paidOrderNum !== 0" class="num">{{ paidOrderNum }}</text>
                <image class="paid-order" src="https://img.lkbang.net/xcx/paid-order.png" />
                <text>待付款</text>
              </view>
              <view class="order-item" @click="setSubMsg('/pages/order/orderList?state=3')">
                <text v-if="goodsOrderNum !== 0" class="num">{{ goodsOrderNum }}</text>
                <image class="goods-order" src="https://img.lkbang.net/xcx/goods-order.png" />
                <text>待收货</text>
              </view>
              <view class="order-item" @click="setSubMsg('/pages/order/orderList?state=4')">
                <image
                  class="completed-order"
                  src="https://img.lkbang.net/xcx/completed-order.png"
                />
                <text>已完成</text>
              </view>
              <!--青海移动不展示  2021.11.19  -->
              <view v-if="$config('yxm')" class="order-item" @click="toRefund">
                <image class="service-order" src="https://img.lkbang.net/xcx/service-order.png" />
                <text>退款/售后</text>
              </view>
            </view>
          </view>
        </view>
        <view v-if="$config('yxm')" class="card-box">
          <view class="card-main">
            <view class="coupon-info">
              <view class="coupon-info-item" @click="navigateToPage(1, couponInfo.jumpUrl)">
                <view class="detail">
                  <text class="detail-number">{{
                    userInfo.hasLogin ? couponInfo.count || 0 : 0
                  }}</text>
                  <text class="detail-unit">{{ couponInfo.unit || "张" }}</text>
                </view>
                <text class="desc">{{ couponInfo.name || "优惠券" }}</text>
              </view>
              <view class="coupon-info-item" @click="navigateToPage(2, giftCardInfo.jumpUrl)">
                <view class="detail">
                  <template v-if="userInfo.hasLogin">
                    <template v-if="giftCardInfo.count && giftCardInfo.count.indexOf('.') > -1">
                      <text class="detail-number">{{ giftCardInfo.count.split(".")[0] }}</text>
                      <text class="detail-unit">.{{ giftCardInfo.count.split(".")[1] }}</text>
                    </template>
                    <template v-else>
                      <text class="detail-number">0</text>
                    </template>
                  </template>
                  <template v-else>
                    <text class="detail-number">0</text>
                  </template>
                  <text class="detail-unit">{{ giftCardInfo.unit || "元" }}</text>
                </view>
                <text class="desc">{{ giftCardInfo.name || "礼品卡" }}</text>
              </view>
              <view
                v-if="cardBagInfo.type === 'cardbag'"
                class="coupon-info-item"
                @click="navigateToPage(5)"
              >
                <view class="detail">
                  <view
                    v-if="cardBagInfo.bubbleView && !cardBagInfo.angleMark && showPoint"
                    class="point"
                  />
                  <view v-if="cardBagInfo.angleMark" class="text-desc">
                    {{ cardBagInfo.angleMark }}
                  </view>
                  <image style="width: 48rpx; height: 48rpx;" :src="cardBagInfo.icon" />
                </view>
                <text class="desc">{{ cardBagInfo.name || "我的卡包" }}</text>
              </view>
            </view>
          </view>
        </view>
        <!-- 提现 -->
        <!-- <template v-if="xhkInfo.show">
          <view
            v-if="(userInfo.nickname || userBaseInfo.nickName) && $config('yxm')"
            class="card-box"
            :class="[xhkInfo.show ? '' : 'card-box-top']"
          >
            <view class="card-title">
              <text>我的返现</text>
              <view class="card-info" @click="xhkRepayment"
                >全部返现记录 &nbsp; <text class="cell-right iconfont icon-arrow arrows"
              /></view>
            </view>
            <view class="card-main">
              <view class="order-section cash-out">
                <view class="cash-out-text">
                  <image src="https://img.lkbang.net/xcx/gold.png" />
                  <view class="cash-out-txt">
                    <view class="cash-out-raise"
                      >您的可提现金额<text>{{ cashOutRaise || 0 }}</text
                      >元</view
                    >
                    <view class="cash-out-return"
                      >待返现(元)<text>{{ cashOutReturn || 0 }}</text></view
                    >
                  </view>
                </view>
                <button class="card-xhk-btn" @click="xhkRepayment('cashOutRaise')">
                  去提现
                </button>
              </view>
            </view>
          </view>
        </template> -->
        <!-- 综合应用服务 -->
        <view class="card-box">
          <view class="card-title">
            <text>综合应用服务</text>
            <!-- <view class="card-info">全部订单></view> -->
          </view>
          <view class="card-main">
            <view class="order-section">
              <!-- #ifdef MP-WEIXIN -->
              <view v-if="$config('yxm')" class="order-item" @click="tip()">
                <image class="paid-order" src="https://img.lkbang.net/xcx/weChat.png" />
                <text>关注微信</text>
              </view>
              <!-- #endif -->
              <view
                class="order-item"
                @click="$config('yxm') ? navToCustomer() : callPhone('400-010-0017')"
              >
                <!-- <view v-if="!authState" class="auth-info__mask" @click.stop="showAuthModal" />
                <button
                  v-if="$config('yxm')"
                  class="contact-service"
                  :session-from="sessionFrom"
                  open-type="contact"
                >
                  联系客服
                </button> -->
                <image class="goods-order" src="https://img.lkbang.net/xcx/IM.png" />
                <text v-if="$config('yxm')">在线客服</text>
                <text v-if="$config('qinghai')">电话客服</text>
              </view>
              <view class="order-item" @click="navTo('/subPackages/common/address/address')">
                <image class="completed-order" src="https://img.lkbang.net/xcx/address.png" />
                <text>我的地址</text>
              </view>
              <view class="order-item">
                <qa-selector @clear="loginPopupFn" />
              </view>
            </view>
          </view>
          <!-- <view class="card-footer">
            <text>使用享花卡支付，享最高40天免息！</text>
            <button class="card-xhk-btn disabled">立即还款</button>
          </view> -->
        </view>
      </view>
    </view>

    <login-popup ref="login-popup" type="center" title="用户授权登录" />
    <uni-popup ref="xhk-popup" type="center">
      <uni-popup-dialog
        type="info"
        title="我的享花卡"
        confirm-txt="知道了"
        stay-style
        :duration="2000"
        hide-cancel-btn
        @confirm="confirm"
      >
        <view class="xhk-popup">
          <view>享花卡&上海银行储蓄卡</view>
          <view>卡号：{{ xhkInfo.cardNo }}</view>
          <view class="declare">本卡仅限于在羊小咩APP或小程序使用</view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
    <!--uni-app-->

    <uni-popup ref="xhk-btn-popup" type="center">
      <uni-popup-dialog
        type="info"
        content="您可以下载“羊小咩”APP，在APP内完成激活即可享最高40天购物免息！"
        :duration="2000"
        hide-cancel-btn
        @close2="close2"
        @confirm="confirm"
      />
    </uni-popup>
    <tipModal :value="showTip" :type="qrFrom" @change="changeTipStatus" />
    <user-info-popup
      ref="authPopup"
      @auth-state="handleAuthState"
      @get-user-info="handleUserInfo"
    />

    <!-- <uni-popup ref="order-service" type="center">
      <uni-popup-dialog
        type="info"
        content="您可以下载“羊小咩”APP，在APP内完成订单退款及售后！"
        :duration="2000"
        hide-cancel-btn
        @close2="close2"
        @confirm="confirm"
      />
    </uni-popup> -->
    <skeleton v-if="allLoading" />
    <activityModal
      v-if="Object.keys(activityModalData).length > 0"
      :modal-data="activityModalData"
      page-name="我的"
      @close="closeActivityModal"
      @goto="jumpToWebView(activityModalData)"
    />
  </view>
</template>
<script>
const status = ["未申请", "审核中", "审核失败", "已有额度未激活", "开户成功"];
import loginPopup from "@/components/loginPopup";
import userInfoPopup from "@/components/userInfoPopup";
import uniPopup from "@/components/uni-popup/uni-popup.vue";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog.vue";
import skeleton from "./user.skeleton";
import authApi from "@/api/address.api";
import { queryMemberAndCouponInfo } from "@/api/member.api";
import {
  getVaildSubTmplIds,
  uploadPopup,
  getGiftCard,
  getWalletInfo,
  getFincialData
} from "@/api/home.api";
import { h5Mixin } from "@/utils/h5Mixin";
import { getVaildTmplIds, submitSubcribeInfo, getAcceptList } from "@/utils/subscribe";
import tipModal from "@/components/tip-modal";
import { saTrackEvent, saDeviceId } from "@/utils/sa";
import { getCartCountVal } from "../../mixins/common.js";
import activityModal from "@/components/activityModal";
import QaSelector from "@/components/qaTool/qaSelector";
import userInfoBox from "./userInfoBox.vue";
import giftButton from "./giftButton.vue";
import member from "./member.vue";
import config from "@/config";
import { parseTime } from "@/utils/index";
const tmplIds = [
  config.SUB_MSG_LIST.SELLER_SHIP,
  config.SUB_MSG_LIST.ORDER_RECEIPT,
  config.SUB_MSG_LIST.COUPON_RECEIPT
];
let vaildTmplIds = [];
const newTmplIds = [
  config.SUB_MSG_LIST.RESULT_NOTICE,
  config.SUB_MSG_LIST.RECEIPT_OPEN_SUCCESS
  // config.SUB_MSG_LIST.NEWPRODUCT_NOTICE
];
const tenantBasicInfo = uni.getStorageSync("tenantBasicInfo");
let startY = 0,
  moveY = 0,
  pageAtTop = true;
export default {
  components: {
    loginPopup,
    userInfoPopup,
    uniPopup,
    uniPopupDialog,
    tipModal,
    skeleton,
    activityModal,
    QaSelector,
    userInfoBox,
    giftButton,
    member
  },
  mixins: [h5Mixin()],
  data() {
    return {
      navHeight: 70,
      allLoading: true,
      showTip: false,
      coverTransform: "translateY(0px)",
      coverTransition: "0s",
      moving: false,
      paidOrderNum: 0,
      goodsOrderNum: 0,
      authState: false,
      userBaseInfo: {},
      userInfo: {
        nickname: "",
        hasLogin: false
      },
      xhkBtnText: "立即开通",
      xhkBtnState: true,
      xhkOpened: true,
      xhkInfo: {},
      xhkPopupTxt: "您可以下载“羊小咩”APP，在APP内完成激活即可享最高40天购物免息！",
      qrFrom: "wx",
      telReg: /^(\d{3})\d{4}(\d{4})$/,
      cashOutRaise: "",
      cashOutReturn: "",
      activityModalData: {},
      activityJumpUrl: "",
      giftInfo: {},
      memberInfo: {}, // 会员信息
      giftCardInfo: {
        // 礼品卡信息
        count: "0"
      },
      couponInfo: {}, // 优惠券信息
      cardBagInfo: {},
      showMaxMember: true, // 是否展示和max会员相关元素
      maxMemberIconUrl: "", // max会员icon
      maxMemberInfo: {},
      bgType: "normal",
      showPoint: true,
      changedBg: false // 是否已经切换过背景图
    };
  },
  async onLoad(option) {
    const vm = this;
    uni.$on("login", usnerInfo => {
      if (usnerInfo) {
        vm.getUserInfo();
        if (this.activityJumpUrl) {
          const url = this.activityJumpUrl;
          this.activityJumpUrl = "";
          uni.redirectTo({
            url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
          });
        }
        // #ifdef MP-WEIXIN
        getVaildSubTmplIds(tmplIds).then(res => {
          vaildTmplIds = res;
        });
        // #endif
      }
    });

    if (uni.getStorageSync("token")) {
      this.setUserInfo();
      // #ifdef MP-WEIXIN
      vaildTmplIds = await getVaildSubTmplIds(tmplIds);
      // #endif
    }
    if (option && option.login == 1) {
      vm.loginPopupFn();
    }
    this.getUserPopup();
    process.env.NODE_ENV !== "production" &&
      uni.$on("qaEnvChange", () => {
        this.xhkInfo = {};
        this.userInfo = {};
        this.userBaseInfo = {};
        this.init();
      });
    // 注销登录清空数据
    uni.$on("logout", () => {
      this.userInfo.nickname = "";
      this.userInfo.hasLogin = false;
    });
    const date = parseTime(new Date(), "{y}-{m}-{d}");
    if (uni.getStorageSync("date")) {
      const lastDate = uni.getStorageSync("date");
      if (date > lastDate) {
        uni.setStorageSync("date", date);
        this.showPoint = true;
      } else {
        this.showPoint = false;
      }
    } else {
      uni.setStorageSync("date", date);
      this.showPoint = true;
    }
  },
  onTabItemTap() {
    saTrackEvent("MINI_BottomTabsClick", { tab_name: "我的" });
  },
  onShow() {
    const vccToken = uni.getStorageSync("token") || "";
    this.init();
    this.getNavBarHeight();
    if (vccToken) {
      this.getMemberAndCouponInfo();
      this.getWalletInfo();
    } else {
      this.userInfo.hasLogin = false;
    }
  },
  onReady() {
    this.allLoading = false;
  },
  onUnload() {
    // 移除监听事件
    uni.$off("login");
    uni.$off("logout");
    uni.$off("qaEnvChange");
  },
  // #ifndef MP
  onNavigationBarButtonTap(e) {
    const index = e.index;
    if (index === 0) {
      this.navTo("/subPackages/common/set/set");
    } else if (index === 1) {
      // #ifdef APP-PLUS
      const pages = getCurrentPages();
      const page = pages[pages.length - 1];
      const currentWebview = page.$getAppWebview();
      currentWebview.hideTitleNViewButtonRedDot({
        index
      });
      // #endif
      uni.navigateTo({
        url: "/subPackages/common/notice/notice"
      });
    }
  },
  // #endif
  computed: {
    customField() {
      const xhkInfo = JSON.parse(JSON.stringify(this.xhkInfo || {}));
      delete xhkInfo.repayDesc;
      delete xhkInfo.creditTotalAmountDesc;
      return JSON.stringify({
        ...this.userInfo,
        ...xhkInfo,
        ...tenantBasicInfo
      });
    },
    sessionFrom() {
      return `我的-在线客服|${this.userBaseInfo.nickName}|${this.userBaseInfo.avatarUrl}|${this.customField}`;
    }
  },

  methods: {
    init() {
      getCartCountVal();
      this.userBaseInfo = uni.getStorageSync("userBaseInfo") || {};
      this.authState = !!this.userBaseInfo.nickName;
      if (uni.getStorageSync("token")) {
        this.setUserInfo();
        this.getOrderInfo();
        this.getXhkInfo();
        // 20220402 发现获取返现信息的接口有时会提示异常，而这块功能已在小程序下线，为此注释掉相关代码
        // this.getCashOut();
        this.getGiftCard();
      }
    },
    changeBg(type) {
      // max会员和普通会员滑动后切换背景颜色
      this.changedBg = true;
      this.bgType = type;
    },
    getNavBarHeight() {
      if (this.$config("qinghai")) {
        const sysInfo = wx.getSystemInfoSync();
        const cubeInfo = wx.getMenuButtonBoundingClientRect();
        const statusBarHeight = sysInfo.statusBarHeight;
        const navbarHeight = (cubeInfo.top - sysInfo.statusBarHeight) * 2 + cubeInfo.height;
        this.navHeight = statusBarHeight + navbarHeight;
      }
    },
    async getMemberAndCouponInfo() {
      // 查询会员信息及优惠券信息
      const [data, err] = await queryMemberAndCouponInfo();
      if (err) return;
      const { memberInfo, maxMemberInfo } = data;
      this.maxMemberInfo = maxMemberInfo || {};
      this.memberInfo = memberInfo && memberInfo.constructor === Object ? data.memberInfo : {};
      this.maxMemberIconUrl = maxMemberInfo && maxMemberInfo.iconUrl ? maxMemberInfo.iconUrl : "";
      /* #ifdef MP-WEIXIN */
      this.showMaxMember =
        maxMemberInfo &&
        maxMemberInfo.status &&
        (maxMemberInfo.status == 2 || maxMemberInfo.status == 3)
          ? true
          : false;
      if (!this.changedBg) {
        this.bgType =
          maxMemberInfo &&
          maxMemberInfo.status &&
          (maxMemberInfo.status == 2 || maxMemberInfo.status == 3)
            ? "maxMember"
            : "normal";
      }
      /* #endif */
      /* #ifndef MP-WEIXIN */
      this.showMaxMember = false;
      this.bgType = "normal";
      /* #endif */
    },
    async getWalletInfo() {
      // 查询优惠券、礼品卡、和卡包信息
      const [data, err] = await getWalletInfo();
      if (err) return;
      const serviceList = data.serviceList || [];
      const couponInfoArr = serviceList.filter(v => v.type === "coupon");
      const giftCardInfoArr = serviceList.filter(v => v.type === "giftcard");
      const cardBagInfoArr = serviceList.filter(v => v.type === "cardbag");
      this.couponInfo = couponInfoArr.length ? couponInfoArr[0] : {};
      this.giftCardInfo = giftCardInfoArr.length ? giftCardInfoArr[0] : {};
      this.cardBagInfo = cardBagInfoArr.length ? cardBagInfoArr[0] : {};
    },
    toRefund() {
      if (!this.userInfo.hasLogin) {
        this.$refs["login-popup"].open();
        return;
      }
      const vccToken = uni.getStorageSync("token") || "";
      const vccChannel = uni.getStorageSync("vccChannel") || "";
      const urlpj = `${config.MALL_URL}/refundList?vccChannel=${vccChannel}&vccToken=${vccToken}`;
      uni.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(urlpj))}`
      });
    },
    async getGiftCard() {
      if (this.$config("qinghai") && this.userInfo.hasLogin) {
        const [res, err] = await getGiftCard();
        if (!err) {
          this.giftInfo = res || {};
        }
      }
    },
    async closeActivityModal() {
      const data = JSON.parse(JSON.stringify(this.activityModalData));
      const token = uni.getStorageSync("token") || "";
      this.activityModalData = {};
      if (data?.exposureType == 3 && token) {
        const uid = data.uid;
        const exposureType = data.exposureType;
        await uploadPopup({
          uid,
          exposureType
        });
      }
    },
    async getUserPopup() {
      const [data] = await authApi.getUserPopup();
      const token = uni.getStorageSync("token") || "";
      this.activityModalData = data || {};
      if (data?.exposureType == 1 && token) {
        // 每天仅弹出一次 进行上报
        const uid = data.uid;
        const exposureType = data.exposureType;
        await uploadPopup({
          uid,
          exposureType
        });
      }
    },
    async jumpToWebView(data) {
      saTrackEvent("MINI_PagePopupWindowClick", {
        popupwindow_id: data.uid,
        popupwindow_name: data.componentName,
        page_name: "我的"
      });
      data = data || {};
      const token = uni.getStorageSync("token") || "";
      const url = data.jumpUrl || "";
      this.activityJumpUrl = url;
      if (data?.needLogin && !token) {
        this.activityModalData = {};
        this.$refs["login-popup"].open();
        return;
      }
      if (data?.exposureType == 2 && token) {
        const uid = data.uid;
        const exposureType = data.exposureType;
        await uploadPopup({
          uid,
          exposureType
        });
      }
      this.activityModalData = {};
      if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0) {
        uni.navigateTo({
          url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
        });
        return;
      }
      uni.navigateTo({
        url
      });
    },
    setUserInfo() {
      const phone = uni.getStorageSync("phone");
      this.userInfo.nickname = phone.replace(this.telReg, "$1****$2");
      this.userInfo.hasLogin = true;
    },
    getUserInfo() {
      const vm = this;
      vm.setUserInfo();
      vm.getOrderInfo();
      vm.getXhkInfo();
      // vm.getCashOut();
      vm.getGiftCard();
      vm.getWalletInfo();
      vm.getMemberAndCouponInfo();
    },
    config() {
      uni.redirectTo({
        url: `/subPackages/common/set/set`
      });
    },
    tip() {
      this.qrFrom = "wx";
      this.showTip = true;
    },
    changeTipStatus() {
      this.showTip = false;
    },
    clearData() {
      this.paidOrderNum = 0;
      this.goodsOrderNum = 0;
      this.userInfo.hasLogin = false;
    },
    loginPopupFn(isclear) {
      if (isclear) this.clearData(); // 切换环境之后重置一些数据
      if (!uni.getStorageSync("token")) {
        this.$refs["login-popup"].open();
      }
    },
    close2() {
      // TODO 做一些其他的事情，before-close 为true的情况下，手动执行 done 才会关闭对话框
      // ...
      // done()
    },
    /**
     * 点击确认按钮触发
     * @param {Object} done
     * @param {Object} value
     */
    confirm() {
      // 输入框的值
      // console.log(value)
      // TODO 做一些其他的事情，手动执行 done 才会关闭对话框
      // ...
      // done()
    },
    open(ref) {
      this.$refs[ref].open();
    },
    close(ref) {
      this.$refs[ref].close();
    },
    setSubMsg(url) {
      if (!this.userInfo.hasLogin) {
        this.$refs["login-popup"].open();
      } else if (!vaildTmplIds.length) {
        this.navTo(url);
      } else {
        // 非羊小咩不触发订阅消息
        if (this.$config("yxm")) {
          // #ifdef MP-WEIXIN
          wx.requestSubscribeMessage({
            tmplIds: vaildTmplIds,
            success: res => {
              this.submitInfo(res);
              this.navTo(url);
              const vaildIds = getVaildTmplIds(res);
              saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
                trigger_node: "我的页，点击订单相关按钮",
                check_content: vaildIds,
                buttons_name: "允许"
              });
            },
            fail: err => {
              console.error("requestSubscribeMessage", err);
              saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
                trigger_node: "我的页，点击订单相关按钮",
                check_content: "商家发货通知,优惠券到账通知,优惠券过期通知",
                buttons_name: "取消"
              });
              this.navTo(url);
            }
          });
          // #endif
        } else {
          this.navTo(url);
        }
      }
    },
    submitInfo(res) {
      const acceptList = getAcceptList(res);
      submitSubcribeInfo(acceptList);
    },
    /**
     * 统一跳转接口,拦截未登录路由
     * navigator标签现在默认没有转场动画，所以用view
     */
    navTo(url) {
      if (!this.userInfo.hasLogin) {
        // url = '/pages/public/login';
        this.$refs["login-popup"].open();
      } else if (url == "open-popup") {
        this.qrFrom = "gzh"; // 退款售后
        this.showTip = true;
      } else {
        uni.navigateTo({
          url
        });
      }
    },
    navToCustomer() {
      const account = uni.getStorageSync("userAuthInfo").uuid || saDeviceId;
      const customerH5Url = `https://kefu.q-gp.com/H5/#/chat?skillGroupId=398&enterpriseId=216&headline=%E7%BE%8A%E5%B0%8F%E5%92%A9%E5%95%86%E5%9F%8E&tel=400-666-0873&account=${account}`;
      const customerUrlEncode = `/pages/webview/webview?url=${encodeURIComponent(
        JSON.stringify(customerH5Url)
      )}`;
      /* #ifdef MP-ALIPAY */
      // 如果是支付宝时未登录下 使用神策设备id代替 uuid
      if (!this.userInfo.hasLogin) {
        return uni.navigateTo({
          url: customerUrlEncode
        });
      }
      /* #endif */
      this.navTo(customerUrlEncode);
    },
    xhkRepayment(val) {
      // cashOutRaise
      // if (!this.xhkInfo.overdue && parseInt(this.xhkInfo.repayAmt) == 0) return
      if (val === "appToFace") {
        saTrackEvent("PD_YXMMACP_UserClickMyPageGoToConfirmBtn");
        this.qrFrom = "appToFace";
      } else if (val === "cashOutRaise") {
        // 去提现
        saTrackEvent("PD_YXMMACP_UserClickMyPageGetCash");
        this.qrFrom = "app";
      } else {
        this.qrFrom = "app";
      }
      this.showTip = true;
    },
    handleToPayBack() {
      const vccToken = uni.getStorageSync("token") || "";
      const jumpUrl = `${config.VCC_URL}/bill?vccToken=${vccToken}&vccChannel=${config.VCC_CHANNEL}`;
      saTrackEvent("PD_YXMMACP_UserClickMyToRepay");
      uni.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(jumpUrl))}`
      });
    },
    handleOpen() {
      const vm = this;
      if (!vm.xhkBtnState) return;
      saTrackEvent("PD_YXMMACP_UserClickMyVccCardButton", {
        vcc_state: status[this.xhkInfo.accountStatus - 1],
        buttons_name: this.xhkBtnText
      });
      // vm.open('xhk-btn-popup')
      // if (vm.xhkBtnText == '立即激活') {
      //   vm.qrFrom = 'app'
      //   vm.showTip = true
      // } else {
      //   this.goApply();
      // }
      wx.requestSubscribeMessage({
        tmplIds: newTmplIds,
        success: res => {
          this.goApply();
          const vaildIds = getVaildTmplIds(res);
          saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
            trigger_node: "我的-点击 立即开通",
            check_content: vaildIds,
            buttons_name: "允许"
          });
        },
        fail: err => {
          console.error("requestSubscribeMessage", err);
          saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
            trigger_node: "我的-点击 立即开通",
            check_content: "审核结果通知,发票开具成功提醒",
            buttons_name: "取消"
          });
          this.goApply();
        }
      });
    },
    handleAuthState(e) {
      this.authState = !!e.nickName;
    },
    showAuthModal() {
      this.$refs["authPopup"].open();
    },
    handleUserInfo(e) {
      this.authState = !!e.nickName;
      this.userBaseInfo = e;
    },
    async getXhkInfo() {
      // 获取信用钱包用户信息
      const vm = this;
      const [getData] = await authApi.xhkInfo();
      if (getData) {
        vm.xhkInfo = getData;
        // getData.accountStatus = '5'
        switch (parseInt(getData.accountStatus)) {
          case 1: // 未申请
            vm.xhkBtnText = "立即开通";
            break;
          case 2: // 审核中
            vm.xhkBtnText = "正在审核";
            vm.xhkBtnState = false;
            break;
          case 3: // 审核失败
            vm.xhkBtnText = "立即开通";
            vm.xhkBtnState = true;
            vm.$forceUpdate();
            break;
          case 4: // 审核成功未开户（包含开户失败）
            vm.xhkBtnText = "立即激活";
            vm.xhkBtnState = true;
            break;
          case 5: // 已开户
            vm.xhkOpened = false;
            break;
        }
        // vm.xhkInfo.show = false
        // vm.xhkOpened = false; // 提交前删除
      }
    },
    // async getCashOut() {
    //   if (this.$config("qinghai")) return false;
    //   // 获取提现
    //   const vm = this;
    //   const [getData] = await authApi.cashOut();
    //   if (getData) {
    //     vm.cashOutRaise = getData.accountAmount;
    //     vm.cashOutReturn = getData.waitReturnCashAmount;
    //   }
    // },
    async getOrderInfo() {
      // 我的 查询各状态订单数量
      const [getData] = await authApi.orderInfo();
      let arrTemp = null;
      // console.log(getData.statusNumList)
      if (getData) {
        arrTemp = getData.statusNumList;
        for (let i = 0; i < arrTemp.length; i++) {
          if (arrTemp[i].status == 11) {
            this.paidOrderNum =
              parseInt(arrTemp[i].number) <= 99
                ? (this.paidOrderNum = arrTemp[i].number)
                : (this.paidOrderNum = "99+");
          }
          if (arrTemp[i].status == 31) {
            parseInt(arrTemp[i].number) <= 99
              ? (this.goodsOrderNum = arrTemp[i].number)
              : (this.goodsOrderNum = "99+");
          }
        }

        // paidOrderNum: '', // 待付款 statusNumList[0].number
        // goodsOrderNum: '' // 待收货 statusNumList[1].number
      }
    },
    /**
     *  会员卡下拉和回弹
     *  1.关闭bounce避免ios端下拉冲突
     *  2.由于touchmove事件的缺陷（以前做小程序就遇到，比如20跳到40，h5反而好很多），下拉的时候会有掉帧的感觉
     *    transition设置0.1秒延迟，让css来过渡这段空窗期
     *  3.回弹效果可修改曲线值来调整效果，推荐一个好用的bezier生成工具 http://cubic-bezier.com/
     */
    coverTouchstart(e) {
      if (pageAtTop === false) {
        return;
      }
      this.coverTransition = "transform .1s linear";
      startY = e.touches[0].clientY;
    },
    coverTouchmove(e) {
      moveY = e.touches[0].clientY;
      let moveDistance = moveY - startY;
      if (moveDistance < 0) {
        this.moving = false;
        return;
      }
      this.moving = true;
      if (moveDistance >= 80 && moveDistance < 100) {
        moveDistance = 80;
      }

      if (moveDistance > 0 && moveDistance <= 80) {
        this.coverTransform = `translateY(${moveDistance}px)`;
      }
    },
    coverTouchend() {
      if (this.moving === false) {
        return;
      }
      this.moving = false;
      this.coverTransition = "transform 0.3s cubic-bezier(.21,1.93,.53,.64)";
      this.coverTransform = "translateY(0px)";
    },
    /**
     * 拨打电话
     */
    callPhone(tel) {
      uni.makePhoneCall({
        phoneNumber: tel
      });
    },
    /**
     * 跳转到优惠券或者礼品卡
     */
    async navigateToPage(type, url) {
      // type 1:优惠券 2:礼品卡 3:会员中心, 4:会员权益明细
      const token = uni.getStorageSync("token") || "";
      if (!token) {
        uni.removeStorageSync("token");
        this.$refs["login-popup"].open();
        // uni.navigateTo({
        //   url: "/pages/user/login"
        // });
        return;
      }
      const urlMap = {
        1: "/pages/coupon/index",
        2: "/pages/giftCardList/index",
        3: "/subPackages/common/member/index",
        4: "/subPackages/common/member/detail",
        5: ""
      };
      console.log("url :>> ", url);
      const query = url ? { url } : { url: urlMap[type] };
      if ([1, 2].indexOf(type) > -1) {
        // 优惠券 礼品卡点击埋点
        const eventName = "MINI_MyPageAccountColumnBtnClick";
        const eventData =
          type === 1
            ? { type: "coupon", buttons_name: "优惠券" }
            : { type: "giftcard", buttons_name: "礼品卡" };
        saTrackEvent(eventName, eventData);
      }
      // #ifdef MP-WEIXIN
      if (type === 5) {
        this.showPoint = false;
        const [res] = await getFincialData();
        uni.navigateToMiniProgram({
          appId: "wx7c92f8bed76ea778",
          path: "/pages/vccCardBag/index",
          extraData: {
            fromAPPID: uni.getAccountInfoSync().miniProgram.appId,
            fromPage: "pages/user/user",
            params: {
              appName: "yxm",
              token: res.token || "",
              bind: res.bind,
              code: res.code || "",
              phoneNo: res.phoneNo || "",
              uuid: res.uuid || "",
              userId: res.userId || "",
              tenantId: uni.getStorageSync("tenantId"),
              channel: res.vccChannel || ""
            },
            needQuery: ["phoneNo", "token"]
          },
          envVersion: "trial"
        });
        return;
      }
      // #endif
      const method = "navigateTo";
      if (query.url) {
        uni[method](query);
      }
    }
  }
};
</script>
<style lang="scss">
@keyframes fadeinout {
  0% {
    opacity: 0.3;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}
.face-recognition {
  display: flex;
  justify-content: space-between;
  font-size: 22rpx;
  color: #ed6a0c;
  background: #fffbe8;
  margin: 10rpx 20rpx 0;
  height: 60rpx;
  line-height: 60rpx;
  margin-bottom: 26rpx;
  padding-left: 10rpx;
  border-radius: 10rpx;
  button {
    margin-top: 10rpx;
    margin-right: 10rpx;
    width: 120rpx;
    height: 40rpx;
    display: inline-block;
    line-height: 34rpx;
    font-size: 20rpx;
    padding: 0;
    color: #ed6a0c;
    background: #fffbe8;
    border: 1px solid #ed6a0c;
    border-radius: 10rpx;
    text {
      font-size: 22rpx;
    }
  }
}
.btn-position {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
}
.color-gray {
  color: #999;
}
.display-block {
  display: block;
}
.user-info {
  display: flex;
  align-items: center;
}
.user-config {
  margin-top: 35rpx;
  .config {
    width: 48rpx;
    height: 48rpx;
    font-size: 48rpx;
    color: #fff;
  }
}
.order-section.cash-out {
  padding: 25rpx 20rpx;
}
.cash-out {
  &-text image {
    vertical-align: 30rpx;
    display: inline-block;
    width: 48rpx;
    height: 40rpx;
  }
  .card-xhk-btn {
    margin-top: 22rpx;
  }
  &-txt {
    color: #666;
    line-height: 1.6;
    font-size: 24rpx;
    display: inline-block;
    margin-left: 20rpx;
  }
  &-raise text {
    color: #333;
    font-size: 40rpx;
    margin: 0 10rpx;
    font-weight: 700;
  }
  &-return {
    color: #999;
    text {
      color: #333;
      margin-left: 10rpx;
    }
  }
}
%flex-center {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
%section {
  display: flex;
  justify-content: space-around;
  align-content: center;
  background: #fff;
  border-radius: 10rpx;
}
.contact-service {
  opacity: 0;
  position: absolute;
  z-index: 9;
  display: block;
  height: 110rpx;
  padding: 0;
}
.xhk-popup {
  font-size: 28rpx;
  text-align: center;
  .declare {
    margin-top: 40rpx;
  }
  button {
    width: 526rpx;
    height: 80rpx;
    line-height: 80rpx;
    border: none;
    color: #fff;
    background-image: linear-gradient(269deg, #ff5d00 12%, #ff1900 86%);
    border-radius: 40rpx;
    margin: 32rpx 0;
  }
}
.card {
  &-box {
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 24rpx;
  }
  &-title {
    display: flex;
    justify-content: space-between;
    height: 85rpx;
    line-height: 85rpx;
    padding: 0 24rpx;
    border-bottom: 1rpx solid rgba(216, 216, 216, 0.3);
    text {
      font-size: 28rpx;
      align-self: center;
      color: $font-color-dark;
      font-weight: 700;
    }
  }
  &-info {
    font-size: 24rpx;
    color: #999;
    .arrows {
      font-size: 24rpx;
      color: #ccc;
    }
  }
  &-xhk-btn {
    width: 180rpx;
    height: 60rpx;
    line-height: 58rpx;
    border-radius: 40rpx;
    border: 1rpx solid #ec1500;
    font-size: 14px;
    color: #ec1500;
    text-align: center;
    background: #fff;
    margin-top: 11rpx;
    margin-right: 0;
  }
  &-xhk-btn.disabled {
    opacity: 0.7;
    background: #fff;
    color: rgba(236, 21, 0, 0.7);
    border: 1rpx solid rgba(236, 21, 0, 0.7);
  }
  &-footer {
    display: flex;
    justify-content: space-between;
    padding: 0 20rpx;
    height: 84rpx;
    line-height: 84rpx;
    border-top: 1rpx solid rgba(216, 216, 216, 0.3);
    text {
      font-size: 24rpx;
      color: #666;
    }
  }
}
.xhk {
  &-state {
    position: relative;
    display: flex;
    padding: 0 20rpx 20rpx;
  }
  &-icon {
    width: 52rpx;
    height: 36rpx;
    margin-top: 45rpx;
  }
  &-title {
    margin-top: 26rpx;
    margin-left: 16rpx;
    font-size: 24rpx;
    color: #666;
    width: 500rpx;
    text {
      line-height: 1.7;
    }
  }
  &-txt {
    font-size: 24rpx;
    color: #666666;
  }
  &-bold {
    font-weight: 400;
    color: #333;
    font-size: 32rpx;
  }
}
.main-list {
  position: relative;
  margin-top: -50rpx;
  &.yxm {
    margin-top: 0;
  }
}
.user-section {
  height: 548rpx;
  padding: 186rpx 24rpx 0;
  position: relative;
  &.unlogin {
    height: 440rpx;
  }
  .bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    animation: fadeinout 0.3s linear forwards;

    // filter: blur(1px);
    // opacity: .7;
  }
}

.vip-card-box {
  display: flex;
  flex-direction: column;
  color: #f7d680;
  // height: 240rpx;
  // background: linear-gradient(to left, rgba(0,0,0,.7), rgba(0,0,0,.8));
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  padding: 20rpx 24rpx;
  .card-bg {
    position: absolute;
    top: 20rpx;
    right: 0;
    width: 380rpx;
    height: 260rpx;
  }
  .b-btn {
    position: absolute;
    right: 20rpx;
    top: 16rpx;
    width: 132rpx;
    height: 40rpx;
    text-align: center;
    line-height: 40rpx;
    font-size: 22rpx;
    color: #36343c;
    border-radius: 20px;
    background: linear-gradient(to left, #f9e6af, #ffd465);
    z-index: 1;
  }
  .tit {
    font-size: $font-base + 2rpx;
    color: #f7d680;
    margin-bottom: 28rpx;
    .yticon {
      color: #f6e5a3;
      margin-right: 16rpx;
    }
  }
  .e-b {
    font-size: $font-sm;
    color: #d8cba9;
    margin-top: 10rpx;
  }
}
.cover-container {
  background: $page-color-base;
  padding: 0 30rpx;
  padding-bottom: 20rpx;
  .arc {
    position: absolute;
    left: 0;
    top: -34rpx;
    width: 100%;
    height: 36rpx;
  }
}
.tj-sction {
  @extend %section;
  .tj-item {
    @extend %flex-center;
    flex-direction: column;
    height: 140rpx;
    font-size: $font-sm;
    color: #75787d;
  }
  .num {
    font-size: $font-lg + 8;
    color: $font-color-dark;
    margin-bottom: 8rpx;
    font-weight: 700;
  }
}
.order-section {
  @extend %section;
  padding: 25rpx 0;
  .order-item {
    @extend %flex-center;
    position: relative;
    width: 120rpx;
    height: 120rpx;
    border-radius: 10rpx;
    font-size: $font-sm;
    color: $font-color-dark;
    image {
      width: 80rpx;
      height: 80rpx;
      display: block;
    }
    .num {
      min-width: 32rpx;
      // height: 16px;
      height: 36rpx;
      background: red;
      box-sizing: border-box;
      color: #fff;
      border: 1rpx solid #fff;
      font-size: 20rpx;
      text-align: center;
      // line-height: 14px;
      line-height: 28rpx;
      padding: 0 10rpx;
      border-radius: 20rpx;
      display: inline-block;
      position: absolute;
      top: 3rpx;
      right: 14rpx;
      border: 4rpx solid #fff;
    }
  }
  .yticon {
    font-size: 48rpx;
    margin-bottom: 18rpx;
    color: #fa436a;
  }
  .icon-shouhoutuikuan {
    font-size: 44rpx;
  }
}
.history-section {
  padding: 30rpx 0 0;
  margin-top: 20rpx;
  background: #fff;
  border-radius: 10rpx;
  .sec-header {
    display: flex;
    align-items: center;
    font-size: $font-base;
    color: $font-color-dark;
    line-height: 40rpx;
    margin-left: 30rpx;
    .yticon {
      font-size: 44rpx;
      color: #5eba8f;
      margin-right: 16rpx;
      line-height: 40rpx;
    }
  }
  .h-list {
    white-space: nowrap;
    padding: 30rpx 30rpx 0;
    image {
      display: inline-block;
      width: 160rpx;
      height: 160rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
    }
  }
}

.auth-info__mask {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  height: 100%;
  // background: rgba(0, 255, 255, 0.288);
}

.user-qinghai {
  /* padding-top: 120rpx; */
  .user-qinghai-content {
    position: relative;
    /* height: 286rpx; */
    /* margin: 140rpx 30rpx 30rpx 30rpx; */
    margin: 20rpx 30rpx 30rpx;
    padding: 46rpx 24rpx 24rpx;
    /* background: #5371E0; */
    background-image: linear-gradient(269deg, #ff5d00 12%, #ff1900 86%);
    border-radius: 8px;
    border-radius: 16rpx;
    overflow: hidden;
    &::before {
      content: "";
      background-color: $white;
      width: 517px;
      height: 473px;
      position: absolute;
      left: -210px;
      top: -410px;
      border-radius: 50%;
      overflow: hidden;
      opacity: 0.12;
      background: $white;
    }
  }
}
.main-qinghai {
  margin-top: 0;
}
// 新增优惠券、礼品卡模块
.coupon-info {
  width: 100%;
  height: 172rpx;
  background: #fff;
  border-radius: 12rpx;
  display: flex;
  &-item {
    width: 50%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .detail {
      position: relative;
      display: flex;
      align-items: baseline;
      // margin-bottom: 12rpx;
      height: 60rpx;
      .point {
        position: absolute;
        top: -12rpx;
        right: -12rpx;
        width: 12rpx;
        height: 12rpx;
        background: linear-gradient(269deg, #ff5d00 12%, #ff1900 86%);
        border-radius: 50%;
      }
      .cardbag-icon {
        position: absolute;
        top: -28rpx;
        right: -28rpx;
        width: 28rpx;
      }
      .text-desc {
        position: absolute;
        top: -30rpx;
        right: -50rpx;
        height: 28rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 6rpx;
        background: linear-gradient(269deg, #ff5d00 12%, #ff1900 86%);
        border-radius: 14rpx 14rpx 14rpx 0;
        font-size: 20rpx;
        color: $white;
        text-align: center;
        word-break: keep-all;
      }
      &-number {
        font-size: 36rpx;
        color: #333;
        font-weight: 600;
      }
      &-unit {
        font-size: 20rpx;
        color: #333;
      }
    }
    .desc {
      font-size: 24rpx;
      color: #666;
    }
  }
}
// .auth-info {
//   width: 622rpx;
//   padding: 0 40rpx;
//   &__mask {
//     position: absolute;
//     top: 0;
//     left: 0;
//     z-index: 10;
//     width: 100%;
//     height: 100%;
//     // background: rgba(0, 255, 255, 0.288);
//   }
// &__tip {
//   color: #666;
//   font-size: 28rpx;
//   line-height: 40rpx;
//   text-align: center;
//   padding: 24rpx 0 48rpx;
// }
// &__agree {
//   background: linear-gradient(270deg, #ff5d00 0%, #ff1900 100%);
//   height: 72rpx;
//   border-radius: 36rpx;
//   color: #fff;
//   font-size: 28rpx;
//   line-height: 72rpx;
// }
// &__cancel {
//   font-size: 28rpx;
//   color: #ec1500;
//   line-height: 40rpx;
//   text-align: center;
//   padding: 24rpx 0 36rpx;
// }
// }
</style>
