<template>
    <view>
        <page-standby></page-standby>
        <keyboard-listener style="height: 1px;" @keyup="onKeyup" @keydown="onKeydown"></keyboard-listener>
    </view>
</template>

<script>

import pageStandby from '@/components/index/page_standby.vue';//待机页
import keyboardListener from '@/components/index/keyboard/keyboard_listener.vue'; //键盘监听

import util from "@/utils/util.js"
import dictKeyboard from '@/utils/dictOfKeyboard'
import {
    API
} from "@/utils/api";
import {
    ox
} from "@/utils/server";
import print from "@/utils/print";
let app = getApp();
export default {
    components: {
        'page-standby': pageStandby,
        'keyboard-listener': keyboardListener,
    },
    watch: {
        //已拆分standby到单独页面, 不再需要计算在本nvue页面高度
        // showPageStandby(ov,nv){
        // 	if(nv){
        // 		// #ifdef APP-NVUE
        // 		setTimeout(async()=>{
        // 			dom = weex.requireModule("dom");
        // 			let size = await util.getNvueRefSize(this,dom,"mfooter");
        // 			this.footerHeight = size.height.toFixed(2)
        // 		},200)
        // 		// #endif
        // 	}
        // }
    },
    computed: {
        shopListTotalPrice() {
            let _total = 0
            if (!this.shopList || this.shopList.length < 1) return 0
            this.shopList.forEach(item => {
                _total += item.shopCountPrice
            })
            return _total
        },
        shopListTotalCount() {
            let _total = 0
            if (!this.shopList || this.shopList.length < 1) return 0
            this.shopList.forEach(item => {
                _total += item.shopCount
            })
            return _total
        },
        //已拆分standby到单独页面, 不再需要计算在本nvue页面高度
        // footerHeight(){
        // 	return this.screenHeight - 100
        // }
    },
    data() {
        return {
            // showPageStandby: false,
            showQRInputBox: false,
            showEndPhoneBox: false,
            screenHeight: '',
            footerHeight: '',
            // globalData: app.globalData,
            globalData: "",
            shopList: [],
            decryptList: [],
            strResult: "",
        }
    },
    async onLoad(res) {
        console.log("onload:", res)
		// this.searchGoodBySku = util.searchGoodBySku
        // this.test()
        // this.showPageStandby = true
    },
    async onReady() {
        // this.screenHeight = await util.getPageHeight()
        console.log(`the index page onReady----` + this.screenHeight,uni.getStorage("stadiumInfo"))
        app = getApp();
        setTimeout(async () => {
            // await this.updateGoodsList().then(async () => {
            //     // console.log("skulist:", this.shopList)
            // })
        }, 100)
    },
    methods: {
        async setTestSku() {
            console.log("Test set SKU 10000012")
            let skulist = await this.searchGoodBySku("10000012")
            this.shopList = this.shopList.concat(skulist)
        },
        searchGoodBySku: async (sku) => {
            let {brand_id,stadium_id,token} = util.getPostParams()
            let urlParams = {
                brand_id,token,stadium_id,
                "sku": sku,
            }
            console.log("searchGoodBySku urlParams:", urlParams)

            return ox.post({
                url: API.getGoodsBySKU,
                data: urlParams,
                isDefaultGet: true,
                failMsg: '操作失败！'
            })
            .then(res => {
                util.hideLoad();
                console.log("searchGoodBySku suc: ", res)
                res = [res]
                //为列表中每一项设置shopCountPrice,shopCount
                res.forEach(item => {
                    item.shopCount = 1
                    // item.shopCountPrice = item.erp_goods.erp_goods_price
                    item.shopCountPrice = item.user_price
                })
                return res
            })
        },
        combinedList(list1, list2) {

            console.log("combinedList", list1, list2)
            if (!list2) return util.showNone("未找到商品")

            let _list = list1
            list2.forEach(item => {
                let _index = _list.findIndex(_item => _item.id == item.id)
                if (_index != -1) {
                    _list[_index].shopCount += 1
                    _list[_index].shopCountPrice = _list[_index].user_price * _list[_index].shopCount
                } else {
                    _list.push(item)
                }
            })
            return _list
        },

        // 按键松开事件
        async onKeyup(event) {
            console.log("按键松开: ", event)
            // decryptList, strResult
            let res = dictKeyboard.dict[event.keyCode];
            console.log("keyCode from keyboard:", res);
            this.decryptList.push(res);
            if (event.keyCode != 13) {
                return console.log("继续接收:", this.decryptList)
            };
            this.decryptList.pop();
            this.strResult = await dictKeyboard.resultScan(this.decryptList);
            console.log("扫码结果-step-1:", this.strResult)
            this.orderQrcode = this.strResult
            console.log("decryptList-before-splice: ", this.decryptList)
            this.decryptList.splice(0);
            console.log("decryptList-after-splice: " + this.decryptList)

            //过滤结果中的down_arrow
            if (this.strResult.indexOf("down_arrow") != -1) {
                this.strResult = this.strResult.replace("down_arrow", "")
            }
            console.log("扫码结果-step-2:", this.strResult)

            let skulist = await this.searchGoodBySku(this.strResult).then(res => {
                console.log("searchGoodBySku suc: ", res)
                return res
            }).then(skulist => {
                this.addSkuListToShopList(skulist);
                // return skulist
            }).catch(err => {
                console.log("searchGoodBySku err: ", err)
                // util.showNone("未找到商品")
				util.showNone(err.res.data?.message||"未找到商品-s")
            })
            //将skulist合并到shopList
            // this.shopList = this.combinedList(this.shopList, skulist)
            // this.shopList = this.shopList.concat(skulist)

        },
        //跳转index页面,并将商品列表传递过去
        addSkuListToShopList(skulist) {
            console.log("addSkuListToShopList", skulist)
            skulist = encodeURIComponent(JSON.stringify(skulist))
            uni.reLaunch({
                url: `/pages/index/index?skulist=${skulist}`,
                animationType: 'zoom-fade-out',
                animationDuration: 300
            });
            
        },

        // 监听按键按下事件
        onKeydown(event) {
            // console.log("按键按下: ", event)
        },
        // 业务逻辑
        getGoodFromPad(sku, brand_id) {
            return ox.post({
                url: API.getGoodFromPad,
                data: {
                    sku,
                    brand_id
                },
                isDefaultGet: true
            })
                .then(res => {
                    util.hideLoad();
                    if (res.data.code == 0) { }
                    return res
                })
        },
        // 更新商品列表
        async updateGoodsList() {
            let _list = await this.getGoodsList()
            //打印信息
            console.log("app.globaldata: ", app.globalData)
            app.globalData.goodsList = _list
        },
        // 更新购物车列表
        updateShopList() {
            app.globalData.shopList = this.shopList
        },
        getGoodsList() {
            let url =
                "https://testmanager.ouxuanzhineng.cn/admin/erpRetailGoods/list?brand_id=63&stadium_id=167&type_key=&key=&page=1&page_size=9999&is_sale=1&is_show_on_assistant=1&token=e6cabeae-0c1a-11ee-aa40-5254005df464";
            // let urlParams = util.getUrlParams(url);
            // console.log("getGoodsList需要适配urlParams:", urlParams)
			let {brand_id,stadium_id,token} = util.getPostParams()
			let urlParams = {
				brand_id,stadium_id,token,
				"type_key": "",
				"key": "",
				"page": "1",
				"page_size": "9999",
				"is_sale": "1",
				"is_show_on_assistant": "1",
			}
            return ox.post({
                url: API.getGoodsList,
                data: urlParams,
                isDefaultGet: true,
                failMsg: "获取商品列表失败"
            })
			.then(res => {

				util.hideLoad();
				console.log("getGoodsList suc: ", res)
				
				if(!res.list||res.list.length==0){//无商品
					return uni.showModal({
						title: '提示',
						content: "该门店暂无商品,请尝试更换门店",
						success: function (res) {
							if (res.confirm) {
								console.log('用户点击确定');
								util.routeTo('/pages/login/index','rL')
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}else{
					//为res.list中每一项设置shopCountPrice,shopCount
					res.list.forEach(item => {
						item.shopCount = 1
						item.shopCountPrice = item.user_price
					})
					return res
				}


			})
        },


    }
}
</script>

<style lang="scss" scoped></style>