import merchant from "@/api/https/merchant";
import { setStorage, jx_default_storage_plugin, getStorage, cleatStorage } from "@/utils/storage";
import toast from "@/utils/toast";
import { timeFormatD } from "@/utils/tools";
import { store as newStore, store } from '@/store'
import configCms from "@/utils/configCms";
import Bluetooth from '@/utils/bluetoothPrinter/bluetooth'
import util from '@/utils/bluetoothPrinter/util'
import login from "@/api/https/login";
import { computed } from "vue";
import { emojiAnanlyze } from '@/utils/emoji'

/*************************************************
 * 全局通用方法
 * @param data 事实订单数据
 */
function useGlobalFunc() {
    const bluetooth = new Bluetooth()
    const playVoid = uni.createInnerAudioContext()   // 创建音频实例


    /*************************************************
     * 退出登录
    */
    function logOutFn() {
        cleatStorage('token')
        cleatStorage('userID')
        cleatStorage('userType')
        cleatStorage('storeID')
        cleatStorage('storeName')
        cleatStorage('userID2')
        cleatStorage('mobile')
    }


    /*************************************************
     * 获取实时订单数据
     * @time 2023年2月1日 11点17分
     * @param {data} 请求data数据
     * @return {res} code:响应状态 data:响应数据 desc:错误信息
    */
    async function globGetToDay(data: AnyObject) {
        let orderNumber = await merchant.get_store_order_sale_info(data);
        if (orderNumber.code == 0) {
            return orderNumber.data
        } else {
            toast("实时订单数据异常", 2);
        }
    }

    /*************************************************
     * 查看详情图片
     * @time 2023-02-01 11:18:09
     * @param {}-
     * @return {*}
    */
    async function previewImage(url: string | Array<string>,index?:number) {
        new Promise((resolve, reject) => {
            uni.previewImage({
                current: index ? index : typeof url === 'string' ? url : url[0],
                urls: Array.isArray(url) ? url : [url],
                longPressActions: {
                    itemList: ['保存图片'],
                    success(res) {
                        uni.showModal({
                            title: '相册权限使用说明',
                            content: '便于您保存图片与运营进行交流等场景中写入相册文件内容',
                            complete: (result) => {
                                if (result.confirm) {
                                    uni.saveImageToPhotosAlbum({
                                        filePath: Array.isArray(url) ? url[res.index] : url,
                                        complete(r) {
                                            if (r.errMsg === 'saveImageToPhotosAlbum:ok') {
                                                toast('保存成功')
                                            } else {
                                                toast('保存失败')
                                            }
                                        }
                                    })
                                }
                            }
                        })
                    }
                },
                success: (res: any) => {
                    resolve(res)
                },
                fail: (err: any) => {
                    toast(err)
                    reject(err)
                }
            })
        })
    }


    /*************************************************
     * 存储用户信息
     * @param {object} [data] 用户信息数据
    */
    let serveInfoTimer: any = null
    async function setUserInfo(data: AnyObject) {
        setStorage("token", data.token);
        setStorage("userID", data.userID);
        setStorage("userID2", data.userID2);
        setStorage("mobile", data.mobile);
        jx_default_storage_plugin()
        // 防止ios app 出现认证信息还没有缓存就已经跳转请求了

        let storeRes = await login.get_my_store_list({ version: '1.3.5' })
        let dataList = storeRes.data || []
        if (dataList.length == 0) {
            return uni.jxAlert({
                title: '提示',
                content: '该账号未绑定门店，请联系运营绑定，加盟联系电话18048531223'
            })
        }
        if (dataList.length == 1) {
            let data = dataList[0]
            setStorage("storeID", data.id);
            setStorage('storeName', data.name)
            uni.switchTab({ url: '/pages/merchant/index' })
            return
        }

        clearTimeout(serveInfoTimer)
        serveInfoTimer = setTimeout(() => {
            uni.navigateTo({
                url: "/subPages/switchStore/switchStore",
                animationType: 'slide-in-top',
                animationDuration: 500
            })
        }, 0)
    }


    /*************************************************
     * app 微信登录
     * @bangding {Function} 绑定
     * @seccess {Function} 登录成功
    */
    type appWxLoginType = {
        bangding?: Function
        success?: Function
    }
    function appWxLogin(options: appWxLoginType) {
        if (plus.runtime.isApplicationExist({ pname: 'com.tencent.mm', action: 'weixin://' })) {  // 判断用户是否安装了微信
            // 微信开放平台的应用标识
            // 预登录
            let weixinService: AnyObject
            plus.oauth.getServices((services) => {
                if (services && services.length) {
                    for (var i = 0, len = services.length; i < len; i++) {
                        if (services[i].id === 'weixin') {
                            weixinService = services[i]
                            break
                        }
                    }
                    // 如果没有获取到微信服务，则退出授权
                    if (!weixinService) {
                        return uni.jxAlert({
                            title: '登录失败',
                            content: '请先下载微信',
                        })
                    }

                    // 进行微信授权，拿到 code
                    weixinService.authorize(async (event: AnyObject) => {
                        //此处获取code的关键
                        let data = {
                            authType: "weixinapp",
                            authSecret: event.code,
                        }
                        // event.code 发给后端验证，验证成功后处理业务
                        let res = await login.applets_login(data)
                        console.log('ZSW-res', res);
                        if (res.code == 0) {
                            // 第一次登录绑定手机号码
                            if (res.data.tokenType == 2) {
                                options.bangding && options.bangding(res.data.token)
                            }

                            // 登录成功
                            if (res.data.tokenType != 2) {
                                options.success && options.success(res.data)
                            }
                        } else {
                            if ((res.desc).indexOf('row') == -1) {
                                uni.jxAlert({
                                    title: '提示',
                                    content: `登录失败：${res.desc || res.data}`
                                })
                            } else {
                                uni.jxAlert({
                                    title: '提示',
                                    content: `登录失败：对不起该账号未绑定门店，请联系官方客服进行绑定！`
                                })
                            }

                        }
                    })
                } else {
                    uni.jxAlert({
                        title: '提示',
                        content: '本机不支持微信登录',
                    })
                }
            })
        } else {
            uni.jxAlert({
                title: '提示',
                content: '请先下载微信',
            })
        }
    }


    /*************************************************
     * 全局判断是否有新信息，有信息就在tabar显示
     */
    async function newMessage() {
        let data = {
            storeIDs: JSON.stringify([+getStorage('storeID')]),
            fromReadCount: 0,
            toReadCount: 0,
            offset: 0,
            pageSize: -1,
            fromTime:
                timeFormatD(+new Date() - 7 * 24 * 60 * 60 * 1000) + ' 00:00:00',
            toTime: timeFormatD(+new Date()) + ' 23:59:59',
        }
        let msgRes = await merchant.Get_store_message_statuses(data)
        if (msgRes.code == 0) {
            let num = msgRes.data.totalCount

            // 没有信息，移除
            if (num == 0) {
                store.commit('storeInfo/setIsNewMessage', false)
                uni.removeTabBarBadge({ index: 3 })
            } else {
                store.commit('storeInfo/setIsNewMessage', true)
                // 有信息显示
                uni.setTabBarBadge({
                    index: 3,
                    text: num > 100 ? '99+' : '' + num,
                })
            }
        }
    }


    /**************************************************************
     * 复制订单信息内容
     * @param {String} data 需要复制的内容
     * @param {String} [text] 复制成功提示内容(非必填)
     * @param {string} [errorT] 复制失败提示内容(非必填)
     */
    function copyInfo(data: string, text = '复制成功', errorT = '复制失败') {
        uni.setClipboardData({
            data: data,
            success() {
                toast(text)
            },
            fail() {
                toast(errorT)
            }
        })
    }


    /************************************************************
     * 拨打电话
     * @param {string} phoneNumber 将要拨号的手机号
     * @param {String} [text] 拨号成功提示内容(非必填)
     * @param {string} [errorT] 拨号失败提示内容(非必填)
     */
    function phoneCall(phoneNumber: string, text = '拨号完成', errorT = '取消拨号') {
        uni.jxConfirm({
            title: '拨打电话权限说明',
            content: '便于您快速地跳到拨号界面与运营进行交流',
            success() {
                uni.makePhoneCall({
                    phoneNumber: phoneNumber,
                    success() {
                        console.log(text)
                    },
                    fail() {
                        toast(errorT)
                    }
                })
            }
        })

    }


    /*************************************************
     * 打开微信小程序
     * @param {string} [url] 跳转地址
     * @param {string} [id] 小程序原始ID
    */
    function openWeixin(url: string, id = 'gh_e9161397303e') {
        if (plus.runtime.isApplicationExist({ pname: 'com.tencent.mm', action: 'weixin://' })) {  // 判断用户是否安装了微信
            // 跳转到微信小程序进行物料申请
            plus.share.getServices(function (res) {
                var sweixin = null;
                for (var i = 0; i < res.length; i++) {
                    var t: AnyObject = res[i];
                    if (t.id == 'weixin') {
                        sweixin = t;
                    }
                }
                if (sweixin) {
                    sweixin.launchMiniProgram({
                        id: id,                 //这里写你的小程序原始id（以gh开头）
                        type: 0,				//这里是不同的环境（ 0-正式版； 1-测试版； 2-体验版。 默认值为0。）
                        path: url,              //这里是指 定页的路径，如需传参直接字符串拼接（首页可以省略）
                    });
                }
            }, function (res) {
                uni.jxAlert({
                    title: '提示',
                    content: '打开小程序失败',
                })
            });
        } else {
            uni.jxAlert({
                title: '温馨提示',
                content: '请先下载微信',
            })
        }
    }


    /*************************************************
     * 判断门店是否在营业中
     * @param {any} [newTime] 需要判断的时间
    */
    function isTrades(newTime: any): boolean {
        let storeInfo = newStore.state.storeInfo.allStoreInfo
        let businessTime: Array<any> = []
        businessTime[0] = storeInfo.openTime1
        businessTime[1] = storeInfo.closeTime1
        businessTime[2] = storeInfo.openTime2
        businessTime[3] = storeInfo.closeTime2

        // 获取当前时间进行比较
        let honer = newTime.getHours()
        let minutes = newTime.getMinutes() < 10 ? '0' + newTime.getMinutes() : newTime.getMinutes()
        let time: number = +(String(honer) + String(minutes))
        if (
            (time >= businessTime[0] && time <= businessTime[1]) || (time >= businessTime[2] && time <= businessTime[3])
        ) {
            return true      // 未休息
        } else {
            return false     // 休息中
        }
    }


    /*************************************************
     * 获取当前app是否选哟更新
     * @return {Boolean} isUpdate 是否需要进行更行
    */
    async function watchVersion(fn: Function) {
        let res = await merchant.get_app_varsion({ appId: configCms.appId })
        let systemInfo = uni.getSystemInfoSync()
        let version = ''
        let versions:AnyObject = {}
        if(systemInfo.platform === 'android'){
            versions = JSON.parse(res.data[0].value).update
            version = versions.version
        }else{
            version = JSON.parse(res.data[0].value).other.appName.split(',')[1]
        }
        let versionInfo = compareVersions(version,systemInfo.appVersion)
        if (versionInfo) {
            fn && fn(true, versions)
        } else {
            fn && fn(false, versions)
        }
    }

    function compareVersions(v1: string, v2: string) {
        var regEx = /(\.0)+[^\.]*$/
        var v1parts = v1.replace(regEx, '').split('.')
        var v2parts = v2.replace(regEx, '').split('.')
        for (var i = 0; i < v1parts.length; ++i) {
            if (v2parts.length == i) {
                return true
            }
            if (v1parts[i] == v2parts[i]) {
                continue
            } else if (v1parts[i] > v2parts[i]) {
                return true
            } else {
                return false
            }
        }
        if (v1parts.length != v2parts.length) {
            return false
        }
        return false
    }


    /*************************************************
     * 格式化今日订单数据
    */
    function wholeCalcPrice(calcData: AnyObject) {
        if (calcData.isPointStore) {
            if (calcData.isNotQuote || calcData.isZero) {
                return calcData.actualPayPrice
                    ? (calcData.actualPayPrice / 100).toFixed(2)
                    : 0;
            } else {
                if (calcData.isUpperfif) {
                    return calcData.earningPrice
                        ? (calcData.earningPrice / 100).toFixed(2)
                        : 0;
                } else {
                    return "请按平台查看";
                }
            }
        } else {
            if (calcData.isUpperfif || calcData.isZero) {
                return calcData.earningPrice
                    ? (calcData.earningPrice / 100).toFixed(2)
                    : 0;
            } else {
                return "请按平台查看";
            }
        }
    }


    /*************************************************
     * 格式化今日订单数据
    */
    function singleCalcPrice(calcData: AnyObject) {
        if (calcData.vendorPayPercentage != 0) {
            if (calcData.vendorPayPercentage < 50) {
                return (calcData.actualPayPrice / 100).toFixed(2)
            } else {
                return (calcData.earningPrice / 100).toFixed(2)
            }
        } else {
            if (calcData.isPointStore) {
                return (calcData.actualPayPrice / 100).toFixed(2)
            } else {
                return (calcData.earningPrice / 100).toFixed(2)
            }
        }
    }


    /*************************************************
     * 查询打印机状态并连接
    */
    function setPrinterStatus() {
        // 获取打印机信息
        let data: any = getStorage('commitBTDevCharact')
        setInterval(() => {
            let isPlay = store.state.storeInfo.isConnectPrinter
            // 判断打印机是否在线
            util.notifyBLEState(data.deviceId, data.serviceId, data.uuid)
                .then(async (res) => {
                    if (res != 12) {
                        console.log('连接失败')
                        await bluetooth.reconnect()
                        if (!isPlay) return
                        playVoidFn()
                        store.commit('storeInfo/setIsConnectPrinter', false)
                    } else {
                        console.log('连接正常')
                        store.commit('storeInfo/setIsConnectPrinter', true)
                    }
                }).catch(async () => {
                    console.log('连接失败')
                    await bluetooth.reconnect()
                    if (!isPlay) return
                    playVoidFn()
                    store.commit('storeInfo/setIsConnectPrinter', false)
                })
        }, 1000 * 20)
    }
    // 播放音频
    function playVoidFn() {
        playVoid.src = '/static/audio/close_printer.mp3'
        playVoid.stop()
        playVoid.play()
    }

    // ******************** 判断是否有淘鲜达 *****************************
    //#region 
    const storeMaps = computed(() => {
        return store.state.storeInfo.allStoreInfo
    })
    // function isTxd() {
    //     let state = false
    //     storeMaps.value.StoreMaps.forEach((item: AnyObject) => {
    //         if (item.vendorID == 16) {
    //             state = true
    //         }
    //     })
    //     return state
    // }
    //#endregion

    /**
     * 查询美团/饿百的IM状态
     */
    const getMtStoreIMStatus = async () => {
        let mtStore = isExistPlatformID(1)
        let ebStore = isExistPlatformID(3)
        let data = []
        if (mtStore && mtStore.length > 0) {
            data.push({
                vendorID: 1,
                vendorOrgCode: mtStore[0].vendorOrgCode + '',
                vendorStoreID: mtStore[0].vendorStoreID + ''
            })
        }

        if (ebStore && ebStore.length > 0) data.push({
            vendorID: 3,
            vendorOrgCode: ebStore[0].vendorOrgCode + '',
            vendorStoreID: ebStore[0].vendorStoreID + ''
        })
        if (data.length === 0) return
        let res = await merchant.get_mt_store_im_status({ data: JSON.stringify(data) })
        let arr: any = []
        if (res.code === '0') {

            res.data.forEach((item: AnyObject) => {
                if (item.errMsg && item.errMsg) arr.push({
                    ...item,
                    vendorID: +item.errMsg.substring(0, 1)
                })
                else arr.push({ ...item })
            })
        }
        store.commit('storeInfo/setImOnlineStatus', arr)
    }

    /**
     * 是否存在某个平台
     */
    function isExistPlatformID(platformID: number) {
        return storeMaps.value.StoreMaps.filter((item: AnyObject) => item.vendorID == platformID)
    }


    /**
     * 是否含有聊天表情
     */
    function isCloudEmoji(emoji: string) {
        let emojiArr = emoji.match(/\[(.+?)\]/g)
        return emojiArr && emojiArr.length > 0 ? true : false
    }

    interface emojiType {
        type: string,
        text: string,
        emoji: string
    }

    /**
     * 解析emoji数据
     */
    function analyEmoji(emoji: string) {
        if (!isCloudEmoji(emoji)) {
            return [
                {
                    type: 'text',
                    text: emoji,
                    emoji: ''
                }
            ]
        }

        // emoji = '[大哭][大哭][大哭][大哭][心碎][心碎][心碎]11111顶顶顶顶呃零零零零[流泪]iiiihdhggydgjfg kevbuygbhjbnb'

        let arr: emojiType[] = []

        let emojiArr: string[] = emoji.match(/\[(.+?)\]/g) || []
        if (emojiArr && emojiArr.length > 0) {
            emojiArr.map((item, index) => {
                let emojiImg = emojiAnanlyze(item)  // 返回的emoji解析数据
                if (emojiImg === item) emojiImg = 'unknown:' + emoji    // 未知表情
                let indexOf = emoji.indexOf(item)   // item在聊天emoji中的位置

                if (indexOf === 0) {
                    // emoji
                    arr.push({
                        type: 'emoji',
                        text: '',
                        emoji: emojiImg
                    })

                    // emoji之后的文字
                    let afterSymbol = emoji.substring(indexOf + item.length, indexOf + item.length + 1)
                    if (afterSymbol !== '[' && afterSymbol.length > 0 && index === emojiArr.length - 1) {
                        arr.push({
                            type: 'text',
                            text: emoji.substring(indexOf + item.length),
                            emoji: ''
                        })
                    }
                } else {
                    // emoji之前的文字
                    arr.push({
                        type: 'text',
                        text: emoji.substring(0, indexOf),
                        emoji: ''
                    })

                    // emoji
                    arr.push({
                        type: 'emoji',
                        text: '',
                        emoji: emojiImg
                    })

                    // emoji之后的文字
                    let afterSymbol = emoji.substring(indexOf + item.length, indexOf + item.length + 1)
                    if (afterSymbol !== '[' && afterSymbol.length > 0 && index === emojiArr.length - 1) {
                        arr.push({
                            type: 'text',
                            text: emoji.substring(indexOf + item.length),
                            emoji: ''
                        })
                    }
                }
                emoji = emoji.replace(emoji.substring(0, indexOf + item.length), '')    // 清除已处理完的数据
            })
        }
        return arr || []
    }

    return {
        logOutFn,                   // 全局公用方法
        globGetToDay,               // 获取实时订单数据
        previewImage,               // 查看详情图
        setUserInfo,                // 储存用户信息
        appWxLogin,                 // app 微信登录
        openWeixin,                 // 打开微信小程序
        watchVersion,               // 检查是否有新版本
        newMessage,                 // 展示新信息
        copyInfo,                   // 复制信息
        phoneCall,                  // 拨打电话
        isTrades,                   // 判断是否是在营业时间
        wholeCalcPrice,             // 格式化今日订单数据
        singleCalcPrice,            // 格式化今日订单数据
        setPrinterStatus,           // 查询打印机状态并连接
        // isTxd,                      // 判断是否有淘鲜达
        getMtStoreIMStatus,         // 获取美团IM单聊状态
        isExistPlatformID,          // 是否含有平台门店
        analyEmoji,                 // 解析emoji表情
        isCloudEmoji                // 是否含有emoji
    }
}


export default useGlobalFunc