/**
 * 蓝牙打印机
 */
import { store } from '@/store'
import { cleatStorage, getStorage, setStorage } from '@/utils/storage'
import toast from '@/utils/toast'
import { versionCompare, jx_throttles } from '@/utils/tools'
import { onLoad } from '@dcloudio/uni-app'
import { ref, onBeforeUnmount } from 'vue'
import Bluetooth from '@/utils/bluetoothPrinter/bluetooth'
import util from '@/utils/bluetoothPrinter/util'
import useOrderInfo from '@/composables/useOrderInfo'
import useGlobalFunc from '@/composables/useGlobalFunc';


function printerSetUp() {
    const bluetooth = new Bluetooth()
    const { bluetoothPrinter } = useOrderInfo()
    const { setPrinterStatus } = useGlobalFunc()

    /**
     * 查看版本是否支持
     */
    onLoad(() => {
        // 获取本机信息
        let sysInfo = JSON.parse(store.state.serveInfo.sysInfo)
        if (
            sysInfo.platform == 'android' &&
            versionCompare('4.3.0', sysInfo.osVersion)
        ) {
            uni.jxAlert({
                title: '温馨提示',
                content: '当前系统版本过低，请升级',
                success: () => {
                    uni.navigateBack()
                }
            })
        }
        if (
            sysInfo.platform == 'ios' &&
            versionCompare('4.3.0', sysInfo.osVersion)
        ) {

        }


        // 当前设备名称  打印机id
        printerName.value = newPrinterName()
        printerVID.value = getStorage('deviceId')

        // 检查当前蓝牙状态
        bluetooth.openBluetoothAdapter()
    })
    function newPrinterName(): string {
        let name = getStorage('deviceName')
        if (name) {
            return name
        } else {
            return '请选择设备'
        }
    }


    /**
     * @desc 搜索蓝牙
     */
    const blueToothChecked = ref<boolean>(false)
    function initBlue() {
        uni.jxConfirm({
            title: '位置/设备信息权限说明',
            content: '便于搜索您附近的蓝牙设备（含打印功能），在连接成功后，可以进行订单信息的打印',
            success() {
                initBlueThrottles()
            }
        })
    }

    const initBlueThrottles = jx_throttles({
        time: 5000,
        success: () => {
            bluetooth.openBluetoothAdapter().
                then((res) => {
                    setupTwo()  // 进入第二步
                })
                .catch((error) => {
                    toast(error)
                })
        }, fail: (t: number) => {
            toast(`请${t}秒后再试`)
        }
    })


    /**
     * @desdc 第二步初判断本机蓝牙是否可用
     */
    function setupTwo() {
        util.getBTAdapterState()
            .then((res: any) => {
                if (res.available) {
                    if (res.discovering) {
                        bluetooth.stopBluetoothDevicesDiscovery()       // 停止搜索蓝牙
                    } else {
                        setupTherr();
                    }
                } else {
                    toast('本机蓝牙不可用')
                }
            })
            .catch((error) => {
                toast(error)
            })
    }


    /**
     * @desdc 第三步开始获取附近蓝牙
     */
    function setupTherr() {
        bluetooth.startBluetoothDevicesDiscovery()
            ?.then((res) => {
                setupFour()
            }).
            catch((error) => {
                toast(error,)
            })
    }


    /**
     * @desdc 第四步获取附近连接或者没有连接过的蓝牙
     */
    interface SetDataType {
        list: Array<any>,
        services: Array<any>,
        serviceId: number,
        writeCharacter?: boolean,
        readCharacter?: boolean,
        notifyCharacter?: boolean,
    }
    const setData = ref<SetDataType>({
        list: [],
        services: [],
        serviceId: 0,
        writeCharacter: false,
        readCharacter: false,
        notifyCharacter: false,
    })
    const isScanning = ref<boolean>(false)
    let setupFourTimer: any = null
    function setupFour() {
        isScanning.value = true     // 正在搜索
        uni.showLoading({
            title: '正在搜索蓝牙...',
            mask: true
        })
        clearTimeout(setupFourTimer)
        setupFourTimer = setTimeout(() => {
            bluetooth.getBluetoothDevices()
                .then((res: any) => {
                    var devices = [];
                    var num = 0;
                    for (var i = 0; i < res.devices.length; ++i) {
                        if (res.devices[i].name != "" && res.devices[i].localName != "") {
                            devices[num] = res.devices[i];
                            devices[num].RSSI = Math.floor(max(0, devices[num].RSSI + 100) / 10)
                            num++;
                        }
                    }

                    setData.value.list = devices
                    bluetooth.stopBluetoothDevicesDiscovery()   // 停止搜索
                })
                .catch((error) => {
                    toast(error)
                })
                .finally(() => {
                    isScanning.value = false          // 搜索完成
                    uni.hideLoading()
                })
        }, 2000)
    }
    // 信号大小
    function max(n1: number, n2: number) {
        return Math.max(n1, n2)
    }

    /**
     * @desc 第五步
     * 开始链接蓝牙
     */
    const printerName = ref<string>('')         // 打印机名字
    const printerVID = ref<string>('')          // 打印机ID
    const serviceList = ref<Array<AnyObject>>([])
    async function linkBLE(deviceId: string, deviceName: string) {

        bluetooth.deviceId = deviceId
        serviceList.value = []

        try {
            //1.链接设备
            await bluetooth.createBLEConnection()

            uni.showLoading({
                title: '正在获取蓝牙设备服务',
            })
            //2.寻找服务
            await bluetooth.getBLEDeviceServices().then((res) => {
                uni.hideLoading()
                serviceList.value = res
                res.forEach((item: AnyObject) => {
                    getBLEDevCharact(deviceId, item.uuid, deviceName)
                })
            })
        } catch (e) {
            uni.hideLoading()
            uni.jxAlert({
                title: '提示',
                content: '连接失败,请重试,或者先断开其他已经连接的设备'
            })
        }
    }

    // 获取特征值
    let timer: any = null
    function getBLEDevCharact(deviceId: string, serviceId: string, deviceName: string) {
        let json = {
            deviceId,
            serviceId,
            deviceName,
            uuid: ''
        }
        uni.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: res => {
                res.characteristics.forEach(item => {
                    // 同时要有读写监听的权限
                    if (item.properties.read && item.properties.write && item.properties.notify) {
                        // 找到需要的特征
                        json.uuid = item.uuid
                        setStorage('commitBTDevCharact', json)
                        toast('连接成功')
                        setPrinterStatus()
                        store.commit('storeInfo/setIsConnectPrinter', true)
                        printerName.value = deviceName
                        printerVID.value = deviceId
                        setStorage('deviceId', deviceId)
                        setStorage('deviceName', deviceName)
                        clearTimeout(timer)
                        timer = setTimeout(() => {
                            setState()
                            clearTimeout(timer)
                        }, 2500)
                    }
                })
            },
            fail: error => {
                printerName.value = '请选择设备'
                printerVID.value = ''
                toast('获取打印机权限失败请重试')
            }
        })
    }


    /**
    * 设备状态
    */
    function setState() {
        let data: any = getStorage('commitBTDevCharact')
        util.notifyBLEState(data.deviceId, data.serviceId, data.uuid)
            .then((res) => {
                switch (res) {
                    case 12:
                        toast('打印机正常')
                        break
                    case 32:
                        toast('打印机缺纸')
                        break
                    case 36:
                        toast('开盖、缺纸')
                        break
                    case 16:
                        toast('打印机开盖')
                        break
                    case 40:
                        toast('打印机未启动')
                        break
                    default:
                        toast('设备断开')
                }
            })
            .catch((error) => {
                toast(error)
                printerName.value = '请选择设备'
                printerVID.value = ''
            })
    }


    /**
     * 测试打印
     */
    let timer1: any = null
    function testPrint() {
        util.getBTAdapterState()
            .then(async () => {
                bluetoothPrinter('901234567890123')
            })
            .catch(() => {
                uni.jxAlert({
                    title: '提示',
                    content: '请打开蓝牙和定位'
                })
            })
    }


    /*************************************************
     * 断开蓝牙连接
    */
    function closeBLE(deviceId: string) {
        printerName.value = '请选择设备'
        printerVID.value = ''
        cleatStorage('deviceId')
        cleatStorage('deviceName')
        cleatStorage('commitBTDevCharact')
        bluetooth.deviceId = deviceId
        bluetooth.closeBLEConnection()
    }


    /*************************************************
     * 清除打印机缓存
    */
    function clearPrinter() {
        cleatStorage('deviceId')
        cleatStorage('deviceName')
        cleatStorage('commitBTDevCharact')
        uni.jxAlert({
            title: '提示',
            content: '清除缓存成功，请重新启动软件!',
            success: () => {
                plus.runtime.restart()
            }
        })
    }


    /*************************************************
     * 收尾工作
    */
    onBeforeUnmount(() => {
        clearTimeout(setupFourTimer)
        clearTimeout(timer)
        clearTimeout(timer1)
    })


    return {
        printerName,        // 当前打印机名字
        blueToothChecked,   // 动态监听蓝牙开关
        initBlue,           // 初始化蓝牙
        setData,            // 蓝牙列表
        setState,           // 设备状态
        linkBLE,            // 选择蓝牙
        closeBLE,           // 断开蓝牙
        testPrint,          // 测试打印
        printerVID,         // 打印机ID
        isScanning,         // 是否正在搜索打印机
        clearPrinter,       // 清除缓存
    }
}


export default printerSetUp