<template>
    <view>
        <u-popup title="请连接打印机" v-model="showModel" mode="bottom" height="80%">
            <view class="content">
                <view class="cu-bar bg-white solid-bottom margin-top">
                    <view class="action">
                        <text class="cuIcon-title text-orange"></text>
                        蓝牙列表
                        <u-loading mode="flower" :show="searching" size="36"></u-loading>
                    </view>
                    <view class="action">
                        <u-button @click="searchDevice" v-if="!searching">搜索</u-button>
                        <u-button @click="stopSearch" v-if="searching">停止搜索</u-button>
                    </view>
                </view>
                <view class="cu-list menu sm-border">
                    <view class="cu-item" v-for="(item, index) in bleDevices" :key="index" @click="connect(item.deviceId)">
                        <view class="content">{{ item.name }}</view>
                    </view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import printKit from '@/common/js/kit/print/printKit.js';
import bleKit from '@/common/js/kit/bluetoothKit.js';
import { labelCommand } from '@/common/js/kit/print/labelCommand.js';
export default {
    props: {
        canvasWidth: {
            type: Number,
            default: 70
        },
        canvasHeight: {
            type: Number,
            default: 130
        }
    },
    data() {
        return {
            searching: false,
            showModel: false,
            printing: false,
            bleDevices: [],
            deviceId: '',
        };
    },
    computed: {
        canvasStyle() {
            return {
                width: this.canvasWidth,
                height: this.canvasHeight
            };
        }
    },
    methods: {
		//展示搜索的蓝牙列表
		showBluetoothList() {
			this.showModel = true;
			this.searchDevice();
		},
        async print(width, height, generateContentFunction) {
            this.toPrint(() => {
                let command = new labelCommand(width, height);
                command.setGap(3);
                generateContentFunction(command);
                command.setPagePrint();
                printKit.sendData(command.getData());
                setTimeout(() => {
                    uni.hideLoading();
                }, 2000);
            });
        },
        /**
         * 将纸往前推指定长度
         * @param {Object} height
         */
        async feed(height) {
            this.toPrint(() => {
                let command = new labelCommand(80, 120);
                command.setFeed(height);
                printKit.sendData(command.getData());
                setTimeout(() => {
                    uni.hideLoading();
                }, 1000);
            },'前推中...');
        },
        /**
         * 将纸往前推后拉长度
         * @param {Object} height
         */
        async backFeed(height) {
            this.toPrint(() => {
                let command = new labelCommand(80, 120);
                command.setBackFeed(height);
                printKit.sendData(command.getData());
                setTimeout(() => {
                    uni.hideLoading();
                }, 1000);
            },'回拉中');
        },
        printByCanvasData(canvasData) {},
        async toPrint(callback,tips="打印中...") {
            let isInited = printKit.isInited();
            if (!isInited) {
                this.$u.toast('请连接蓝牙打印机');
                this.showModel = true;
                this.searchDevice();
            }
            await this.printInited();
            uni.showLoading({
                title: tips,
                mask: true
            });
            setTimeout(() => {
                callback();
            }, 300);
        },
        printInited() {
            return new Promise((reslove, rejct) => {
                let i = 0;
                let intervalId = setInterval(() => {
                    if (printKit.isInited()) {
                        clearInterval(intervalId);
                        reslove();
                        return;
                    }
                    // 防止死循环
                    if (i++ > 1000) {
                        clearInterval(intervalId);
                        reject('打印机连接超时');
                    }
                }, 500);
            });
        },
        async connect(deviceId) {
            try {
                await printKit.init(deviceId);
                // 缓存连接
                this.showModel = false;
                this.deviceId = deviceId;
            } catch (err) {
                this.deviceId = '';
                console.error(err);
                this.$u.toast('打印机连接失败');
            } finally {
                uni.hideLoading();
            }
        },
        async searchDevice() {
            this.searching = true;
            // 10s后自动关闭搜索
            setTimeout(() => {
                this.searching = false;
                bleKit.stopSearch();
            }, 10000);
            try {
                await bleKit.open();
                await bleKit.startSearch(devices => (this.bleDevices = devices));
            } finally {
                this.searching = false;
            }
        },
        stopSearch() {
            this.searching = false;
            bleKit.stopSearch();
        },
        async tryAutoConnect() {
            // 自动连接蓝牙
            let deviceId = this.deviceId;
            if (!deviceId) {
                return;
            }
            await bleKit.open();
            await this.searchDevice();
            // 用户已经操作选择了其它蓝牙
            if (this.deviceId != deviceId) {
                return;
            }
            // 当前能搜索到指定的设备
            if (this.bleDevices.some(e => e.deviceId == deviceId)) {
                this.connect(this.deviceId);
            }
        }
    },
    async created() {
        this.tryAutoConnect();
    }
};
</script>

<style></style>
