/**
 * 蓝牙打印订单
 */
import { getStorage } from '../storage'
import toast from '../toast'
import { store } from '@/store'
import { jx_trembling, timeFormatD, timeFormatHMS } from '../tools'
import urlConfig from "@/api/config";
import useGlobalFunc from '@/composables/useGlobalFunc'
import useOrderInfo from '@/composables/useOrderInfo'
import order from '@/api/https/order';
const { isTrades } = useGlobalFunc()
const { bluetoothPrinter } = useOrderInfo()


/*********************************************新订单提示********************************************
 * @desc 使用递归形式，或者使用定时器的方式来写，循环去请求接口，如果没有新数据立马结束本次请求
 */
// 准备来新订单播放的音频
const newOrderMp3 = uni.createInnerAudioContext()


// abort() 需要使用这个方法来中断请求
let listen: any = null



/*************************************************************************
 * 监听新订单，使用递归的方式监听
 */
export let listenOrder: any = async () => {
    // 定义变量判断门店是否在印业状态
    console.log('监听订单信息')
    // 判断店铺是否在线
    let storeInfo = store.state.storeInfo.allStoreInfo
    let currentFlag: boolean = isTrades(new Date())

    // 判断如果没有登录或者是没有 storeID 就停止递归监听
    if (!getStorage('storeID') || !getStorage('token')) return false

    // 无网络不监听
    if (!store.state.serveInfo.isNetWork) return false

    try {
        // 定义一个变量来保存数据
        interface NewOrderDataType {
            storeID: string
            waitingSecond: number
            lastOrderTime?: string
            lastOrderSeqID?: number
        }
        let newOrderData: NewOrderDataType = {
            storeID: getStorage('storeID'),
            waitingSecond: 86400
        }
        newOrderData.lastOrderTime = timeFormatHMS(+new Date())
        // 开始进入递归监听
        if (listen) listen.abort() // 中断请求
        listen = uni.request({
            url: urlConfig + '/v2/cms/GetNewOrderMsg',
            data: newOrderData,
            header: {
                token: getStorage('token')
            },
            success: ({ data }) => {
                let { code, data: res } = (data as AnyObject)
                if (code == 0) {
                    // 刷新订单页面
                    store.commit('serveInfo/setUpdateOrder', Date.now())
                    res = JSON.parse(res)
                    // 判断是否是tabBar页面
                    if (getCurrentPages().length == 1) {
                        uni.setTabBarBadge({ index: 0, text: '新' })
                    }
                    console.log('订单状态发生改变', JSON.stringify(res,undefined,4))
                    shake()
                    // 新订单，语音播报提醒，其他处理操作
                    if (res.Type === 'newOrder') {
                        console.log('监听订单信息')
                        getPrintOrders()
                        // 判断门店是否处于营业状态，设置是否禁用了语音播报，当前门店是不是在休息
                        if (storeInfo.status == 1 && currentFlag && getStorage('isPlayShound')) {
                            newOrderMp3.src = 'https://image.jxc4.com/image/e640abe4c40032490264674da03434af.jpg'
                            newOrderMp3.stop()
                            newOrderMp3.play()
                        }
                    } else if (res.Type === "newWait4ApproveAfsOrder") {
                        // 售后单待处理
                        if (storeInfo.status == 1 && currentFlag && getStorage('isPlayShound')) {
                            newOrderMp3.src = 'https://image.jxc4.com/image/0a6fe4e82f2905e42012074f66f81698.jpg'
                            newOrderMp3.stop()
                            newOrderMp3.play()
                        }
                    } else {
                        // 订单状态发生改变
                        if (storeInfo.status == 1 && currentFlag && getStorage('isPlayShound')) {
                            newOrderMp3.src = 'https://image.jxc4.com/image/dafc928fa23d688ce71aa645f9b77c90.jpg'
                            newOrderMp3.stop()
                            newOrderMp3.play()
                        }
                    }
                    listenOrderThrottles()
                } else {
                    // 发生错误继续监听
                    listenOrderThrottles()
                }
            },
            fail: (error) => {
                // 如果不是主动中断请求就继续监听
                if (!error.errMsg.includes('abort')) {
                    listenOrderThrottles()
                }
            }
        })

    } catch (error) {
        toast('系统发生错误请重启应用')
    }
}


// 节流防止重复播报
let newListFun: any = null
let listenOrderThrottles = jx_trembling(() => {
    newListFun = listenOrder
    listenOrder()
    listenOrder = null
    listenOrder = newListFun
}, 5000)





/**********************使用蓝牙打印机进行打印************************
 * 
 */
// 获取订单数据
let getOrderJson = {
    storeIDs: JSON.stringify([getStorage('storeID')]),
    fromDate: timeFormatD(+new Date()),
    toDate: timeFormatD(+new Date()),
    statuss: JSON.stringify([5, 10, 15, 17, 18, 20, 22]),
    offset: 0,
    pageSize: -1
}


/*************************************************
 * 连续震动提醒
*/
function shake() {
    let timer: any = null
    let timer1: any = null
    uni.vibrateLong({
        success: () => {
            clearTimeout(timer)
            timer = setTimeout(() => {
                uni.vibrateLong({
                    success: () => {
                        clearTimeout(timer1)
                        timer1 = setTimeout(() => {
                            uni.vibrateLong({})
                            clearTimeout(timer1)
                        }, 700)
                    }
                })
                clearTimeout(timer)
            }, 700)
        }
    })
}


/*************************************************
 * 打印订单
*/
async function getPrintOrders() {
    if (!getStorage('deviceName')) return
    // bluetoothPrinter(getOrderJson, 2)
    let orderRes = await order.get_orders(getOrderJson)
    console.log('新订单信息',JSON.stringify(orderRes,undefined,4))
}