/**
 * 订单管理hooks
 */

import { getStorage } from "@/utils/storage"
import toast from "@/utils/toast"
import util from "@/utils/bluetoothPrinter/util"
import Bluetooth from '@/utils/bluetoothPrinter/bluetooth'
import printerTemplate from '@/utils/bluetoothPrinter/printerTemplate'
import configCms from "@/utils/configCms"
import order from "@/api/https/order"
import merchant from "@/api/https/merchant"

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


    /************************************************************
     * 拨打电话
     * @param {string} phoneNumber 将要拨号的手机号
     * @param {String} [text] 拨号成功提示内容(非必填)
     * @param {string} [errorT] 拨号失败提示内容(非必填)
     */
    function phoneCall(phoneNumber: string, text = '拨号完成', errorT = '取消拨号') {
        uni.makePhoneCall({
            phoneNumber: phoneNumber,
            success() {
                console.log(text)
            },
            fail() {
                toast(errorT)
            }
        })
    }


    /************************************************************
     * 跳转到详情页
     * @param {string} vendorOrderID 订单id
     * @param {string} vendorID 品牌id
     */
    function orderDetail(vendorOrderID: string, vendorID: string) {
        uni.navigateTo({ url: `/subPages/orderChild/orderDetail/orderDetail?vendorOrderID=${vendorOrderID}&vendorID=${vendorID}` })
    }


    /*************************************************************
     * 跳转到配送管理页面
     * @param {string} vendorOrderID 订单id
     */
    function deliverManager(vendorOrderID: string) {
        uni.navigateTo({ url: `/subPages/orderChild/deliverManager/deliverManager?orderId=${vendorOrderID}` })
    }


    /************************************************************
     * 打印订单
     * @param {string} vendorOrderID 订单号
     * @param {string} vendorID 品牌ID
     */
    async function printerOrder(vendorOrderID: string, vendorID: string) {
        if (getStorage('defaultPrinter') == '0') {
            // 蓝牙打印机
            bluetoothPrinter(vendorOrderID)
        } else if (getStorage('defaultPrinter') == '1') {
            // 网络打印机
            internetPrinter(vendorOrderID, vendorID)
        } else {
            // 手动选择
            uni.jxConfirm({
                title: '选择设备',
                content: '请选择打印设备进行打印',
                confirmText: '网络打印',
                cancelText: '蓝牙打印',
                isReturn: 1,
                success: () => {
                    internetPrinter(vendorOrderID, vendorID)
                },
                fail: () => {
                    bluetoothPrinter(vendorOrderID)
                }
            })
        }
    }

    /**
     * 网络打印
     * @param {string} vendorOrderID 订单号
     */
    async function internetPrinter(vendorOrderID: string, vendorID: string) {
        let res = await order.get_printer_status({
            storeID: getStorage('storeID'),
        })
        if (res.code == 0) {
            if (res.data.printerStatus == 2) {
                let data = {
                    vendorOrderID,
                    vendorID,
                }
                let pOorder = await order.print_order(data)
                if (pOorder.code == 0) {
                    toast('订单发送成功', 1)
                } else {
                    toast('订单发送失败', 2)
                }
            } else {
                let data = {
                    vendorOrderID,
                    vendorID,
                }
                let pOorder = await order.print_order(data)
                if (pOorder.code == 0) {
                    uni.jxAlert({
                        title: '提示',
                        content: '打印机已离线，但订单已推动成功'
                    })
                } else {
                    toast('订单发送失败', 2)
                }
            }
        } else {
            toast('获取打印机数据异常', 2)
        }
    }

    /**
     * 蓝牙打印
     */
    async function bluetoothPrinter(vendorOrderID: any, type = 1) {
        if (getStorage('deviceName')) {
            let data: any
            if (type == 1) {
                data = {
                    vendorOrderID: vendorOrderID
                }
            } else {
                data = vendorOrderID
            }

            let orderRes = await order.get_orders(data)
            if (orderRes.code == 0) {
                getPrinterSku(orderRes.data.data[0])   // 获取订单数据
            } else {
                toast('测试订单数据异常')
            }
        } else {
            toast('未连接打印机')
        }
    }

    // 获取订单数据
    let timer1: any = null
    async function getPrinterSku(orderInfo: AnyObject) {
        let data = {
            vendorOrderID: orderInfo.vendorOrderID,
            vendorID: orderInfo.vendorID
        }
        let skuRes = await merchant.get_order_sku_info(data)
        if (skuRes.code) {
            let data = {
                orderInfo: orderInfo,
                skus: skuRes.data,
            }
            let datas: any = getStorage('commitBTDevCharact')
            getBlechData()
            util.notifyBLEState(datas.deviceId, datas.serviceId, datas.uuid)
                .then(async (res) => {
                    if (res == 12) {
                        toast('正在打印订单')
                        bluetooth.notifyBLECharacteristicValue()    // 订阅蓝牙 notify
                        clearTimeout(timer1)
                        timer1 = setTimeout(() => {
                            writeBLECharacteristicValue(data)   // 向打印机写入数据
                            clearTimeout(timer1)
                        }, 500)
                    } else {
                        toast('打印机异常请检查')
                    }
                })
                .catch(async (error) => {
                    toast(error)
                })
            return

        } else {
            toast('订单商品数据异常')
        }
    }
    // 获取写入标识数据
    function getBlechData() {
        let datas: any = getStorage('commitBTDevCharact')
        bluetooth.deviceId = datas.deviceId
        bluetooth.serviceId = datas.serviceId
        bluetooth.writeId = datas.uuid
    }
    //写入控制命令
    async function writeBLECharacteristicValue(data: AnyObject) {
        let printerCenter = await printerTemplate(data)
        printbuffs(printerCenter)
    }
    // 分包向打印机发送数据
    function printbuffs(buffer: any) {
        // 1.并行调用多次会存在写失败的可能性
        // 2.建议每次写入不超过20字节
        // 分包处理，延时调用
        const maxChunk = 20
        const delay = 20
        for (
            let i = 0, j = 0, length = buffer.byteLength;
            i < length;
            i += maxChunk, j++
        ) {
            let subPackage = buffer.slice(
                i,
                i + maxChunk <= length ? i + maxChunk : length
            )
            setTimeout(printbuff, j * delay, subPackage)
        }
    }
    // 写入数据
    function printbuff(buffer: any) {
        bluetooth.writeBLECharacteristicValue(buffer)
    }


    /************************************************************
     * 转换厂商
     */
    function waybillVendor(
        waybillVendorID: number,
        status: number,
        waybillStatus: number
    ) {
        if (waybillVendorID == -1) {
            if (status < 25 && waybillStatus == 0) {
                return '暂无配送员'
            } else if (waybillStatus >= 20) {
                return '商家自送'
            } else {
                return '暂无配送信息'
            }
        } else {
            return (configCms as AnyObject).serveInfo.vendorName[waybillVendorID]
        }
    }


    /************************************************************
     * 售后详情
     */
    function afterSalesDetaile(afsOrderID: number | string) {
        uni.navigateTo({
            url: `/subPages/orderChild/afterSalesOrderDetail/afterSalesOrderDetail?afsOrderID=${afsOrderID}`,
        })
    }


    return {
        copyInfo,           // 复制内容
        phoneCall,          // 拨号
        orderDetail,        // 查看订单详情
        deliverManager,     // 配送管理
        printerOrder,       // 打印订单
        waybillVendor,      // 转换厂商
        afterSalesDetaile,  // 售后详情
        bluetoothPrinter,   // 打印订单
    }
}


export default useOrderInfo