// import { ApiResponse, get, post } from './request';
// import { get,post } from '@/utils/request-kip.js'
import wx from './js_sdk/weixin';
import request from '@/utils/request-kip.js';
const get = request.get;
const post = request.post;
import store from '@/store';
import { getMobileOperatingSystem, getQueryParam, isInWeixinH5 } from '@/utils';
import CryptoJS from 'crypto-js';
// crypto-js/sha1
// import { Token } from './config/tokenManager';

const OAUTH_PREFIX = '/oauth/v1';

/*
 手机号+验证码登录
 params: {
 phoneNumber: string;
 jsCode?: string;
 verifyCode: string;
 }
 */
export function login(params) {
  // request.post(url, params, {contentType: 'form', ...DEFAULT_CONFIG, noToken: true});
  return request.post(`${OAUTH_PREFIX}/auth/phone-login`, params, {
    isAuthRequest: true,
    isHandleError: false,
  });
}

//
/*
 手机号+验证码登录，微信公众号内H5页面用
 params: {
 phoneNumber: string;
 authCode: string;
 verifyCode: string;
 }
 : Promise<{ code: string, data: Token }>
 */
export function loginWeixinH5(params) {
  return request.post(`${OAUTH_PREFIX}/auth/subscription-phone-login`, params, {
    isAuthRequest: true,
    isHandleError: false,
  });
}

/*
 params: {
 encryptedData: string;
 iv: string;
 jsCode: string;
 }

 : Promise<{ code: string, data: Token }>
 */
export function loginByWxOnClick(params) {
  return request.post(`${OAUTH_PREFIX}/auth/authorized-phone-login`, params, {
    isAuthRequest: true,
    isHandleError: false,
  });
}

/*
 jsCode: string
 : Promise<{ code: string, data: Token }>
 */
export function getLoginTokenByWxCode(jsCode) {
  return request.post(
    `${OAUTH_PREFIX}/auth/openid-login`,
    { jsCode },
    { isAuthRequest: true, isHandleError: false }
  );
}

/*
 微信公众号内H5页面用
 authCode: string
 : Promise<{ code: string, data: Token }>
 */
export function getLoginTokenByWxCodeH5(authCode) {
  return request.post(
    `${OAUTH_PREFIX}/auth/subscription-code-login`,
    { authCode },
    { isAuthRequest: true, isHandleError: false }
  );
}

/*
 refresh_token: string

 : Promise<ApiResponse<Token>>
 */
export function updateToken(refresh_token) {
  return request.post(
    `${OAUTH_PREFIX}/oauth/renewToken`,
    { refreshToken: refresh_token },
    { isAuthRequest: true, isHandleError: false }
  );
}

/*
 TODO mp-weixin中logout需要解绑手机号和openid；app中logout需要吗？
 : Promise<{ code: string, data: Token }>
 */
export function logout() {
  let data = undefined;
  // #ifdef MP-WEIXIN
  data = { removeBinding: 1 };
  // #endif
  // #ifdef H5
  if (isInWeixinH5()) {
    data = { removeBinding: 1 };
  }
  // #endif
  return post(`${OAUTH_PREFIX}/auth/logout`, data, { isLogout: true });
}

// 微信公众号H5获取用户openId - 需要登录
/*
 微信公众号H5获取用户openId - 需要登录
 param: { code: string }

 : Promise<{
 code: string,
 data: string
 }>
 */
export function WxJsOpenId(param) {
  return request.post(`/oauth/v1/wx/config/openId`, param);
}
// 微信公众号H5获取用户openId - 需要登录
// export function WxJsOpenId(param: { code: string }, config?:RequestConfig ): Promise<{
//   code: string,
//   data: string
// }> {
//   return post(`/oauth/v1/wx/config/openId`, param, config);
// }

/**
 * 获取 jsapi_ticket
 * @param access_token
 * @param type
 * @returns {Promise | Promise<unknown>}
 * @constructor
 */
export function WxJsGetTicket({ access_token, type = 'jsapi' }) {
  return request.get(`/cgi-bin/ticket/getticket`, { access_token, type });
}

/**
 * 获取微信token
 * https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
 * @param grant_type
 * @param appid
 * @param secret
 * @returns {Promise | Promise<unknown>}
 */
export function getWxToken({ grant_type, appid, secret }) {
  return request.get(`/cgi-bin/token`, { grant_type, appid, secret });
}

// 签名算法

/**
 *
 * @param noncestr
 * @param jsapi_ticket
 * @param url
 * @returns {string} 签名
 */
export function createWxSign({ noncestr, jsapi_ticket, url, jsApiList }) {
  const params = {
    noncestr,
    jsapi_ticket,
    timestamp: Number.parseInt(new Date().getTime() / 1000),
    url,
  };
  const signArr = ['noncestr', 'jsapi_ticket', 'timestamp', 'url'].sort(); // ['jsapi_ticket', 'noncestr', 'timestamp', 'url']
  let signStr = '';
  signArr.forEach((key, index) => {
    signStr = signStr + `${key}=${params[key]}${index < signArr.length}`;
  });
  const signature = CryptoJS.SHA1(signStr).toString(CryptoJS.enc.Hex);

  return {
    appId: uniq.getStorageSync('appid'),
    timestamp: params.timestamp,
    nonceStr: params.nonceStr,
    signature,
    jsApiList,
  };
}

// H5获取微信签名信息Api - 需要登录

/*
 H5获取微信签名信息Api - 需要登录
 param: { url: string }): Promise<{
 code: string,
 data: {
 appId: string,
 nonceStr: string,
 signature: string,
 timestamp: string,
 url: string
 }
 }>
 */
function WxJsSdkSignature(param) {
  return request.post(`/oauth/v1/wx/config/signature`, param);
}

/*
 jsApiList: string[], openTagList?: string[]


 */
export async function initWxJsSdkConfig(jsApiList = [], openTagList = []) {
  let url = location.href;
  // https://developers.weixin.qq.com/community/develop/doc/000ae2cb950808f90d8bc415551800
  //2. 判断是否为ios 如果为ios且有缓存url 则不做处理
  const isIOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);
  if (isIOS && window.H5_LAUNCH_URL) {
    url = window.H5_LAUNCH_URL;
  }
  // url = url.replace(/http(s)?:\/\//g, '');
  window.wxJsSdkConfigInitPromise = null;
  window.wxJsSdkConfigInitPromise = await WxJsSdkConfig(
    jsApiList,
    url,
    openTagList
  );
}

/*
 weixin jssdk: 通过config接口注入权限验证配置
 jsApiList: string[], url?: string, openTagList?: string[]
 : Promise<{ errMsg: "wx.config:OK" }>
 */
async function WxJsSdkConfig(jsApiList = [], url = '', openTagList = []) {
  const res = await WxJsSdkSignature({ url: url ? url : location.href }); // 这个接口需要登录！
  let debug = false;
  try {
    debug = uni.getStorageSync('WX_JSSDK_DEBUG') || false;
  } catch {}
  return new Promise((resolve, reject) => {
    console.log(242, res.data);
    console.log(243, '当前页面的url', window.location.href);
    wx.config({
      debug,
      appId: res.data.appId,
      // appId: 'wx907c27f16841a919',
      timestamp: res.data.timestamp,
      nonceStr: res.data.nonceStr,
      signature: res.data.signature,
      jsApiList,
      openTagList: openTagList ? openTagList : [],
    });
    wx.ready(function () {
      // 来自微信官方文档：
      // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，
      // 所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
      // eslint-disable-next-line no-console
      console.log('wx.ready');
      resolve({ errMsg: 'wx.config:OK' });
    });
    wx.error(function (err) {
      // eslint-disable-next-line no-console
      console.log('err');
      console.log(err);
      reject(err);
    });
  });
}

// 将 wx.uploadImage 上传的图片转存到阿里云OSS
// 后端调用的

/*
 param: { appId: string, mediaId: string }

 : Promise<{
 videoUrl: string
 }>
 */
export function WxJsUploadMediaToOSS(param) {
  return request.get(`/oauth/v1/wx/config/wechat/h5/mediaUrl`, param);
}

/*
 // 使用微信 jssdk 选择及上传图片
 // https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#17


 count: number,
 sizeType: ['original', 'compressed'] | ['compressed'] | ['original'],
 sourceType: ['album', 'camera'] | ['album'] | ['album'],
 loadingText?: string

 : Promise<{ message: string, ossUrls: string[] }>
 */
export async function wxChooseImageAndUpload(
  count,
  sizeType,
  sourceType,
  loadingText
) {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: count,
      sizeType,
      sourceType,
      // : { localIds: string[] }
      success: (res) => {
        if (loadingText) {
          setTimeout(() => {
            uni.showLoading({
              title: loadingText,
            });
          }, 100);
        }
        const localIds = res.localIds;
        // eslint-disable-next-line no-console
        console.log('----00---', res.localIds);
        const serverIds = [];
        const ossUrls = [];
        let i = 0;
        const length = localIds.length;
        const upload = () => {
          wx.uploadImage({
            localId: localIds[i],
            isShowProgressTips: 0,
            // : { serverId : string}
            success: async (resUpload) => {
              serverIds.push(resUpload.serverId);
              // eslint-disable-next-line no-console
              console.log('----01---', serverIds.join(';'));
              const resOssUpload = await WxJsUploadMediaToOSS({
                appId: store.state.appId,
                mediaId: resUpload.serverId,
              });
              ossUrls.unshift(resOssUpload.videoUrl);
              // eslint-disable-next-line no-console
              console.log('----02---', serverIds.join(';'), ossUrls);
              //如果还有照片，继续上传
              i++;
              if (i < length) {
                upload();
              } else {
                resolve({ message: '', ossUrls: ossUrls });
              }
            },
            fail: (resFail) => {
              // eslint-disable-next-line no-console
              console.log('----03---', resFail);
              reject(resFail);
            },
          });
        };
        upload();
      },
      fail: (resFail) => {
        // eslint-disable-next-line no-console
        console.log('----04---', resFail);
        reject(resFail);
      },
    });
  });
}

// 微信H5 - 获取openId
// TODO 临时方案，微信H5登录做好后要改
export function getOpenIdInH5() {
  // #ifdef H5
  const OPENID_KEY = store.state.appId + '-openid';
  const LANDING_PAGE = '/pages/weixin-h5/order';
  const openId = uni.getStorageSync(OPENID_KEY);
  if (openId) {
    // eslint-disable-next-line no-console
    console.log('openId in H5:', openId);
    return;
  }

  const query = getQueryParam();
  const fullPath = location.href.replace(location.origin, '');
  if (fullPath.indexOf(LANDING_PAGE) == 0) {
    return;
  }

  const redirect_uri =
    location.origin +
    LANDING_PAGE +
    '?appId=' +
    store.state.appId +
    '&redirect_uri=' +
    encodeURIComponent(fullPath);
  const state = 'abc123';

  const url =
    `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${store.state.appId}` +
    `&redirect_uri=${encodeURIComponent(
      redirect_uri
    )}&response_type=code&scope=snsapi_userinfo` +
    `&state=${state}#wechat_redirect`;

  location.href = url;
  // #endif
}
