/*
 * @Description: 公共方法
 * @Author: zhoupeng
 * @Date: 2020-04-21 10:26:10
 * @LastEditTime: 2020-07-21 13:27:07
 */
import wx from 'weixin-js-sdk';
import * as Service from '../services/index';
import Config from '../../../utils/config';
import { Toast } from 'antd-mobile';
import router from 'umi/router';
import { getQueryVariable, getQueryVariableBy, getQueryParamUrl } from '../../../utils/helper';

var AppId = '';
var Timestamp = '';
var Signature = '';
var Noncestr = '';

//分享链接地址
const shareTitle = '宠爱王国会员服务';

//分享链接 （由于在uat、灰度上，有/marketing，做判断）
const shareURL = `${window.location.origin}${
  window.location.origin.indexOf('uat.chongaibao.com') ||
  window.location.origin.indexOf('cabnewappapi.test.chongaibao')
    ? '/marketing'
    : ''
}/#/./ckuh5/scanning?page=index`;

const shareIcon =
  'http://newpetpassport.chongaibao.com/newpetpassportpro/pub/upload/image/e1619456d2e047e6b7d5644e6a0ca465';

//微信登录、判断是否为新用户
export const makeScanning = async () => {
  console.log('makeScanning');

  //记录初始页时，路由长度
  var length = window.history.length ? window.history.length : 0;
  window.sessionStorage.setItem('historyLength', length);

  //1，走授权，获取code
  var code = getQueryVariable('code');

  window.sessionStorage.setItem('queryUrl', window.location.href);

  //2，通过code，获取用户信息。判断用户是否为新用户
  const { rc, msg, data } = await Service.loginByWechat({ code, platform: 'ckuh5' });

  if (rc === Config.constant.codeSuccess) {
    const ckuUserVo = data && data.thirdUser && data.thirdUser.cku ? data.thirdUser.cku : null;

    //存储用户信息
    window.sessionStorage.setItem(
      'access-user',
      ckuUserVo ? JSON.stringify(ckuUserVo) : JSON.stringify({}),
    );
    window.sessionStorage.setItem('openId', data.openId);

    //如果是新用户，注册
    if (!ckuUserVo) {
      //router.push(`index`);
      //router.push(`mobileCode`);
      router.push(`/ckuh5/index`);
      router.push(`/ckuh5/mobileCode`);

      window.sessionStorage.setItem('newUserFlag', 1);
    } else {
      window.sessionStorage.setItem('newUserFlag', 0);
      //1，查询会员和犬舍有效期是否相同
      const { rc: identicalRc, msg: identicalMsg, data: identicalData } = await Service.identical();
      if (!identicalRc) {
        if (identicalData && identicalData.requiredExpireIdentical) {
          router.push(`/ckuh5/index`);
          Toast.offline('查询会员和犬舍有效期不相同，请在APP中操作完成后，再登录', 5);
        } else {
          if (ckuUserVo.authentication === '0') {
            //如果是已注册，但是没有认证
            router.push(`/ckuh5/index`);

            Toast.info('您没有实名认证', 2);
            router.push('/ckuh5/authentication');
          } else {
            //如果是已注册，已认证
            router.push(`/ckuh5/index`);

            const saveUrl = window.sessionStorage.getItem('queryUrl');
            var page = getQueryVariableBy(saveUrl, 'page');
            var params = getQueryParamUrl(saveUrl);

            router.push(`/ckuh5/${page}?fromPage=scanning&${params}`);
          }
        }
      } else {
        Toast.info('拉平接口有误', 1);
      }
    }
  } else {
    Toast.info(msg, 1);
  }
};

//检测是否拉平
export const identical = async callBack => {
  //1，查询会员和犬舍有效期是否相同
  const { rc, msg, data } = await Service.identical();
  if (!rc) {
    if (data && data.requiredExpireIdentical) {
      Toast.offline('查询会员和犬舍有效期不相同，请在APP中操作完成后，再登录', 5);
    } else {
      callBack();
    }
  } else {
    Toast.info('拉平接口有误', 1);
  }
};

//微信授权判断
export const wechatAuthorization = async () => {
  console.log('wechatAuthorization');
  //1，走授权，通过url
  const { rc, data } = await Service.getConfig({
    url: window.location.href.split('#')[0],
  });
  if (rc === 0) {
    AppId = data.appId;
    Timestamp = data.timestamp;
    Signature = data.signature;
    Noncestr = data.noncestr;

    console.log('obj:', AppId, Timestamp, Signature, Noncestr);
    wx.config({
      //beta: true,
      debug: false,
      appId: AppId,
      timestamp: Timestamp,
      nonceStr: Noncestr,
      signature: Signature,
      // 这里是把所有的方法都写出来了 如果只需要一个方法可以只写一个
      jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'chooseWXPay',
        'getLocation',
        'previewImage',
      ],
    });
    wx.ready(function() {
      console.log('设置config成功');

      wx.onMenuShareTimeline({
        title: shareTitle, // 分享标题
        link: shareURL, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareIcon, // 分享图标
        success: function() {
          // 用户点击了分享后执行的回调函数
        },
      });
      wx.onMenuShareAppMessage({
        title: shareTitle, // 分享标题
        link: shareURL, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        desc: '', // 分享描述
        imgUrl: shareIcon, // 分享图标
        type: 'link', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function() {
          // 用户点击了分享后执行的回调函数
        },
      });
    });
    wx.error(function(res) {
      console.log(res);
    });
  }
};

/**
 * @description: 获取会员卡类型
 * @param {type}
 * @return:
 * @author: zhoupeng
 */
const cardTypeObj = {
  '0': '普卡',
  '10': '银卡',
  '20': '金卡',
  '30': '铂金卡',
  '40': '紫金卡',
};
export const getCardTypeCZ = cardType => {
  try {
    return cardTypeObj[cardType] ? cardTypeObj[cardType] : '';
  } catch (e) {
    return '';
  }
};

/**
 * @description: 获取会员类型
 * @param {type}
 * @return:
 * @author: zhoupeng
 */
const memberTypeObj = {
  '10': '爱宠会员',
  '20': '繁育专业会员',
};
export const getMemberTypeCZ = memberType => {
  try {
    return memberTypeObj[memberType] ? memberTypeObj[memberType] : '';
  } catch (e) {
    return '';
  }
};
