// @ts-ignore
import wx from 'weixin-js-sdk';
import request from "~/utils/request";
import Crypto from 'crypto-js';
import {HtyHostHeader, WebViewEntryUrl} from "~/utils/index";
const CACHES: any = {};

const raw = function (args: any) {
    let keys = Object.keys(args);
    keys = keys.sort();
    let newArgs = {} as any;
    keys.forEach(function (key) {
        newArgs[key.toLowerCase()] = args[key];
    });

    let string = '';
    for (let k in newArgs) {
        string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    return string;
};

const sign = function (jsapi_ticket: string, url: string) {
    let ret = {
        jsapi_ticket: jsapi_ticket,
        nonceStr: Math.random().toString(36).substr(2, 15),
        timestamp: Math.floor(new Date().getTime() / 1000).toString(),
        url: url,
    };
    return {...ret, signature: Crypto.SHA1(raw(ret)).toString()}
};

const is_wx_mini = () => navigator.userAgent.includes('miniProgram')

const init = async (apis: string[]) => {
    if (!is_wx_mini()) {
        return;
    }
    let url = window.localStorage.getItem(WebViewEntryUrl) || window.location.href;
    let ticket = CACHES[url];
    if (!ticket) {
        // @ts-ignore
        const {r, d, e} = await request({url: '/api/v1/uc/wx_get_jsapi_ticket', headers: { [HtyHostHeader]: WX_DOMAIN }});
        if (r) {
            CACHES[url] = ticket = d;
        } else {
            console.log("get js tick failed...", e);
        }
    }
    if (ticket) {
        let {timestamp, nonceStr, signature} = sign(ticket, url);

        wx.config({
            // @ts-ignore
            appId: WX_APP_ID, timestamp, nonceStr, signature, jsApiList: apis,
            success: (res: any) => {
                console.log('config res...', res)
            },
            fail: (err: any) => {
                console.log('config err...', err)
            }
        });
        check(apis)
        wx.error(function ({errMsg}: any) {
            console.log('error...', errMsg);
        });
    }
}

const check = (apis: string[]) => {
    wx.checkJsApi({
        jsApiList: apis,
        success: ({checkResult, errMsg}: any) => {
            // console.log('check...', checkResult, errMsg)
        },
        fail: (e: any) => {
            console.log('check failed...', e)
        }
    })
}

const download_image = async (serverId: string) => {
    return new Promise((resolve, reject) => {
        wx.downloadImage({
            serverId,
            isShowProgressTips: 0,
            success: ({localId}: any) => {
                resolve(localId)
            },
            fail: (err: any) => {
                console.log("get local id err...", err)
                reject(err)
            }
        })
    })
}

const get_local_img_data = async (localId: string) => {
    return new Promise((resolve, reject) => {
        wx.getLocalImgData({
            localId,
            isShowProgressTips: 0,
            success: (res: any) => {
                resolve(res.localData)
            },
            fail: (err: any) => {
                console.log(0, "get local data err...", err)
                reject(err)
            }
        })
    })
}

const wxUtil = {
    init, sign, check, is_wx_mini, download_image, get_local_img_data
}

export {wxUtil, wx}

