import wx from 'weixin-js-sdk'
import { getWxCodeUrl } from '@/api/account'
import { client, isAndroid } from './client'
import { wxJsConfig } from '@/api/app'
import { objectToQuery } from './util'
import { useAppStore } from '@/stores/app'
import { ClientEnum } from '@/enums/appEnums'
export enum UrlScene {
    LOGIN = 'login',
    PC_LOGIN = 'pcLogin',
    BIND_WX = 'bindWx',
    BASE = 'base'
}
const wechatOa = {
    _authData: {
        code: '',
        scene: ''
    },
    setAuthData(data: any = {}) {
        this._authData = data
    },
    getAuthData() {
        return this._authData
    },
    getSignLink() {
        if (typeof window.signLink === 'undefined' || window.signLink === '') {
            window.signLink = location.href.split('#')[0]
        }
        return isAndroid() ? location.href.split('#')[0] : window.signLink
    },
    getUrl(
        scene: UrlScene,
        scope = 'snsapi_userinfo',
        extra = {}
    ): Promise<void> {
        const currentUrl = `${location.href}${
            location.search ? '&' : '?'
        }scene=${scene || ''}&${objectToQuery(extra)}`
        return new Promise((resolve, reject) => {
            getWxCodeUrl({
                url: currentUrl,
                scope
            }).then((res) => {
                location.href = res.url
                resolve()
            }, reject)
        })
    },
    config() {
        return new Promise((resolve, reject) => {
            wxJsConfig({
                url: this.getSignLink()
            }).then((res) => {
                wx.config({
                    appId: res.appid, // 必填，公众号的唯一标识
                    timestamp: res.timestamp, // 必填，生成签名的时间戳
                    nonceStr: res.nonceStr, // 必填，生成签名的随机串
                    signature: res.signature, // 必填，签名
                    jsApiList: res.jsApiList,
                    success: () => {
                        resolve('success')
                    },
                    fail: (res: any) => {
                        reject('wx config is fail')
                    }
                })
            })
        })
    },
    miniProgram: wx.miniProgram,
    ready(): Promise<void> {
        return new Promise( (resolve, reject) => {
            const appStore = useAppStore()
            if (client == ClientEnum.OA_WEIXIN && appStore.getLoginConfig?.loginWay?.includes(1)) {
                // jssdk配置
                this.config()
            }
            wx.ready(() => {
                resolve()
            })
            wx.error(() => {
                reject()
            })
        })
    },
    pay(options: Record<any, any>) {
        return new Promise((resolve, reject) => {
            this.ready()
                .then(() => {
                    wx.chooseWXPay({
                        timestamp: options.timeStamp,
                        nonceStr: options.nonceStr,
                        package: options.packageValue,
                        signType: options.signType,
                        paySign: options.paySign,
                        success: (res: any) => {
                            if (res.errMsg === 'chooseWXPay:ok') {
                                resolve(res)
                            } else {
                                reject(res.errMsg)
                            }
                        },
                        cancel: (res: any) => {
                            reject(res)
                        },
                        fail: (res: any) => {
                            reject(res)
                        }
                    })
                })
                .catch((err) => {
                    reject(err)
                })
        })
    },
    share(options: Record<any, any>) {
        this.ready().then(() => {
            const { shareTitle, shareLink, shareImage, shareDesc } = options
            wx.updateTimelineShareData({
                title: shareTitle, // 分享标题
                link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: shareImage // 分享图标
            })
            // 发送给好友
            wx.updateAppMessageShareData({
                title: shareTitle, // 分享标题
                link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: shareImage, // 分享图标
                desc: shareDesc
            })
            // 发送到tx微博
            wx.onMenuShareWeibo({
                title: shareTitle, // 分享标题
                link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: shareImage, // 分享图标
                desc: shareDesc
            })
        })
    },
    getAddress() {
        return new Promise((reslove, reject) => {
            this.ready().then(() => {
                wx.openAddress({
                    success: (res: any) => {
                        reslove(res)
                    },
                    fail: (res: any) => {
                        reject(res)
                    }
                })
            })
        })
    },
    getLocation() {
        return new Promise((reslove, reject) => {
            this.ready().then(() => {
                wx.getLocation({
                    type: 'gcj02',
                    success: (res: any) => {
                        reslove(res)
                    },
                    fail: (res: any) => {
                        reject(res)
                    }
                })
            })
        })
    },
    hideMenuItems(menuList: string[]) {
        return new Promise((resolve, reject) => {
            this.ready().then(() => {
                wx.hideMenuItems({
                    menuList,
                    success: (res: any) => {
                        resolve(res)
                    },
                    fail: (res: any) => {
                        reject(res)
                    }
                })
            })
        })
    },
    showMenuItems(menuList: string[]) {
        return new Promise((resolve, reject) => {
            this.ready().then(() => {
                wx.showMenuItems({
                    menuList,
                    success: (res: any) => {
                        resolve(res)
                    },
                    fail: (res: any) => {
                        reject(res)
                    }
                })
            })
        })
    }
}

export default wechatOa
