/**多单选择模式-销售出仓 */
export const multiModelMixin = {
    data() {
        return {
            empid: "",
            barcodeInput: "",
            inputSearch: "", // 进仓单搜索输入框
            inputCurrentTarget: null, // 存储输入框target
            pageindex: 0, // 页码
            pagesize: 20, // 每页显示数量
            headerHeight: 0, // 头部栏位高度
            hasSaveBarcodeList: [], // 已保存条码code
            pdaPopupData: [], // pda底部数据弹窗——展示数据
            locationList: [], // 定位列表
            draftData: {}, // 草稿模式储存器
            locationState: { // 当前定位信息
                index: -1,
                value: ""
            },
            popupDetail: {}, // 展示的数据源
            barcodeProperty: {}, // 条码详情属性对照
            // 状态
            confirmLoading: false, // 确认按钮加载状态
            orderConfirmLoading: false, // 确认按钮加载状态
            openTitle: false, // 打开右上角菜单
            showScanStart: false, // 是否开始扫描条码
            showLocation: false, //是否开启定位功能
            showOrderToDelect: false, // 是否开启管理功能
            selOrderVisible: false, // 弹出订单选择窗口
            isFinishSelOrder: true, // 是否加载完搜索列表
            ifLockOutware: false, // 读取全局设置-是否查询发货加锁
            scrollTop: false, // 滚动设置
            
            checkboxToDel: [], // 选单时记录勾选的订单，扫码时记录勾选的条码
            pickerDefaultIndex: 0, // 仓库-picker组件选择值的索引
            storageListPicker: [], // 仓库-picker组件选择的值
            detailType: 0, // 展示的数据属性,0：订单详情；1：包件详情；2：条码详情
            packageProperty: {}, // 包件明细属性对照
            storageVisible: true, //仓库选择展示状态-picker组件
			ifBigBar:false, // 条码打包单检测条件
			bigBarStr: '', // 条码打包单抬头
            bwHeight: null // 虚拟滚动高度
        }
    },
    computed: {
        formatDate(time) {
            return function(time) {
                let date = new Date(time);
                return $lj.dateformat(date, 'yyyy-MM-dd')
            }
        },
        isCountSum(table, type) {
            return function(table, type) {
                let sum = 0;
                for (let i = 0; i < this.dataStorage[table].length; i++) {
                    sum += Number(this.dataStorage[table][i][type]);
                }
                if (sum.toString().indexOf(".") > -1) {
                    if (sum.toString().split(".")[1].length >= 4) {
                        sum = $lj.numberFormat(sum, 4);
                    } else if (sum.toString().split(".")[1].length >= 2){
                        sum = $lj.numberFormat(sum, 2);
                    }
                    return sum;
                } else {
                    return sum;
                }
            }
        },
        showProperty() { // 区分详情类型
            let obj = {};
            switch (this.detailType) {
                case 0:
                    obj = this.orderProperty
                    break;
                case 1:
                    obj = this.packageProperty
                    break;
                case 2:
                    obj = this.barcodeProperty
                    break;
            }
            return obj;
        },
    },
    created() {
        this.empid = $lj.getStorage('user').empid;
    },
    provide() {
        return {
            updateScrollTop:(offset)=> {
                this.scrollTop = {
                allowScroll: true,
                offset,
                complete: ()=> {
                        this.scrollTop = false
                    }
                }
            }
        }
    },
    mounted() {
        // 读取系统选项设置
        this.autoGetOptionValue();
        // 读取草稿模式
        this.dataStorage.userid = $lj.getStorage("user").usercode;
        this.dataStorage.lastLoginAccount = $lj.getStorage("lastLoginAccount");
        this._getDraftModeData(this.draftName);

        let self = this;
        // document.onkeydown = function(event){
        //     if (!self.showScanStart) {
        //         /**聚焦搜索框，搜索订单 */
        //         if (self.$refs.searchOrderInput) {
        //             self.$refs.searchOrderInput.focus();
        //         }
        //     } else {
        //         /**聚焦底部输入框 */
        //         if (self.$refs.barcodeInput) {
        //             self.$refs.barcodeInput.focus();
        //             // 关闭弹出窗体
        //             self.$refs.padPopupDetail.close();
        //             self.$refs.pdaDetail.close();
        //         }
        //     }
        // };
        this.autoScanSetting();
        
        /**监听安卓返回按键 */
        api.addEventListener({
            name: 'keyback'
        }, function(ret, err) {
            self.handleCloseBtn();
        });
        /**设置content高度，便于定位滚动 */
        let height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; //浏览器高度
        this.headerHeight = document.querySelector("header.header").clientHeight;
        this.$refs.barcodeBody.style.marginTop = this.headerHeight + 'px';
        this.$refs.barcodeBody.style.height = height - this.headerHeight - this.$refs.inwareFooter.clientHeight + 'px';
    },
    methods: {
        autoScanSetting(scanCallback, focusCallback) {
            let self = this;
            if (api.deviceName.toUpperCase() == 'MOBYDATA') {
                $lj.registerDecodeReceiver();
                $lj.removeEventListener("longjoeAPI_mobyM71Decoded");
                $lj.addEventListener("longjoeAPI_mobyM71Decoded", (ret) => {
                    if (scanCallback) {
                        scanCallback(ret);
                    } else {
                        if (!self.showScanStart) {
                            /**聚焦搜索框，搜索订单 */
                            self.inputSearch = ret.value.barcodeString;
                            self.handleSearchOrder(self.inputSearch.trim());
                        } else {
                            /**聚焦底部输入框 */
                            self.barcodeInput = ret.value.barcodeString;
                            self.handleFooterInput();
                            // 关闭弹出窗体
                            self.$refs.padPopupDetail.close();
                            self.$refs.pdaDetail.close();
                        }
                    }
                });
            } else {
                document.onkeydown = function(event){
                    if (focusCallback) {
                        focusCallback();
                    } else {
                        if (!self.showScanStart) {
                            /**聚焦搜索框，搜索订单 */
                            if (self.$refs.searchOrderInput) {
                                self.$refs.searchOrderInput.focus();
                            }
                        } else {
                            /**聚焦底部输入框 */
                            if (self.$refs.barcodeInput) {
                                self.$refs.barcodeInput.focus();
                                // 关闭弹出窗体
                                self.$refs.padPopupDetail.close();
                                self.$refs.pdaDetail.close();
                            }
                        }
                    }
                };
            }
        },
        fixbody(obj){
            let tabHeight = document.querySelector(".van-tab") && document.querySelector(".van-tab").offsetHeight || 0;
            this.bwHeight = parseInt(obj.minHeight) - tabHeight;
        },
        /**开启选择删除 */
        handleShowCheckBox() {
            this.showOrderToDelect = true;
            this.openTitle = false;
        },
        /**处理仓库仓位信息 */
        _autoStorageInfo(power) {
            let storageInfo = $lj.getStorage("storageInfo") || {};
            //this.bigBarStr = storageInfo.bigCodeStr.toString().toUpperCase().trim();
            if (storageInfo.storagePower == null || storageInfo.storagePower == "") {
                $lj.toast("该用户的仓库权限不存在 / 该用户不存在");
                return false;
            }
            if (storageInfo.storagePower == "-1") {
                $lj.toast("你没有仓库权限");
                return false;
            }
            // if (power && storageInfo.storagePower != "0") {
            //     for (let i = storageInfo.storageList.length - 1; i >= 0; i--) {
            //         if (storageInfo.storagePower.indexOf(storageInfo.storageList[i].storageid) == -1) {
            //             storageInfo.storageList.splice(i, 1);
            //         }
            //     }
            // }
            return storageInfo;
        },
        /**手动扫描按钮-底部 */
        handleScanBtn() {
			let self = this;
            $lj.openScanner((ret) => {
                setTimeout(() => {
                    self.barcodeInput = ret.content.trim();
                    self.handleFooterInput();
                }, 200);
            })
        },
        /**手动扫描按钮-订单 */
        handleScanOrder() {
			let self = this;
            $lj.openScanner((ret) => {
                setTimeout(() => {
                    let content = ret.content.trim();
                    self.inputSearch = content;
                    self.handleSearchOrder(content);
                }, 200);
            })
        },
        /**生成包件明细匹配验证ID */
        _fnSetMatchID(newData) {
            console.time("添加Matchid-For==>");
            let arrMxList = JSON.parse(JSON.stringify(newData));
            for (let i = 0; i < arrMxList.length; i++) {
                
                let strMarch = this._getMatchID();
                let arrMatchid = strMarch.split(',');
                let strMatchid = "";
                for (let j = 0; j < arrMatchid.length; j++) {
                    strMatchid += arrMxList[i][arrMatchid[j]].toString() + "%";
                }
                arrMxList[i].matchId = strMatchid;
            }
            console.timeEnd("添加Matchid-For==>");
            return arrMxList;
        },
        /**左上角返回按钮——退出页面 */
        _fnCloseBtn(idField, callback) {
            let self = this;
            if (!this.showScanStart) {
                if (this.dataStorage.order.length) {
                    $lj.WarnSound();
                    $lj.selectDialog("退出，并放弃扫描吗？", "是否放弃扫描已添加订单", ["退出", "继续操作"], function(btnIndex) {
                        if (btnIndex == 1) {
                            $lj.closeWin();
                            $lj.setStorage(self.draftName, null);
                        } else if (btnIndex == 2) {
                            return false;
                        }
                    })
                } else {
                    $lj.closeWin();
                    // $lj.setStorage(this.draftName, null);
                }
            } else {
                $lj.WarnSound();
                $lj.selectDialog("退出，并保留新增数据吗？", "提示：新添加未提交的条码可保留至草稿\n(点击空白可取消退出)", ["保留", "不保留"], function(btnIndex) {
                    console.log("btnIndex==>", btnIndex);
                    if (btnIndex == 1) {
                        console.log("保留");
                        /**储存数据 */
                        let orderList = [];
                        for (let i = 0; i < self.dataStorage.order.length; i++) {
                            let obj = {};
                            obj.scid = self.dataStorage.order[i].scid;
                            obj[idField] = self.dataStorage.order[i][idField];
                            orderList.unshift(obj);
                        }
                        let data = {
                            userid: self.dataStorage.userid,
                            lastLoginAccount: self.dataStorage.lastLoginAccount,
                            order: orderList,
                            barcode: self.dataStorage.barcode
                        }
                        $lj.setStorage(self.draftName, data);
                    } else if (btnIndex == 2) {
                        console.log("不保留");
                        $lj.setStorage(self.draftName, null);
                    }

                    if (btnIndex >= 1) {
                        callback && callback();
                        $lj.closeWin();
                    }
                })
            }
        },
        /**读取草稿模式 */
        _getDraftModeData(storageName) {
            let darft = $lj.getStorage(storageName)
            console.log("读取草稿", JSON.stringify(darft));
            if (darft != undefined && darft != null) {
                this.draftData = darft;

                this._autoGetDraftBarcode();
            }
        },
        /**方法：接口汇总，验证错误信息 */
        _fnGetBracodeStartScanning(path, requestBody, alertText, callback) {
            let self = this;
            this.confirmLoading = true;
            this.loadingTips(true);
            $lj.postLJRequest(path, requestBody, function (ret) {
                if (ret) {
                    /**发货订单异常判断 */
                    if (ret.errorMsg && ret.errorMsg.length > 0) {
                        let errormsg = "";
                        for (let i = 0; i < ret.errorMsg.length; i++) {
                            errormsg += `[${ret.errorMsg[i].outwarecode}]: ${ret.errorMsg[i].msg}\n`;
                        }
                        api.alert({
                            title: alertText,
                            msg: errormsg
                        });

                        self.confirmLoading = false;
                        self.loadingTips(false);
                        $lj.FailSound();
                        return false;
                    }
                    // 回调函数
                    if (!callback(ret)) return;

                    self.confirmLoading = false;
                    self.loadingTips(false);
                    self.showScanStart = true;
                }
            }, function(ret) {
                self.confirmLoading = false;
                self.loadingTips(false);
                $lj.FailSound();
            }, true);
        },
        /**方法：读取已保存条码 */
        _fnGetSavedBarcode(savedList, idField) {
            this.hasSaveBarcodeList = [];
            console.log("方法：读取已保存条码", JSON.stringify(savedList));
            for (let i = 0; i < savedList.length; i++) {
                this.hasSaveBarcodeList.push(savedList[i].barcode);
                for (let j = 0; j < this.dataStorage.order.length; j++) {
                    if (savedList[i][idField] == this.dataStorage.order[j][idField]) {

                        let barcode_mx = JSON.parse(JSON.stringify(savedList[i]));

                        let addqty =  barcode_mx.packqty * barcode_mx.qty;
                        let adduqty = typeof(barcode_mx.packuqty) == "undefined" ? 0 : barcode_mx.packuqty * barcode_mx.qty;
                        
                        
                        if (this._fnCountABarcode(j, barcode_mx, addqty, adduqty)) {
                            break;
                        } else {
                            continue;
                        }
                    }
                }
            }
        },
        /**草稿模式：读取草稿条码 */
        _fnGetDraftBarcode(savedList, idField) {
            let self = this;
            // 读取草稿条码
            if (self.draftData.barcode.length) {
                if (savedList.length) {
                    /** 检测草稿模式中的条码是否合法 */
                    let hasInList = self._fnCheckInclude(savedList, "barcode", self.draftData.barcode);
                    // 去重，去除与读取条码重合的条码
                    if (hasInList.length) {
                        for (let i = self.draftData.barcode.length - 1; i >= 0; i--) {
                            let index = hasInList.indexOf(self.draftData.barcode[i].barcode);
                            if (index > -1) {
                                self.draftData.barcode.splice(i, 1);
                                hasInList.splice(index, 1);
                                if (!hasInList.length) {
                                    break;
                                }
                            }
                        }
                    }
                }
                if (!self.draftData.barcode.length) {
                    // 去重后，无草稿条码
                    $lj.toast("草稿条码均已被保存", 1000, "top");
                    $lj.WarnSound();
                } else {
                    // 去重后，还有草稿条码
                    let isAllPass = true;
                    // 验证，检查草稿条码是否在有效扫描范围内
                    for (let i = 0; i < self.draftData.barcode.length; i++) {
                        let hasIndex = self._fnCheckIndex(self.original.barcodeList, "barcode", self.draftData.barcode[i].barcode);
                        if (hasIndex == -1) {
                            $lj.toast("部分草稿条码\n不在有效扫描范围，\n恢复失败", 2500, "middle");
                            $lj.WarnSound();
                            isAllPass = false;
                            break;
                        }
                    }

                    if (isAllPass) {
                        // 恢复，有效草稿条码恢复
                        let msgArr = [];
                        for (let i = 0; i < self.draftData.barcode.length; i++) {
                            for (let j = 0; j < self.dataStorage.order.length; j++) {
                                if (self.draftData.barcode[i][idField] == self.dataStorage.order[j][idField]) {
                                    let barcode_mx = JSON.parse(JSON.stringify(self.draftData.barcode[i]));
                                    let addqty =  barcode_mx.packqty * barcode_mx.qty;
                                    // let adduqty =  barcode_mx.packuqty * barcode_mx.qty;
                                    console.log("进仓单没有packuqty属性：typeof(barcode_mx.packuqty) == undefined", typeof(barcode_mx.packuqty) == undefined);
                                    let adduqty = typeof(barcode_mx.packuqty) == undefined ? 0 : barcode_mx.packuqty * barcode_mx.qty;
                                    
                                    if (!self._fnAddOrderBarcode(j, barcode_mx, addqty, adduqty)) {
                                        msgArr.push(self.draftData.barcode[i].barcode);
                                    }
                                    break;
                                }
                            }
                        }
                        if (msgArr.length) {
                            let errormsg = "";
                            for (let i = 0; i < msgArr.length; i++) {
                                errormsg += `[${msgArr[i]}]\n`;
                            }
                            api.alert({
                                title: "警告:超计划扫描，恢复失败！",
                                msg: errormsg
                            });
                            $lj.WarnSound();
                        } else {
                            $lj.toast("草稿条码成功恢复", 1000, "top");
                            $lj.OkSound();
                        }
                    }
                }
            }
        },
        /**组件：multi-order、barcode-widget，接收多选数据*/
        _autoGetMultiple(data) {
            this.checkboxToDel = data;
            this.showOrderToDelect = Boolean(data.length);
            console.log("checkboxToDel==>", this.checkboxToDel);
        },
        /**组件：multi-order=>关闭多选状态 */
        _fnCloseMulti() {
            this.checkboxToDel = [];
            this.$refs.multiOrder.fnClearSel();
            this.showOrderToDelect = false;
        },
        /**组件：lj-pda-detail=>查看详情 */
        handleShowOrderDetail(item) {
            this.detailType = 0;
            this._fnSetDetail(item);
        },
        /**组件：lj-pda-detail=>查看详情 */
        handleShowPackageDetail(item, index) {
            this.detailType = index;
            this._fnSetDetail(item);
        },
        /**组件：lj-pda-detail=>查看详情 */
        handleShowBarcodeDetail(item) {
            this.detailType = !this.showScanStart ? 1 : 2;
            this._fnSetDetail(item);
        },
        /**组件：lj-pda-detail=>设置详情弹窗信息 */
        _fnSetDetail(item) {
            this.popupDetail = item;
            console.log("展示内容==>", JSON.stringify(item));
            this.$refs.pdaDetail.open();
        },
        /**组件：lj-pda-popup=>点击底部数据，弹窗展示详情 */
        handleShowIndicateDetail(type) {
            let array = [];
            if (type) {
                // 包装汇总
                array = JSON.parse(JSON.stringify(this.dataStorage.package));
            } else {
                // 进仓单汇总
                array = JSON.parse(JSON.stringify(this.dataStorage.order));
            }
            array.sort(function(a) {
                return a.qtySum == a.planqtySum ? 1 : -1;
            });
            console.log("排序后", array);
            this.pdaPopupData = array;
            this.detailType = type;
            this.$refs.padPopupDetail.open();
        },
        /**组件：lj-selorder=>搜索结果——确认事件 */
        actionConfirmOrder(path, requestBody, alertText, callback) {
            if (this.orderConfirmLoading) {
                $lj.toast("查询中...", 1000, "bottom");
                return false;
            }
            let self = this;
            this.orderConfirmLoading = true;
            this.loadingTips(true);
            $lj.postLJRequest(path, requestBody, function (ret) {
                if (ret) {
                    // self.$refs.selorder && self.$refs.selorder.loadingOff();
                    if (ret.errorMsg && ret.errorMsg.length > 0) {
                        let errormsg = "";
                        for (let i = 0; i < ret.errorMsg.length; i++) {
                            errormsg += `[${ret.errorMsg[i].outwarecode}]: ${ret.errorMsg[i].msg}\n`;
                        }
                        api.alert({
                            title: alertText,
                            msg: errormsg
                        });

                        $lj.FailSound();
                        return false;
                    }
                    callback(ret);
                    // self.orderConfirmLoading = false;
                    self.loadingTips(false);
                }
            }, function(ret) {
                self.orderConfirmLoading = false;
                self.loadingTips(false);
                // self.$refs.selorder && self.$refs.selorder.loadingOff();
            }, true);
        },
        /**组件：lj-selorder=>搜索结果——搜索更多 */
        autoLoadMoreOrder(path, requestBody) {
            let self = this;
            $lj.postLJRequest(path, requestBody, function (ret) {
                if (ret) {
                    // console.log("ret.orderList==>", ret.orderList);
                    let orderlength = ret.orderList.length;
                    if (orderlength) {
                        self.original.orderList = self.original.orderList.concat(ret.orderList);
                    }
                    
                    if (orderlength == self.pagesize) {
                        self.isFinishSelOrder = false;
                        self.pageindex++;
                    } else {
                        self.isFinishSelOrder = true;
                    }
                    // $lj.OkSound();
                    $lj.toast("加载成功", 1000, "top");
                }
            });
        },
        /**组件：lj-selorder=>搜索发货单接口 */
        _fnSearchGetOrder(path, requestBody, idField, codeField) {
            let self = this;
            $lj.postLJRequest(path, requestBody, function (ret) {
                if (ret) {
                    console.log("ret.orderList==>", ret.orderList);
                    self.original.orderList = ret.orderList;


                    let length = self.original.orderList.length;
                    if (length >= 2) {
                        self.selOrderVisible = true;
                        
                        if (length == self.pagesize) {
                            self.isFinishSelOrder = false;
                            self.pageindex++;
                        } else {
                            self.isFinishSelOrder = true;
                        }

                        self.$nextTick(function() {
                            self.$refs.selorder.open();
                            
                            $lj.OkSound();
                            $lj.toast("查询成功", 1000, "top");
                        });

                    } else if (length == 1) {
                        // 查重
                        let hasOrder = self._fnCheckIndex(self.dataStorage.order, idField, ret.orderList[0][idField]);
                        if (hasOrder > -1) {
                            self.inputCurrentTarget && self.inputCurrentTarget.select();
                            $lj.WarnSound();
                            $lj.toast("单号:" + ret.orderList[0][codeField] + "已添加");
                        }  else {
                            self.handleConfirmOrder(ret.orderList);
                            self.inputCurrentTarget && self.inputCurrentTarget.select();
                        }
                    } else {
                        self.inputCurrentTarget && self.inputCurrentTarget.select();
                        $lj.WarnSound();
                        $lj.toast("提示：查询失败，暂无结果", 2000, "middle");
                    }
                }
            });

        },
        /**组件：lj-selorder=>关闭监听-关闭弹窗订单选择模块 */
        autoCloseSelOrder() {
            this.selOrderVisible = false;
        },
        /**头部栏目：右上角菜单——打开定位 */
        handleShowLocation() {
            $lj.toast("功能维护中", 2000, "middle");
            // if (this.showScanStart) {
            //     this.openTitle = false;
            //     this.showLocation = true;
            //     this.$refs.multiOrder.fnTabsAction("barcode");
            // }
        },
        /**头部栏目：右侧按钮-关闭状态 */
        handleHeaderRightBtn() {
            if (!this.showScanStart) {
                // 选单状态
                this._fnCloseMulti();
            } else {
                // 开始扫码
                this.$refs.barcodeWidget.fnClearAllList();
                for (let i = 0; i < this.dataStorage.barcode.length; i++) {
                    this.dataStorage.barcode[i].ifcheckbox = false;
                }
            }
        },
        /**头部栏目：右上角菜单——打开管理，批量删除订单 */
        handleShowDelOrder() {
            if (!this.dataStorage.order.length) {
                $lj.toast("提示：请添选单据", 2000, "middle");
                return false;
            }
            this.openTitle = false;
            this.showOrderToDelect = true;
            this.$refs.multiOrder.fnTabsAction("order");
        },
        /**统计：计算订单数据*/
        _fnOrderBoard(targetOrder, waremxList, idField, mtrlField) {
            console.time("统计：计算订单数据==>");
            let orderCodeList = [];
            for (let i = 0; i < targetOrder.length; i++) {
                for (let j = 0; j < waremxList.length; j++) {
                    if (waremxList[j][idField] == targetOrder[i][idField]) {
                        if (!targetOrder[i].hasOwnProperty("children")) {
                            targetOrder[i].children = [];
                            targetOrder[i].barcode = [];
                            targetOrder[i].mtrlware_mx = [];
                            targetOrder[i].qtySum = 0;
                            targetOrder[i].planqtySum = 0;
                        }
                        /**出仓类型-包件按条码 */
                        if (waremxList[j].outtype == 2) {
                            targetOrder[i].qtySum += waremxList[j].qty;
                            targetOrder[i].planqtySum += waremxList[j].planqty;
                        }
                        targetOrder[i].mtrlware_mx.push(waremxList[j][mtrlField]);
                        targetOrder[i].children.push(waremxList[j]);
                    }
                }
                this.dataStorage.order.unshift(targetOrder[i]);
                // this.dataStorage.order.unshift(JSON.parse(JSON.stringify(targetOrder[i])));
                orderCodeList.push(targetOrder[i].outwarecode);
            }
            console.timeEnd("统计：计算订单数据==>");
            console.log("动态生成订单明细：==>", this.dataStorage.order);
            return orderCodeList;
        },
        /**统计：计算包件数据*/
        _fnPackageBoard(newData, idField) {
            console.time("统计包件处理时间==》");
            for (let i = 0; i < newData.length; i++) {
                let hasVal = false;
                // console.log("newData[i]=>", JSON.stringify(newData[i]));

                for (let j = 0; j < this.dataStorage.package.length; j++) {
                    if (this.dataStorage.package[j].matchId == newData[i].matchId) {
                        if (newData[i].outtype == 2) {
                            this.dataStorage.package[j].planqtySum += newData[i].planqty;
                            this.dataStorage.package[j].qtySum += newData[i].qty;
                        }
                        this.dataStorage.package[j].child.push(newData[i]);
                        if (this.dataStorage.package[j].order.indexOf(newData[i][idField]) == -1) {
                            this.dataStorage.package[j].order.push(newData[i][idField]);
                        }
                        hasVal = true;
                        break;
                    }
                }
                if (!hasVal && newData[i].outtype == 2) {
                    let obj = {};
                    obj = JSON.parse(JSON.stringify(newData[i]));
                    obj.planqtySum = 0;
                    obj.qtySum = 0;
                    obj.planqtySum += newData[i].planqty;
                    obj.qtySum += newData[i].qty;
                    obj.child = [newData[i]];
                    obj.order = [newData[i][idField]];
                    this.dataStorage.package.push(obj);
                }
            }
            console.timeEnd("统计包件处理时间==》");
            console.log("动态生成包件明细：==>", this.dataStorage.package);
        },
        // _fnPackageBoard(newData, idField) {
        //     console.time("统计包件处理时间==》");
        //     this._getMatchID();
        //     for (let i = 0; i < newData.length; i++) {
        //         newData[i].matchId = "";
        //     }
        //     for (let i = 0; i < newData.length; i++) {
        //         let hasVal = false;
        //         // console.log("newData[i]=>", JSON.stringify(newData[i]));

        //         for (let j = 0; j < this.dataStorage.package.length; j++) {
        //             if (this._fnMatch(this.dataStorage.package[j], newData[i])) {
        //                 if (newData[i].outtype == 2) {
        //                     this.dataStorage.package[j].planqtySum += newData[i].planqty;
        //                     this.dataStorage.package[j].qtySum += newData[i].qty;
        //                 }
        //                 this.dataStorage.package[j].child.push(newData[i]);
        //                 if (this.dataStorage.package[j].order.indexOf(newData[i][idField]) == -1) {
        //                     this.dataStorage.package[j].order.push(newData[i][idField]);
        //                 }
        //                 hasVal = true;
        //                 break;
        //             }
        //         }
        //         if (!hasVal && newData[i].outtype == 2) {
        //             let obj = {};
        //             obj = JSON.parse(JSON.stringify(newData[i]));
        //             obj.planqtySum = 0;
        //             obj.qtySum = 0;
        //             obj.planqtySum += newData[i].planqty;
        //             obj.qtySum += newData[i].qty;
        //             obj.child = [newData[i]];
        //             obj.order = [newData[i][idField]];
        //             this.dataStorage.package.push(obj);
        //         }
        //     }
        //     console.timeEnd("统计包件处理时间==》");
        //     console.log("动态生成包件明细：==>", this.dataStorage.package);
        // },
        /**计算包件汇总 */
        _fnCountPackage(type, data) {
            for (let i = 0; i < this.dataStorage.package.length; i++) {
                if (this.dataStorage.package[i].matchId == data.matchId) {
                // if (this._fnMatch(this.dataStorage.package[i], data)) {
                    if (type == "add") {
                        // /**出仓类型-包件按条码 */
                        // if (data.outtype == 2) {
                            this.dataStorage.package[i].qtySum += data.packqty * data.qty;
                        // }
                    } else {
                        // /**出仓类型-包件按条码 */
                        // if (data.outtype == 2) {
                            this.dataStorage.package[i].qtySum -= data.packqty * data.qty;
                        // }
                    }
                    break;
                }
            }
        },
        /**获取系统设置，并返回 */
        _fnGetOption(callback){
            let option = {
                mtrlsectypeVal: $lj.getOptionValue(41), // 自定义
                zxmtrlmodeVal: $lj.getOptionValue(42), // 自定义1
                usermtrlmodeVal: $lj.getOptionValue(128), // 自定义2
                statusVal: $lj.getOptionValue(29), // 配置
                woodcodeVal: $lj.getOptionValue(27), // 配置1
                pcodeVal: $lj.getOptionValue(28),// 配置2
            }
            callback(option)
        },
        /**聚焦自动全选文本 */
        handleFooterInputFocus(ev) {
            this.inputCurrentTarget = ev.currentTarget;
            ev.currentTarget.select();
        },
        /**深度重置 */
        _fnDeepReset() {
            this.dataStorage.order = [];
            this.dataStorage.package = [];
            this.dataStorage.barcode = [];
            this.original.orderlist = [];
            this.original.orderMxList = [];
            this.original.barcodeList = [];
            // 重置定位信息
            this.fnResetLocation();
            this.showScanStart = false;
        },
        /**清空统计信息-重置信息 */
        fnResetMsg(idField) {
            for (let i = 0; i < this.dataStorage.order.length; i++) {
                this.dataStorage.order[i].qtySum = 0;
                this.dataStorage.order[i].barcode = [];
                this.dataStorage.order[i].children = [];

                for (let j = 0; j < this.original.orderMxList.length; j++) {
                    if (this.original.orderMxList[j][idField] == this.dataStorage.order[i][idField]) {
                        let outwareMx = JSON.parse(JSON.stringify(this.original.orderMxList[j]));
                        this.dataStorage.order[i].children.push(outwareMx);
                    }
                }
            }
            for (let i = 0; i < this.dataStorage.package.length; i++) {
                this.dataStorage.package[i].qtySum = 0;
            }
        },
        /**定位功能：关闭定位滚动功能-重置信息 */
        fnResetLocation() {
            this.locationState.index = -1;
            this.locationState.value = "";
            this.locationList = [];
            this.showLocation = false;
            this.barcodeInput = "";
        },
        /**定位功能：搜索定位匹配内容 */
        _autoSearchBarcode(val) {
            if (!this.dataStorage.barcode.length) {
                $lj.toast("提示：请先添加条码", 1000, "bottom");
                return false;
            }
            // 清除状态
            this.locationState.index = -1;
            this.locationState.value = "";
            this.locationList = [];
            for (let i = 0; i < this.dataStorage.barcode.length; i++) {
                if (this.dataStorage.barcode[i].barcode.indexOf(val) > -1 || this.dataStorage.barcode[i].mtrlname.indexOf(val) > -1) {
                    this.locationList.push(this.dataStorage.barcode[i].barcode);
                }
            }
            if (this.locationList.length) {
                /**匹配成功 */
                this.handleLocationBarcode(1);
                
                $lj.toast("提示：定位成功");
                this._autoInputBlur();
            } else {
                /**匹配失败 */
                $lj.toast("提示：暂无匹配数据");
                this.inputCurrentTarget && this.inputCurrentTarget.select();
            }
            console.log("this.locationList===>", this.locationList);
        },
        /**定位功能：上一个、下一个 */
        handleLocationBarcode(action) {
            if (!this.locationList.length) {
                $lj.toast("提示：暂无匹配数据");
                return false;
            }

            if (action == -1) {
                this.locationState.index--;
                if (this.locationState.index <= -1) {
                    this.locationState.index = this.locationList.length - 1;
                }
            } else if (action == 1) {
                this.locationState.index++;
                if (this.locationState.index == this.locationList.length ) {
                    this.locationState.index = 0;
                }
            }
            console.log("this.locationState.index==>", this.locationState.index);
            this.locationState.value = this.locationList[this.locationState.index];
            this.$refs.barcodeWidget.scrollOffset(this.locationState.value, this.headerHeight);
        },
        /**底部按钮：删除已选订单*/
        fnDelSelOrder(idField, codeField) {
            console.log("删除前订单列表：==>", this.dataStorage.order);
            if (!this.checkboxToDel.length) return;
            let toDelOrder = [];
            // 选单阶段，删除指定订单
            for (let i = 0; i < this.checkboxToDel.length; i++) {
                let target = this.checkboxToDel[i].trim();
                // 删除已选订单
                for (let j = this.dataStorage.order.length - 1; j >= 0; j--) {
                    if (target == this.dataStorage.order[j][codeField].trim()) {
                        toDelOrder.push(this.dataStorage.order[j][idField]);
                        this.dataStorage.order.splice(j, 1);
                        break;
                    }
                }
            }
                
            if (toDelOrder.length) {
                console.log("要删除的订单数组：==>", toDelOrder);
                // 查找包件展示列表
                for (let j = this.dataStorage.package.length - 1; j >= 0; j--) {
                    let orderlist = this.dataStorage.package[j].order
                    let hasorder = toDelOrder.filter(function(item) {
                        return orderlist.indexOf(item) > -1;
                    });
                    console.log("是否有订单！！=》", hasorder);
                    console.log("是否有订单this.dataStorage.package=》", this.dataStorage.package);
                    // let index = this.dataStorage.package[j].order.indexOf(target);
                    if (hasorder.length) {
                        // 删除包件列表中，包件列表中对应订单号的包件
                        for (let k = this.dataStorage.package[j].child.length - 1; k >= 0; k--) {
                            if (toDelOrder.indexOf(this.dataStorage.package[j].child[k][idField]) > -1) {
                                this.dataStorage.package[j].qtySum -= this.dataStorage.package[j].child[k].qty;
                                this.dataStorage.package[j].planqtySum -= this.dataStorage.package[j].child[k].planqty;
                                this.dataStorage.package[j].child.splice(k, 1);
                            }
                        }
                        // 删除包件列表中，订单号列表
                        this.dataStorage.package[j].order = this.dataStorage.package[j].order.filter(function(item) {
                            return toDelOrder.indexOf(item) == -1;
                        });
                    }
                    if (!this.dataStorage.package[j].child.length) {
                        this.dataStorage.package.splice(j, 1);
                    }
                }

                // 删除已下载包件明细
                for (let k = this.original.orderMxList.length - 1; k >= 0; k--) {
                    if (toDelOrder.indexOf(this.original.orderMxList[k][idField]) > -1) {
                        this.original.orderMxList.splice(k, 1);
                    }
                }
            }
            $lj.toast("提示：删除成功");
        },
        /**底部按钮：扫描组件反馈——删除已扫描条码 */
        autoComfirmDelBarcode(delArr) {
            console.log("delArr===>", JSON.stringify(delArr));
            if (!delArr.length) {
                $lj.toast("提示：删除参数传递错误");
                return false;
            }

            let self = this;
            let tips = delArr.length > 1 ? 
                "是否确定删除已选(" + delArr.length+ ")条码" :
                "是否删除条码:[" + delArr[0] + "]";
            $lj.WarnSound();
            $lj.confirm("提示", tips, function () {
                let success = self._fnDelBarcode(delArr);
                if (success) {
                    $lj.OkSound();
                    $lj.toast("提示：删除成功", 1000, "top");
                    self.$refs.barcodeWidget.fnClearAllList();
                    for (let i = 0; i < self.dataStorage.barcode.length; i++) {
                        self.dataStorage.barcode[i].ifcheckbox = false;
                    }
                }
            })
        },
        /**方法：删除多条条码，并更新订单、包件信息 */
        _fnDelBarcode(delArr) {
            let hasSuccess = false;
            for (let i = 0; i < delArr.length; i++) {
                for (let j = 0; j < this.dataStorage.barcode.length; j++) {
                    if (delArr[i] == this.dataStorage.barcode[j].barcode) {
                        // 删除包件汇总数据
                        this._fnCountPackage("del", this.dataStorage.barcode[j]);
                        // 删除订单汇总数据
                        this._fnDelOrderBarcode(this.dataStorage.barcode[j]);
                        // 删除记忆保存条码数据
                        let index = this.hasSaveBarcodeList.indexOf(this.dataStorage.barcode[j].barcode);
                        if (index > -1) {
                            this.hasSaveBarcodeList.splice(index, 1);
                        }
                        // this._fnDelOrderBarcode(this.dataStorage.barcode[j]);
                        this.dataStorage.barcode.splice(j, 1);
                        hasSuccess = true;
                        break;
                    }
                }
                // 清除定位列表中的所匹配到的值
                for (let j = 0; j < this.locationList.length; j++) {
                    if (delArr[i] == this.locationList[j]) {
                        this.locationList.splice(j, 1)
                        break;
                    }
                }
            }
            return hasSuccess;
        },
        /**底部输入框：扫描输入框-输入监听回调 */
        handleFooterInput() {
            let barcode = this.barcodeInput.trim();
            if (barcode == "") return false;
            this.barcodeInput = "";
            if (this.showLocation) {
                /**定位功能 */
                this._autoSearchBarcode(barcode);
            }  else if (this.showScanStart && this.ifBigBar) {
                /**条码打包单辅助检查*/
                this._fnCheckIfBigBarCode(barcode);
            } else if (this.showScanStart) {
                /**开始扫描 */
                if (!this._addBarcode(barcode)) return;
                // $lj.toast("提示：添加成功", 1000, "bottom");
                this.$toast({
                    message: `提示：[${barcode}]添加成功`,
                    duration: 1000,
                    position: 'top'
                });
                // $lj.OkSound();
            }
        },
        /**系统选项310：pda销售发货加锁——重置解锁 */
        _fnUnlockOurware() {
            if ($lj.getOptionValue(310) == 1) {
                let outwareList = [];
                for (let i = 0; i < this.dataStorage.order.length; i++) {
                    let obj = {};
                    obj.scid = this.dataStorage.order[i].scid;
                    obj.outwareid = this.dataStorage.order[i].outwareid;
                    outwareList.push(obj);
                }
                let requestBody = {
                    token: $lj.getStorage("token"),
                    outwareList: outwareList,
                };
                $lj.postLJRequest('PDA_Unlock_Outware', requestBody, function (ret) {
                    if (ret) {
                        $lj.toast(ret.msg, 1000, "top");
                    }
                });
            }
        },
        /**计算是否含有某条码 */
        _fnCheckIndex(aList, value, target) {
            if (!aList.length) return -1;
            if (target == "" || target == null || target == undefined) return -1; 

            let hasValue = -1;
            for (let i = 0; i < aList.length; i++) {
                if (target.toString().trim().toUpperCase() == aList[i][value].toString().trim().toUpperCase()) {
                    hasValue = i;
                    break;
                }
            }
            return hasValue;
        },
        /**计算集合否包含条码集合 */
        _fnCheckInclude(aList, value, targetArr) {
            if (!aList.length) return -1;
            if (!targetArr.length) return -1;
            let valueArr = [];
            let targetArrLength = targetArr.length;
            for (let i = 0; i < targetArrLength; i++) {
                valueArr.push(targetArr[i][value].trim());
            }

            let hasValue = [];
            for (let i = 0; i < aList.length; i++) {
                if (valueArr.indexOf(aList[i][value].trim()) > -1) {
                    hasValue.push(aList[i][value].trim());

                    if (hasValue.length == targetArrLength) {
                        break;
                    }
                }
            }
            return hasValue;
        },
        /**自动失去焦点 */
        _autoInputBlur() {
            let self = this;
            setTimeout(function() {
                self.$refs.barcodeInput.blur();
            }, 20);
        },
        // _getFailReason(barcode) {
        //     let self = this;
        //     let requestBody = {
        //         token: $lj.getStorage("token"),
        //         barcode: barcode,
        //         billtype: 1,
        //         aNum: 0
        //     };
        //     $lj.postLJRequest('PDA_GetCantOutReason', requestBody, function (ret) {
        //         console.log("保存接口反馈==》", ret);
        //         if (ret) {
        //             api.alert({
        //                 title: "提示：[" +barcode+ "]",
        //                 msg: ret.errorMsg
        //             });
        //             // $lj.toast(ret.errorMsg, 2000, "middle");
        //             $lj.WarnSound();
        //         }
        //     });
        // },
        /**自定义加载状态--监测三个接口是否加载完成 */
        loadingTips(state, messgae) {
            let msg = messgae == undefined ? "加载中\n请稍后..." : messgae;
            if (state) {
                this.$toast.loading({
                    position: "middle",
                    message: msg,
                    forbidClick: true,
                    duration: 0
                });
            } else {
                this.$toast.clear(false);
            }
        },
        _fnCheckIfBigBarCode(barcode){
            let self = this;
            let requestBody = {
                token: $lj.getStorage("token"),
                barcode: barcode,
				type: 0
            }
            $lj.postLJRequest('PDA_GetInWareBigBar', requestBody, function (ret) {
                if (ret) {
                    if (ret.Errmsg) {
                        $lj.toast(`提示：${ret.Errmsg}`, 2000, "middle");
                        $lj.WarnSound();
                        self.inputCurrentTarget && self.inputCurrentTarget.select();
                        return false;

                    }
                    let barcodeList =  ret.barcodeList;
                    if (barcodeList && barcodeList.length > 0) {
                        barcodeList.forEach((item) => {
                            if (!self._addBarcode(item)) return;
                        })

                        self.$toast({
                            message: `提示：[${barcode}]添加成功`,
                            duration: 1000,
                            position: 'top'
                        });
                        // $lj.OkSound();
                    }else{
                        if (!self._addBarcode(barcode)) return;

                        self.$toast({
                            message: `提示：[${barcode}]添加成功`,
                            duration: 1000,
                            position: 'top'
                        });
                        // $lj.OkSound();
                    }
                }
            });
        },
    },
}

/**扫描开单模式；生产进仓-扫描开单 */
export const scanModelMixin = {
    data() {
        return {
            empid: "",
            barcodeInput: "",
            checkboxToDel: [], // 选单时记录勾选的订单，扫码时记录勾选的条码
            //状态
            storageVisible: false, //lj-picker
            actionsSheetVisible: false, //lj-picker
            showScanStart: false,
            openTitle: false, // 打开右上角菜单
            showLocation: false, // 打开定位功能
            locationList: [], // 定位列表
            locationState: { // 当前定位信息
                index: -1,
                value: ""
            },
            popupDetail: {}, // 展示的数据源
            barcodeProperty: {}, // 条码详情属性对照
            draftData: {}, // 草稿模式储存器
            scrollTop: false,
            headerHeight: 0,
            inputCurrentTarget: null,
            storageFatherList: [],
            storageChildList: [],
			ifBigBar:false, // 条码打包单检测条件
			bigBarStr: '', // 条码打包单抬头
            showOrderToDelect: false, // 是否开启管理功能
            bwHeight: null, // 虚拟滚动高度
            descing: false, //备注是否聚焦
            confirmLoading: false
        }
    },
    created() {
        this.empid = $lj.getStorage('user').empid;
    },
    computed: {
        footerScanPho() {
            return this.showScanStart ? "请扫描或输入条码编号" : "可扫描或输入仓库信息";
        }
    },
    provide() {
        return {
            updateScrollTop:(offset)=> {
                this.scrollTop = {
                allowScroll: true,
                offset,
                complete: ()=> {
                        this.scrollTop = false
                    }
                }
            }
        }
    },
    mounted() {
        let self = this;
        // 读取系统选项设置
        this.autoGetOptionValue();
        this.dataStorage.userid = $lj.getStorage("user").usercode;
        this.dataStorage.lastLoginAccount = $lj.getStorage("lastLoginAccount");
        console.log('$lj.getStorage("lastLoginAccount")', $lj.getStorage("lastLoginAccount"));
        this.draftData = $lj.getStorage(this.draftName) || {};
        // 读取权限内仓库信息
        this.getInwareInfo(function(power) {
            let storageInfo = $lj.getStorage("storageInfo");
            //self.bigBarStr = storageInfo.bigCodeStr.toString().toUpperCase().trim();
            if (storageInfo.storagePower == null || storageInfo.storagePower == "") {
                $lj.toast("该用户的仓库权限不存在 / 该用户不存在");
                return false;
            }
            if (storageInfo.storagePower == "-1") {
                $lj.toast("你没有仓库权限");
                return false;
            }
            // if (power && storageInfo.storagePower != "0") {
            //     for (let i = storageInfo.storageList.length - 1; i >= 0; i--) {
            //         if (storageInfo.storagePower.indexOf(storageInfo.storageList[i].storageid) == -1) {
            //             storageInfo.storageList.splice(i, 1);
            //         }
            //     }
            // }
            return storageInfo;
        }, function() {
            console.log("测试mixin调用getInwareInfo");
            // 读取草稿模式
            self._getDraftModeData(self.draftName);
        });

        // document.onkeydown = function(event){
            
        //     if (!self.storageVisible) {
        //         /**打开仓库选择器时,不控制焦点 */
        //         /**聚焦底部输入框 */
        //         if (self.$refs.barcodeInput) {
        //             self.$refs.barcodeInput.focus();
        //             // 关闭弹出窗体
        //             self.$refs.pdaDetail && self.$refs.pdaDetail.close();
        //         }
        //     }
        // };
        this.autoScanSetting();

        /**设置content高度，便于定位滚动 */
        let height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; //浏览器高度
        this.headerHeight = document.querySelector("header.header").clientHeight;
        this.$refs.inwareBody.style.marginTop = this.headerHeight + 'px';
        this.$refs.inwareBody.style.height = height - this.headerHeight - this.$refs.inwareFooter.clientHeight + 'px';

        /**监听安卓返回按键 */
        api.addEventListener({
            name: 'keyback'
        }, function(ret, err) {
            self.handleCloseBtn();
        });
    },
    methods: {
        autoScanSetting(scanCallback, focusCallback) {
            let self = this;
            if (api.deviceName.toUpperCase() == 'MOBYDATA') {
                $lj.registerDecodeReceiver();
                $lj.removeEventListener("longjoeAPI_mobyM71Decoded");
                $lj.addEventListener("longjoeAPI_mobyM71Decoded", (ret) => {
                    if (scanCallback) {
                        scanCallback(ret);
                    } else {
                        if (!self.storageVisible) {
                            if (!self.descing) {
                                self.barcodeInput = ret.value.barcodeString;
                                self.handleFooterInput();
                            }
                        }
                    }
                });
            } else {
                document.onkeydown = function(event){
                    if (focusCallback) {
                        focusCallback();
                    } else {
                        if (!self.storageVisible) {
                            /**打开仓库选择器时,不控制焦点 */
                            /**聚焦底部输入框 */
                            if (self.$refs.barcodeInput && !self.descing) {
                                self.$refs.barcodeInput.focus();
                                // 关闭弹出窗体
                                self.$refs.pdaDetail && self.$refs.pdaDetail.close();
                            }
                        }
                    }
                };
            }
        },
        /**有备注：失去聚焦 */
        handleHasRemarkBlur() {
            this.descing = false;
            setTimeout(() => {
                this.$refs.baseWin.initStyle();
            }, 200);
        },
        fixbody(obj){
            if (this.$refs.sacnTitle) {
                let titleTop = this.$refs.sacnTitle.offsetTop + this.$refs.sacnTitle.offsetHeight - parseInt(obj.marginTop);
                this.bwHeight = parseInt(obj.minHeight) - titleTop;
                console.log(' this.$refs.sacnTitle.offsetTop :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.$refs.sacnTitle.offsetTop));
                console.log(' this.$refs.sacnTitle.offsetHeight :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.$refs.sacnTitle.offsetHeight));
                console.log(' tabHeight :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.bwHeight));
            }
        },
        /**开启选择删除 */
        handleShowCheckBox() {
            this.showOrderToDelect = true;
            this.openTitle = false;
        },
        handleScanBtn() {
			let self = this;
            $lj.openScanner((ret) => {
                setTimeout(() => {
                    let content = ret.content.trim();
                    self.barcodeInput = content;
                    self.handleFooterInput();
                }, 200);
            })
        },
        /**生成包件明细匹配验证ID */
        _fnSetMatchID(newData) {
            console.time("添加Matchid-For==>");
            let arrMxList = JSON.parse(JSON.stringify(newData));
            for (let i = 0; i < arrMxList.length; i++) {
                
                let strMarch = this._getMatchID();
                let arrMatchid = strMarch.split(',');
                let strMatchid = "";
                for (let j = 0; j < arrMatchid.length; j++) {
                    strMatchid += arrMxList[i][arrMatchid[j]].toString() + "%";
                }
                arrMxList[i].matchId = strMatchid;
            }
            console.timeEnd("添加Matchid-For==>");
            return arrMxList;
        },
        /**扫描输入框-输入监听回调 */
        handleFooterInput() {
            console.log("输入监听==>", this.barcodeInput);
            let barcode = this.barcodeInput.trim();
            if (barcode == "") return false;
            this.barcodeInput = "";
            if (this.showLocation) {
                /**定位功能 */
                this._autoSearchBarcode(barcode);
            } else if (this.showScanStart && this.ifBigBar) {
                /**条码打包单辅助检查*/
                this._fnCheckIfBigBarCode(barcode);
            } else if (this.showScanStart) {
                /**开始扫描 */
                if (!this._addBarcode(barcode)) return;
                
                // $lj.toast("提示：添加成功", 1000, "bottom");
                // Toast(`提示：[${barcode}]添加成功`, 1000, "top");
                this.$toast({
                    message: `提示：[${barcode}]添加成功`,
                    duration: 1000,
                    position: 'top'
                });
                // $lj.OkSound();
            } else {
                /**填入基础仓库信息 */
                if (!this._autoGetStorage(barcode)) {
                    $lj.toast("识别失败", 1000, "bottom");
                    return;
                };
                this.$toast({
                    message: `识别成功，并设置`,
                    duration: 1000,
                    position: 'top'
                });
                $lj.OkSound();
                this._autoInputBlur();
            }
        },
        /**扫描匹配车间 关键信息：wrkGrpid,wrkgrpcode,wrkGrpName*/
        _fnMatchWrkgrp(keyWord, list) {
            let obj = null;
            let index = null;
            // 先检测车间列表
            for (let i = 0; i < list.length; i++) {
                if (keyWord == list[i].wrkGrpid || keyWord == list[i].wrkgrpcode || keyWord == list[i].wrkGrpName) {
                    obj = list[i];
                    index = i;
                    break;
                }
            }
            if (obj) {
                return {item: obj, index: index};
            } else {
                return false;
            }
        },
        /**扫描匹配仓库仓位 关键信息：storageid,storagename,locacode,lcode*/
        _fnMatchStorage(keyWord, list) {
            let obj = null;
            // 再检测仓库仓位列表
            for (let i = 0; i < list.length; i++) {
                if ((list[i].hasOwnProperty("lcode") && list[i].lcode) || (list[i].hasOwnProperty("locacode") && list[i].locacode)) {
                    if (keyWord == list[i].lcode || keyWord == list[i].locacode) {
                        obj = list[i];
                        break;
                    }
                } else if (keyWord == list[i].storageid || keyWord == list[i].storagename) {
                    obj = list[i];
                    break;
                }
            }
            return obj;
        },
        /**草稿模式：即时下载，读取草稿条码 */
        _fnGetDraftBarcode_ScanNow(ret) {
            if (ret.errorMsg) {
                $lj.toast("部分草稿条码\n不在有效扫描范围，\n恢复失败", 2500, "middle");
                $lj.WarnSound();
            } else if (ret.barcodeList && ret.barcodeList.length > 0) {
                this.original.barcodeList = this.original.barcodeList.concat(ret.barcodeList);
                for (let i = 0; i < ret.barcodeList.length; i++) {
                    this.$set(ret.barcodeList[i], 'ifcheckbox', false);
                    this.dataStorage.barcode.push(JSON.parse(JSON.stringify(ret.barcodeList[i])));
                }
                // this.dataStorage.barcode = this.dataStorage.barcode.concat(ret.barcodeList);
        
                $lj.toast("草稿条码恢复成功", 1000, "top");
                $lj.OkSound();
            }
        },
        /**草稿模式：先下载，读取草稿条码 */
        _fnGetDraftBarcode() {
            // 验证，检查草稿条码是否在有效扫描范围内
            let isAllPass = true;
            for (let i = 0; i < this.draftData.barcode.length; i++) {
                let hasIndex = this._fnCheckIndex(this.original.barcodeList, "barcode", this.draftData.barcode[i].barcode);
                if (hasIndex == -1) {
                    $lj.toast("部分草稿条码\n不在有效扫描范围，\n恢复失败", 2500, "middle");
                    $lj.WarnSound();
                    isAllPass = false;
                    break;
                } else {
                    this.$set(this.draftData.barcode[i], 'ifcheckbox', false);
                }
            }
            if (isAllPass) {
                // 添加条码
                this.dataStorage.barcode = this.dataStorage.barcode.concat(this.draftData.barcode);
                $lj.toast("草稿条码恢复成功", 1000, "top");
                $lj.OkSound();
            }
        },
        /**监听子组件-回调多选列表 */
        _autoGetMultiple(data) {
            this.checkboxToDel = data;
            this.showOrderToDelect = Boolean(data.length);
        },
        /**底部左侧按钮——“返回”与“重置” */
        handleCancel() {
            if (!this.showScanStart) {
                // 退出页面
                // $lj.setStorage(self.draftName, null);
                $lj.closeWin();
            } else {
                // 重置
                let self = this;
                $lj.WarnSound();
                $lj.selectDialog("确定要重置吗？", "提示：已扫描的数据将会丢失", ["取消", "确定"], function(btnIndex) {
                    if (btnIndex == 2) {
                        self._fnResetMsg();
                    }
                })
            }
        },
        /**左上角返回按钮 */
        handleCloseBtn() {
            if (!this.showScanStart) {
                // 退出页面
                // $lj.setStorage(this.draftName, null);
                let data = JSON.parse(JSON.stringify(this.dataStorage));
                
                console.log("handleCloseBtn退出====》 ", JSON.stringify(data));
                if (this.draftData && JSON.stringify(this.draftData) != "{}") {
                    if (JSON.stringify(this.draftData.barcode) == '[]') {
                        console.log("没有条码信息");
                        $lj.setStorage(this.draftName, data);
                    }
                } else {
                    console.log("没有缓存信息");
                    $lj.setStorage(this.draftName, data);
                }
                $lj.closeWin();
            } else {
                let self = this;
                // if (this.dataStorage.barcode.length > 0) {
                $lj.WarnSound();
                $lj.selectDialog("退出，并保留新增数据吗？", "提示：已扫描的数据可保留至草稿(点击空白可取消退出)", ["保留", "不保留"], function(btnIndex) {
                    console.log("btnIndex==>", btnIndex);
                    if (btnIndex == 1) {
                        console.log("保留");
                        /**储存数据 */
                        $lj.setStorage(self.draftName, self.dataStorage);
                        $lj.closeWin();
                    } else if (btnIndex == 2) {
                        console.log("不保留");
                        let data = JSON.parse(JSON.stringify(self.dataStorage));
                        data.barcode = [];
                        $lj.setStorage(self.draftName, data);
                        $lj.closeWin();
                    }
                })
                // } else {
                //     let data = JSON.parse(JSON.stringify(this.dataStorage));
                //     $lj.setStorage(this.draftName, data);
                //     $lj.closeWin();
                // }
            }
        },
        /**扫描组件反馈——删除已扫描条码 */
        handleDelBarcode(delArr) {
            console.log("delArr===>", JSON.stringify(delArr));
            if (!delArr.length) {
                $lj.toast("提示：删除参数传递错误");
                return false;
            }

            let self = this;
            let tips = "是否确定删除已选条码";
            if (delArr.length == 1) {
                tips = "是否删除:" + delArr[0];
            }
            $lj.WarnSound();
            $lj.confirm("提示", tips, function () {
                let success = false;
                for (let i = 0; i < delArr.length; i++) {
                    for (let j = 0; j < self.dataStorage.barcode.length; j++) {
                        if (delArr[i] == self.dataStorage.barcode[j].barcode) {
                            self.dataStorage.barcode.splice(j, 1);
                            success = true;
                            break;
                        }
                    }
                    // 清除定位列表中的所匹配到的值
                    for (let j = 0; j < self.locationList.length; j++) {
                        if (delArr[i] == self.locationList[j]) {
                            self.locationList.splice(j, 1)
                            break;
                        }
                    }
                }
                if (success) {
                    $lj.OkSound();
                    $lj.toast("提示：删除成功", 1000, "bottom");
                    self.$refs.barcodeWidget.fnClearAllList();
                    for (let i = 0; i < self.dataStorage.barcode.length; i++) {
                        self.dataStorage.barcode[i].ifcheckbox = false;
                    }
                }
            })
        },
        /**聚焦自动全选文本 */
        handleFooterInputFocus(ev) {
            this.inputCurrentTarget = ev.currentTarget;
            ev.currentTarget.select();
        },
        handleClearMultiple() {
            this.$refs.barcodeWidget.fnClearAllList();
            for (let i = 0; i < this.dataStorage.barcode.length; i++) {
                this.dataStorage.barcode[i].ifcheckbox = false;
            }
        },
        /**定位功能：上一个、下一个 */
        handleLocationBarcode(action) {
            if (!this.locationList.length) {
                $lj.toast("提示：暂无匹配数据");
                return false;
            }

            if (action == -1) {
                this.locationState.index--;
                if (this.locationState.index <= -1) {
                    this.locationState.index = this.locationList.length - 1;
                }
            } else if (action == 1) {
                this.locationState.index++;
                if (this.locationState.index == this.locationList.length ) {
                    this.locationState.index = 0;
                }
            }
            console.log("this.locationState.index==>", this.locationState.index);
            this.locationState.value = this.locationList[this.locationState.index];
            
            this.$refs.barcodeWidget.scrollOffset(this.locationState.value, this.headerHeight);
            // document.getElementById(this.locationState.value).scrollIntoView({
            //     block: 'start',
            //     behavior: 'smooth'
            // })
        },
        /**搜索定位匹配内容 */
        _autoSearchBarcode(val) {
            if (!this.dataStorage.barcode.length) {
                $lj.toast("提示：请先添加条码", 1000, "bottom");
                return false;
            }
            // 清除状态
            this.locationState.index = -1;
            this.locationState.value = "";
            this.locationList = [];
            for (let i = 0; i < this.dataStorage.barcode.length; i++) {
                if (this.dataStorage.barcode[i].barcode.indexOf(val) > -1 || this.dataStorage.barcode[i].mtrlname.indexOf(val) > -1) {
                    this.locationList.push(this.dataStorage.barcode[i].barcode);
                }
            }
            if (this.locationList.length) {
                /**匹配成功 */
                // this.locationState.index = 0;
                // this.locationState.value = this.locationList[this.locationState.index];
                this.handleLocationBarcode(1);
                
                $lj.toast("提示：定位成功");
                this._autoInputBlur();
            } else {
                /**匹配失败 */
                $lj.toast("提示：暂无匹配数据");
            }
            console.log("this.locationList===>", this.locationList);
        },
        /**右上角菜单——打开定位 */
        handleShowLocation() {
            $lj.toast("功能维护中", 2000, "middle");
            // if (this.showScanStart) {
            //     this.openTitle = false;
            //     this.showLocation = true;
            // }
        },
        /**关闭定位滚动功能-重置信息 */
        fnResetLocation() {
            this.locationState.index = -1;
            this.locationState.value = "";
            this.locationList = [];
            this.showLocation = false;
            this.barcodeInput = "";
        },
        /**打开类型或退货原因选择列表 */
        handleSelActionType(type) {
            this.actionsSheetType = type;
            switch (this.actionsSheetType) {
                case 'type':
                    this.actionsSheetData = this.inWareTypeAction;
                    break;
                case 'inware_reason':
                    if (!this.reasonAction.length) {
                        $lj.toast("提示：请先设置进仓原因", 2000, "middle");
                        return false;
                    }
                    this.actionsSheetData = this.reasonAction;
                    break;
                case 'inware_plan':
                    this.actionsSheetData = this.planTypeAction;
                    break;
                case 'outwareother_reason':
                    if (!this.reasonAction.length) {
                        $lj.toast("提示：请先设置出仓原因", 2000, "middle");
                        return false;
                    }
                    this.actionsSheetData = this.reasonAction;
                    break;
            }
            this.actionsSheetVisible = true;
        },
        /**设置进仓类型-选择事件 */
        handleSelActionsSheet(item) {
            switch (this.actionsSheetType) {
                case "type":
                    this.dataStorage.intype = item.id;
                    break;
                case "inware_reason":
                    this.dataStorage.reason = item.name;
                    break;
                case 'inware_plan':
                    this.dataStorage.plantype = item.id;
                    break;
                case "outwareother_reason":
                    this.dataStorage.reason = item.name;
                    break;
            }
        },
        /**读取草稿模式 */
        _getDraftModeData(storageName) {
            let darft = $lj.getStorage(storageName);
            if (darft != undefined && darft != null) {
                // this.draftData = darft;

                this._autoGetDraftBarcode();
            }
        },
        /**获取系统设置，并返回 */
        _fnGetOption(callback){
            let option = {
                mtrlsectypeVal: $lj.getOptionValue(41), // 自定义
                zxmtrlmodeVal: $lj.getOptionValue(42), // 自定义1
                usermtrlmodeVal: $lj.getOptionValue(128), // 自定义2
                statusVal: $lj.getOptionValue(29), // 配置
                woodcodeVal: $lj.getOptionValue(27), // 配置1
                pcodeVal: $lj.getOptionValue(28),// 配置2
            }
            callback(option)
        },
        /**计算是否含有某条码 */
        _fnCheckIndex(aList, value, target) {
            if (!aList.length) return -1;
            if (target == "" || target == null || target == undefined) return -1; 

            let hasValue = -1;
            for (let i = 0; i < aList.length; i++) {
                if (target.toString().trim() == aList[i][value].toString().trim()) {
                    hasValue = i;
                    break;
                }
            }
            return hasValue;
        },
        /**普通重置信息 */
        _fnResetMsg() {
            // 清楚缓存内的条码
            this.original.barcodeList = [];
            this.dataStorage.barcode = [];
            // 重置定位信息
            this.fnResetLocation();
            this.showScanStart = false;
        },
        /**组件：lj-storage=>关闭监听-关闭弹窗订单选择模块 */
        autoCloseLjStorage() {
            setTimeout(() => {
                this.storageVisible = false;
            }, 200);
        },
        /**自动失去焦点 */
        _autoInputBlur() {
            let self = this;
            setTimeout(function() {
                self.$refs.barcodeInput.blur();
            }, 20);
        },
        /**自定义加载状态--监测三个接口是否加载完成 */
        loadingTips(state, messgae) {
            let msg = messgae == undefined ? "加载中\n请稍后..." : messgae;
            if (state) {
                this.$toast.loading({
                    position: "middle",
                    message: msg,
                    forbidClick: true,
                    duration: 0
                });
            } else {
                this.$toast.clear(false);
            }
        },
        _fnCheckIfBigBarCode(barcode){
            let self = this;
            let requestBody = {
                token: $lj.getStorage("token"),
                barcode: barcode,
                type: 1
            }
            $lj.postLJRequest('PDA_GetInWareBigBar', requestBody, function (ret) {
                if (ret) {
                    if (ret.Errmsg) {
                        $lj.toast(`提示：${ret.Errmsg}`, 2000, "middle");
                        $lj.WarnSound();
                        self.inputCurrentTarget && self.inputCurrentTarget.select();
                        return false;
                    }
                    self.confirmLoading = true;
                    if(ret.retbarcodeList && ret.retbarcodeList.length > 0) {
                        self.original.barcodeList = self.original.barcodeList.concat(ret.retbarcodeList);
                    }
                    let barcodeList = ret.barcodeList;
                    if (barcodeList && barcodeList.length > 0) {
                        barcodeList.forEach((item) => {
                            if (!self._addBarcode(item)) {
                                self.confirmLoading = false;
                                return;
                            }
                        })
        
                        self.$toast({
                            message: `提示：[${barcode}]添加成功`,
                            duration: 1000,
                            position: 'top'
                        });
                        // $lj.OkSound();
                    } else {
                        if (!self._addBarcode(barcode)) {
                            self.confirmLoading = false;
                            return;
                        }
        
                        self.$toast({
                            message: `提示：[${barcode}]添加成功`,
                            duration: 1000,
                            position: 'top'
                        });
                        // $lj.OkSound();
                    }
                    self.confirmLoading = false;
                }
            });
        },
    }
}