/**
 * 全局文件配置
 */
import { store } from '@/store'
import { setStorage, getStorage } from "@/utils/storage";
import Bluetooth from '@/utils/bluetoothPrinter/bluetooth'
import useGlobalFunc from './composables/useGlobalFunc';
import { onShow } from '@dcloudio/uni-app';
import useOrderInfo from './composables/useOrderInfo';
import util from '@/utils/bluetoothPrinter/util'



function App() {
    const bluetooth = new Bluetooth()
    const { setPrinterStatus } = useGlobalFunc()
    const { bluetoothPrinter,orderDetail } = useOrderInfo()


    /*************************************************
     * 页面出现
    */
    let reconnectTime1: any = null
    onShow(async () => {
        if (getStorage('deviceName')) {
            reconnectTime1 = setTimeout(async () => {
                await bluetooth.reconnect()
                clearTimeout(reconnectTime1)
            }, 1000)
        }
    })


    /**
     * 获取设备信息
     */
    async function SystemInfo() {
        uni.getSystemInfo({
            success(res) {
                setStorage('brand', res.brand || 'pc')
                // 保存本机系统信息
                // 详细字段信息参考 https://uniapp.dcloud.net.cn/api/system/info.html#%E7%B3%BB%E7%BB%9F%E4%BF%A1%E6%81%AF%E7%9A%84%E6%A6%82%E5%BF%B5
                store.commit('serveInfo/setSystemInfo', JSON.stringify(res))
            },
        })
    }


    /*************************************************
     * 监听网络类型
    */
    function onNetWorkStatusChange() {
        uni.onNetworkStatusChange((res) => {
            if (res.isConnected == false) {
                uni.createPushMessage({
                    title: '网络提示',
                    content: '网络被断开，请检查网络设置'
                })
            } else {
                plus.push.clear()
            }
            store.commit('serveInfo/setIsNetWorkS', res.isConnected)
        })
    }


    /*************************************************
     * 应用保活常驻通知栏
    */
    function appKeepAlive() {
        let port = uni.getSystemInfoSync()
        switch (port.platform) {
            case 'android':
                const JModule = uni.requireNativePlugin('J-FrontService')
                JModule.startFrontService({
                    title: '京西到家',
                    content: '京西到家正在运行',
                })

                // 设置oppo通道
                if (port.brand == 'oppo' || port.brand == 'oneplus' || port.brand == 'pacm00') {
                    const plugin = uni.requireNativePlugin("DCloud-PushSound")
                    plugin.setCustomPushChannel({
                        soundName: "neworder",
                        channelId: "10110",
                        channelDesc: "订单类通知提醒",
                        enableLights: true,
                        enableVibration: true,
                        importance: 4,
                        lockscreenVisibility: 1
                    });
                    plugin.setCustomPushChannel({
                        soundName: "msg",
                        channelId: "10111",
                        channelDesc: "顾客IM信息提示",
                        enableLights: true,
                        enableVibration: true,
                        importance: 4,
                        lockscreenVisibility: 1
                    });
                }
            case 'ios':
                console.log('iOS不支持此功能')
                break
        }

    }


    /*************************************************
     * 监听穿透消息
    */
    // const playVoid = uni.createInnerAudioContext()

    function vendorName(text:string) {
        switch (text) {
            case '京东到家':
                return 0
            case '美团外卖':
                return 1
            // case '淘宝闪购':
            //     return 2
            case '淘宝闪购新零售':
                return 3
            case '京东商城':
                return  5
            case '京西到家':
                return  9
            case '微盟':
                return  11
            case '抖音小时购':
                return  14
            // case '淘鲜达':
            //     return  16
            default:
                return -1
        }
    }

    let orderList:Array<AnyObject> = []    // 20s之内没有新订单，置空
    
    function listenMsg() {
        // 获取cid
        plus.push.getClientInfoAsync((info) => {
            let cid = info["clientid"]
            setStorage('cid', cid)
        }, () => { })
        uni.onPushMessage((res) => {
            // 监听通知信息/
            if (res.type == 'receive') {
                let newData: any = res.data.payload
                if (newData.store_title == getStorage("storeName")) orderList.push(newData)
                if (newData.msg_type == 'newOrder') {
                    let data: any = getStorage('commitBTDevCharact')
                    util.notifyBLEState(data.deviceId, data.serviceId, data.uuid).then((res: any) => {
                        if (res == 12) {
                            if (newData.store_title != getStorage("storeName")) return
                            bluetoothPrinter(newData.vendor_order_id)
                        }
                    })
                }
                // 创建通知
                if (newData.store_title != getStorage("storeName")) return
                if (newData.msg_type == 'newImMsg') {
                    store.commit('storeInfo/setImMessage', newData.context)
                    uni.createPushMessage({
                        title: newData.store_title,
                        content: '有新的顾客信息，请及时查看',
                        icon:'./static/image/global/message.png',
                        payload:{ 
                            page: '/pages/message/index', // 目标页面路径
                            storeID:newData.store_id,
                            storeName:newData.store_title,
                            type:'message'
                        }
                    })
                    uni.showTabBarRedDot({index:2})
                } else {
                    store.commit('serveInfo/setUpdateOrder', Date.now())
                    uni.createPushMessage({
                        title: newData.store_title,
                        content: `${newData.context}（${newData.vendor_name}#${newData.order_sqs}号订单）`,
                        icon:'./static/image/global/newOrder.png',
                        payload:{ 
                            page: '/subPages/orderChild/orderDetail/orderDetail', // 目标页面路径
                            vendorOrderID: '' + newData.vendor_order_id, // 订单id
                            vendorID:vendorName(newData.vendor_name),
                            type:'order'
                        }
                    })
                }
                // if(+getStorage('defaultOrderReminder') === 1 || getStorage('defaultOrderReminder') === '' ){

                let src = `/static/audio/${newData.msg_type}.mp3`
                watchAudio(src) // findIndex
                
                // }
            }

            // 监听通知栏点击
            if (res.type == 'click') {
                let currentOrder:any = res.data.payload
                if(currentOrder.type === 'order') orderDetail(currentOrder.vendorOrderID, currentOrder.vendorID)
                else if(currentOrder.storeID) {
                    setStorage("storeID", currentOrder.storeID)
                    setStorage('storeName', currentOrder.storeName)
                    setStorage('storeMessge', 'message')
                    uni.switchTab({ url: currentOrder.page })
                }
            }
        })
    }

    /**
     * 监听音频播放事件 音频播放结束事件，通知完毕，清除 orderList中的数据 findIndex:number
     */
    let isWait = false
    const watchAudio = (newData:string) => {
        // console.log(isWait,'isWait',newData)
        if(isWait) return  // 阻止多个音频同时播放
        if(newData){
            const playVoid = uni.createInnerAudioContext()
            playVoid.src = newData
            playVoid.volume = 1
            isWait = true
            playVoid.play()
            playVoid.onEnded(() => {
                isWait = false
                orderList.shift()   // 头部删除
                // console.log('音频播放结束事件,依次播放，判断是否还有订单',orderList)
                //  `/static/audio/${newData.msg_type}.mp3`
                // if(orderList.length>0) watchAudio(orderList[0].msg_type)
                if(orderList.length>0) watchAudio(`/static/audio/${orderList[0].msg_type}.mp3`)
               
            })
        }
        
        // 20s之后
    }


    /*************************************************
     * 打印机检测
    */
    let reconnectTime: any = null
    async function onPrinterChange() {
        if (getStorage('deviceName')) {
            setPrinterStatus()
            reconnectTime = setTimeout(async () => {
                await bluetooth.reconnect()
                clearTimeout(reconnectTime)
            }, 1000)
        }
    }


    return {
        SystemInfo,                 // 获取本机系统信息
        onNetWorkStatusChange,      // 监听网络状态
        appKeepAlive,               // 安卓应用保活
        listenMsg,                  // 监听消息
        onPrinterChange,            // 监听打印机状态
    }
}



export default App