/**
 * OEM单总编号多仓位送货单
 */
import extend from '../utils/extend.js';
import analyze from '../utils/analyzeScannedContent.js';
import user from '../utils/user.js';
import request from '../utils/request.js';
import token from '../utils/token.js';
import shipPlanEnum from '../utils/shipPlanEnum.js';
import message from '../utils/message.js';

/**
 * 订单存储键
 */
const orderStorageKey = 'multiCustomizeDeliveryOrder';

/**
 * 仓位存储键
 */
const kwcwKey = 'CM_D_KWCW';

/**
 * 是否错误
 */
let isError = false;

/**
 * OEM单总编号多仓位送货单
 */
export default class {
    /**
     * 订单
     */
    order = null;

    /**
     * 用户信息
     */
    user = null;

    /**
     * 仓位
     */
    kwcw = {
        /**
         * 当前仓位内码
         */
        CWID: null,

        /**
         * 当前仓位编码
         */
        CWBM: null,

        /**
         * 当前仓位名称
         */
        CWMC: null,

        /**
         * 仓位状态;CM_C_MB,LX='KWCWZT';=0 空闲，=1 占用
         */
        ZTID: 0,

        /**
         * 仓位列表
         */
        list: [],

        moveAction: false,

        isMove: false
    };

    constructor(order) {
        this.order = order || null;
        this.user = user.get() || {};
        this.init();
    }

    /**
     * 初始化
     */
    init(order) {
        this.order = order;

        if (extend.isNull(order)) {
            extend.removeStorage(orderStorageKey);
            extend.removeStorage(kwcwKey)
            return;
        }
    }

    /**
     * 订单编码
     */
    get orderNumber() {
        let res = ';'
        if (extend.isObject(this.order)) {
            res = this.order.OrderNumber;
        } else {
            res = this.getNewOrderNumber();
        }
        return res;
    }

    /**
     * 获取总数量
     * @returns {number}
     */
    get quantity() {
        let res = 0;
        let lines = this.lines;
        for (let i in lines) {
            if (extend.isArray(lines[i].Codes)) {
                res += lines[i].Codes.length;
            }
        }
        return res;
    }

    /**
     * 获取已扫总数量
     * @returns {number}
     */
    get scanedQty() {
        let res = 0;
        let lines = this.lines;
        for (let i in lines) {
            if (!extend.isNumber(lines[i].ScanedQty)) {
                lines[i].ScanedQty = 0;
            }
            res += lines[i].ScanedQty;
        }
        return res;
    }

    /**
     * 剩余未扫码数量
     */
    get remainQty() {
        let res = 0;
        res = this.quantity - this.scanedQty;
        return res;
    }

    /**
     * 所有行
     */
    get lines() {
        let lines = [];
        if (!extend.isObject(this.order) || !extend.isArray(this.order.Lines)) {
            return lines;
        }
        lines = this.order.Lines;
        for (let i in lines) {
            if (!extend.isArray(lines[i].Codes)) {
                continue;
            }
            lines[i].ScanedQty = 0;
            for (let j in lines[i].Codes) {
                if (lines[i].Codes[j].WarehouseConfirmed) {
                    lines[i].ScanedQty++;
                }
            }
        }
        return lines;
    }

    /**
     * 所有二维码
     */
    get codes() {
        let list = [];
        let lines = this.lines;
        for (let i in lines) {
            if (!extend.isArray(lines[i].Codes)) {
                continue;
            }
            list = list.concat(lines[i].Codes);
        }
        return list;
    }

    /**
     * 仓位列表
     */
    get kwcwList() {
        if (!extend.isArray(this.kwcw.list)) {
            this.kwcw.list = [];
        }
        let codes = this.codes;
        for (let i in this.kwcw.list) {
            this.kwcw.list[i].Quantity = 0;
            for (let j in codes) {
                if (this.kwcw.list[i].CWID === codes[j].CWID) {
                    this.kwcw.list[i].Quantity++;
                }
            }
        }
        return this.kwcw.list;
    }

    /**
     * 仓位列表
     */
    get barcodes() {
        let list = [];
        let codes = this.codes;
        for (let i in codes) {
            list.push(codes[i].Barcode);
        }
        return list;
    }

    /**
     * 获取行
     * @param {number} customCompletionOrderLineId 送货单行内码
     */
    getLine(customCompletionOrderLineId) {
        let line = null;
        if (!extend.isObject(this.order) || !extend.isArray(this.order.Lines)) {
            return line;
        }
        for (let i in this.order.Lines) {
            this.order.Lines[i].Quantity = 0;
            this.order.Lines[i].ScanedQty = 0;
            if (!extend.isArray(this.order.Lines[i].Codes)) {
                continue;
            }
            this.order.Lines[i].Quantity = this.order.Lines[i].Codes.length;
            if (this.order.Lines[i].CustomCompletionOrderLineId === customCompletionOrderLineId) {
                line = this.order.Lines[i];
                for (let j in line.Codes) {
                    if (line.Codes[j].WarehouseConfirmed) {
                        line.ScanedQty++;
                    }
                }
                break;
            }
        }
        return line;
    }

    /**
     * 获取行中的二维码列表
     * @param {number} cwid 库位内码
     * @param {number} customCompletionOrderLineId 送货单行内码
     */
    getLineCodes(cwid, customCompletionOrderLineId) {
        let codes = [];
        if (!extend.isNumber(cwid) || !extend.isNumber(customCompletionOrderLineId)) {
            return codes;
        }
        let line = this.getLine(customCompletionOrderLineId);
        if (!extend.isObject(line) || !extend.isArray(line.Codes)) {
            return codes;
        }
        for (let i in line.Codes) {
            if (!(line.Codes[i].WarehouseConfirmed && line.Codes[i].CWID === cwid)) {
                continue;
            }
            codes.push(line.Codes[i]);
        }
        return codes;
    }

    /**
     * 获取行中已解析的二维码列表
     * @param {number} cwid 库位内码
     * @param {number} customCompletionOrderLineId 送货单行内码
     */
    getLineParseBarcodes(cwid, customCompletionOrderLineId) {
        let codes = [];
        if (!extend.isNumber(cwid) || !extend.isNumber(customCompletionOrderLineId)) {
            return codes;
        }
        let line = this.getLine(customCompletionOrderLineId);
        if (!extend.isObject(line) || !extend.isArray(line.Codes)) {
            return codes;
        }
        for (let i in line.Codes) {
            if (!(line.Codes[i].WarehouseConfirmed && line.Codes[i].CWID === cwid)) {
                continue;
            }
            let code = analyze.parse(line.Codes[i].Barcode);
            if (extend.isObject(code)) {
                codes.push(code);
            }
        }
        return codes;
    }

    /**
     * 获取新订单号
     */
    getNewOrderNumber() {
        return 'OSHD' + extend.dateFormatter(new Date(), 'yyMMdd');
    }

    /**
     * 获取新订单号
     */
    getKwcw(cwid) {
        let res = null;
        for (let i in this.kwcw.list) {
            if (this.kwcw.list[i].CWID === cwid) {
                res = this.kwcw.list[i];
                break;
            }
        }
        return res;
    }

    /**
     * 更新二维码仓位内码
     * @param {Array} list 要更改的二维码列表
     */
    updateCodesCwid(list) {
        this.kwcw.moveAction = false;
        this.kwcw.isMove = false;
        if (!extend.isArray(list) || extend.isNull(this.order)) {
            return;
        }
        let codes = this.codes;
        for (let i in list) {
            for (let j in codes) {
                if (list[i].Barcode === codes[j].Barcode) {
                    codes[j].CWID = this.kwcw.CWID;
                    codes[j].CWBM = this.kwcw.CWBM;
                    codes[j].CWMC = this.kwcw.CWMC;
                    codes[j].CodeStatus = shipPlanEnum.CodeStatus.Edit;
                    continue;
                }
            }
        }
        this.localSaveKwcw();
        this.localSaveOrder();
    }

    /**
     * 本地存储订单
     */
    localSaveOrder() {
        extend.addStorage(orderStorageKey, this.order);
    }

    /**
     * 本地读取订单
     */
    localReadOrder() {
        let order = extend.readStorage(orderStorageKey);
        if (extend.isObject(order)) {
            this.init(order);
        }
    }

    /**
     * 本地存储仓位
     */
    localSaveKwcw() {
        if (!extend.isNumber(this.kwcw.ZTID)) {
            this.kwcw.ZTID = 0;
        }
        if (!extend.isArray(this.kwcw.list)) {
            this.kwcw.list = [];
        }
        if (!extend.isBool(this.kwcw.moveAction)) {
            this.kwcw.moveAction = false;
        }
        if (!extend.isBool(this.kwcw.isMove)) {
            this.kwcw.isMove = false;
        }
        extend.addStorage(kwcwKey, this.kwcw);
    }

    /**
     * 本地读取仓位
     */
    localReadKwcw() {
        let res = extend.readStorage(kwcwKey);
        if (extend.isObject(res)) {
            this.kwcw = res;
            if (!extend.isNumber(this.kwcw.ZTID)) {
                this.kwcw.ZTID = 0;
            }
            if (!extend.isArray(this.kwcw.list)) {
                this.kwcw.list = [];
            }
            if (!extend.isBool(this.kwcw.moveAction)) {
                this.kwcw.moveAction = false;
            }
            if (!extend.isBool(this.kwcw.isMove)) {
                this.kwcw.isMove = false;
            }
        }
    }

    /**
     * 重置当前仓位信息
     */
    resetKwcw() {
        this.kwcw.CWID = null;
        this.kwcw.CWBM = null;
        this.kwcw.CWMC = null;
        this.kwcw.ZTID = 0;
        this.kwcw.moveAction = false;
        this.kwcw.isMove = false;
        this.localSaveKwcw();
    }

    /**
     * 设置二维码
     * @param {string} barcode 条码
     * @param {object} data 参数
     * @param {string} data.barcode 二维码
     * @param {number} data.customCompletionOrderLineId 总编号
     * @param {number} data.cwid 仓位内码
     * @param {number} data.cwbm 仓位编码
     */
    async setBarcode(data) {
        if (isError) {
            return message.playDing();
        }

        if (extend.isNull(this.order) || extend.isNull(data)) {
            return;
        }
        let line = this.getLine(data.customCompletionOrderLineId);
        if (!extend.isObject(line) || !extend.isArray(line.Codes)) {
            return;
        }
        let code = analyze.parse(data.barcode);
        if (extend.isNull(code)) {
            isError = true;
            await message.error({
                content: '无效条码'
            });
            isError = false;
            return;
        }
        if (line.Quantity === line.ScanedQty) {
            isError = true;
            await message.error({
                content: '数量已购'
            });
            isError = false;
            return;
        }
        let isConfirmed = false;
        for (let i in line.Codes) {
            if (line.Codes[i].Barcode === data.barcode) {
                isConfirmed = true;
                if (line.Codes[i].WarehouseConfirmed) {
                    isError = true;
                    await message.error({
                        content: '已扫描'
                    });
                    isError = true;
                    return;
                }
                line.Codes[i].WarehouseConfirmed = 1;
                line.Codes[i].CWID = this.kwcw.CWID;
                line.Codes[i].CWBM = this.kwcw.CWBM;
                line.Codes[i].CWMC = this.kwcw.CWMC;
                line.Codes[i].CodeStatus = shipPlanEnum.CodeStatus.Add;
                this.localSaveOrder();
                break;
            }
        }
        if (!isConfirmed) {
            isError = true;
            await message.error({
                content: '不属于当前产品'
            });
            isError = false;
            return;
        }
    }

    /**
     * 获取用户信息
     */
    async getUser() {
        this.user = user.get();
        if (extend.isNull(this.user)) {
            let tok = await token.getByServer();
            if (!tok.success) {
                message.error({
                    title: '提示',
                    content: '请登录后再试！'
                });
                return null;
            }
        }
        return this.user;
    }

    /**
     * 加载送货单
     * @param {string} orderNumber 送货单编号
     */
    async loadOrder(orderNumber) {
        if (isError) {
            return message.playDing();
        }

        uni.showLoading({
            title: '加载中'
        });
        await this.getUser();
        if (extend.isNull(this.user)) {
            return;
        }
        let res = await request.sendToken({
            url: `api/SmartDevice/MultiCustomizeDeliveryOrder/LoadCustomCompletionOrder`,
            method: 'get',
            data: {
                orderNumber: orderNumber,
                systemUserId: this.user.SystemUserId
            }
        });
        uni.hideLoading();
        if (res.success) {
            if (extend.isObject(res.data)) {
                this.init(res.data);
                this.resetKwcw();
                this.localSaveOrder();
            } else {
                isError = true;
                await message.alert({
                    title: '错误',
                    content: '接收的数据错误！',
                    showCancel: false
                });
                isError = false;
                return;
            }
        } else {
            isError = true;
            await message.alert({
                title: '错误',
                content: res.message,
                showCancel: false
            });
            isError = false;
            return;
        }
    }

    /**
     * 加载仓位列表
     */
    async loadKwcwList() {
        if (isError) {
            return message.playDing();
        }
        
        if (extend.isNull(this.order)) {
            return;
        }
        await this.getUser();
        if (extend.isNull(this.user)) {
            return;
        }
        let res = await request.sendToken({
            url: `api/SmartDevice/MultiCustomizeDeliveryOrder/ListKWCW`,
            method: 'get',
            data: {
                locationId: this.order.LocationId
            }
        });
        if (res.success) {
            if (extend.isArray(res.data)) {
                this.kwcw.moveAction = false;
                this.kwcw.isMove = false;
                this.kwcw.list = res.data;
                console.log(this.kwcw);
                this.localSaveKwcw();
            } else {
                isError = true;
                await message.alert({
                    title: '错误',
                    content: '接收的数据错误！',
                    showCancel: false
                });
                isError = false;
                return;
            }
        } else {
            isError = true;
            message.alert({
                title: '错误',
                content: res.message,
                showCancel: false
            });
            isError = false;
            return;
        }
    }
}