/**
 * 完工单解析
 */
import extend from '../utils/extend.js';
import analyze from '../utils/analyzeScannedContent.js';
import shipPlanEnum from '../utils/shipPlanEnum.js';
import user from '../utils/user.js';
import message from '../utils/message.js';

/**
 * 完工送货单
 */
export default class {
    /**
     * 订单
     */
    order = null;

    /**
     * 订单编码
     */
    orderNumber = '';

    id = -100;

    user = null;

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

    /**
     * 初始化
     */
    init(order) {
        if (!(extend.isObject(order) || extend.isObject(this.order) || order === null)) {
            return;
        }
        this.order = order;

        if (order === null) {
            return;
        }
    }

    /**
     * 计划扫码状态
     */
    get planScanStatus() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.PlanScanStatus)) {
            res = this.order.PlanScanStatus;
        }
        return res;
    }

    /**
     * 装车计划号
     */
    get shipPlanId() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.ShipPlanId)) {
            res = this.order.ShipPlanId;
        }
        return res;
    }

    /**
     * 装车计划号
     */
    get planNumber() {
        let res = '';
        if (extend.isObject(this.order) && extend.isString(this.order.PlanNumber)) {
            res = this.order.PlanNumber;
        }
        return res;
    }

    /**
     * 装车计划总件数
     */
    get totalPackeagQty() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.TotalPackeagQty)) {
            res = this.order.TotalPackeagQty;
        }
        return res;
    }

    /**
     * 已扫描总件数
     */
    get totalScanedQty() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.TotalScanedQty)) {
            res = this.order.TotalScanedQty;
        }
        return res;
    }

    /**
     * 剩余未扫码数量
     */
    get totalUnScanedQty() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.TotalUnScanedQty)) {
            res = this.order.TotalUnScanedQty;
        }
        return res;
    }

    /**
     * 欠货件数
     */
    get totalOweQty() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.TotalOweQty)) {
            res = this.order.TotalOweQty;
        }
        return res;
    }

    /**
     * 剩货件数
     */
    get totalRemainQty() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.TotalRemainQty)) {
            res = this.order.TotalRemainQty;
        }
        return res;
    }

    /**
     * 剩货件数
     */
    get totalAddedQty() {
        let res = 0;
        if (extend.isObject(this.order) && extend.isNumber(this.order.TotalAddedQty)) {
            res = this.order.TotalAddedQty;
        }
        return res;
    }

    /**
     * 所有行
     */
    get lines() {
        let lines = [];
        if (extend.isObject(this.order) && extend.isArray(this.order.Lines)) {
            this.countLinesQty(this.order.Lines);
            lines = this.order.Lines;
        }
        return lines;
    }

    /**
     * 欠货列表
     */
    get oweLines() {
        let lines = [];
        if (extend.isObject(this.order) && extend.isArray(this.order.Lines)) {
            for (let i = 0; i < this.order.Lines.length; i++) {
                if (extend.isNumber(this.order.Lines[i].OweQty) && this.order.Lines[i].OweQty > 0) {
                    lines.push(this.order.Lines[i]);
                }
            }
        }
        return lines;
    }

    /**
     * 剩货列表
     */
    get remainLines() {
        let lines = [];
        if (extend.isObject(this.order) && extend.isArray(this.order.Lines)) {
            for (let i = 0; i < this.order.Lines.length; i++) {
                if (extend.isNumber(this.order.Lines[i].RemainQty) && this.order.Lines[i].RemainQty > 0) {
                    lines.push(this.order.Lines[i]);
                }
            }
        }
        return lines;
    }

    /**
     * 加货列表
     */
    get addLines() {
        let lines = [];
        if (extend.isObject(this.order) && extend.isArray(this.order.Lines)) {
            for (let i = 0; i < this.order.Lines.length; i++) {
                if (this.order.Lines[i].Type === shipPlanEnum.ShipPlanPackageInfoType.PDAScan) {
                    lines.push(this.order.Lines[i]);
                }
            }
        }
        return lines;
    }

    /**
     * 叉板列表
     */
    get forks() {}

    /**
     * 计算行数量
     */
    countLinesQty(lines) {
        if (!extend.isArray(lines)) {
            lines = [];
        }
        for (let i in lines) {
            lines[i].ScanQty = 0;
            lines[i].RemainQty = 0;
            lines[i].AddedQty = 0;
            if (extend.isArray(lines[i].Barcodes)) {
                for (let j in lines[i].Barcodes) {
                    if (lines[i].Barcodes[j].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Scaned) {
                        lines[i].ScanQty++;
                    } else if (lines[i].Barcodes[j].Status === shipPlanEnum
                        .ShipPlanPackageBarcodeStatus.Remain) {
                        lines[i].Remain++;
                    } else if (lines[i].Barcodes[j].Status === shipPlanEnum
                        .ShipPlanPackageBarcodeStatus.Added) {
                        lines[i].Added++;
                    }
                }
            }
        }
        return lines;
    }

    /**
     * 通过条码查找产品列表
     */
    searchLinesByBarcode(barcode) {
        let lines = [];
        if (extend.isNull(this.order)) {
            return lines;
        }
        if (!extend.isArray(this.order.Lines)) {
            this.order.Lines = [];
        }
        for (let i = 0; i < this.order.Lines.length; i++) {
            if (!extend.isArray(this.order.Lines[i].Barcodes)) {
                this.order.Lines[i].Barcodes = [];
            }
            for (let j = 0; j < this.order.Lines[i].Barcodes.length; j++) {
                if (barcode === this.order.Lines[i].Barcodes[j].Barcode) {
                    if ((this.order.PlanScanStatus === shipPlanEnum.ScanStatus.Adding || this.order
                            .PlanScanStatus === shipPlanEnum.ScanStatus.UnAdd) && this.order.Lines[i].Barcodes[j]
                        .Barcode.Type != 1) {
                        continue;
                    }
                    lines.push(this.order.Lines[i]);
                    break;
                }
            }
        }
        return lines;
    }

    /**
     * 通过料号查找不存在条码的产品列表
     * @param {string} barcode 条码
     */
    searchNonBarcodeInLinesByInventoryNumber(barcode) {
        let lines = [];
        if (extend.isNull(this.order)) {
            return lines;
        }
        if (!extend.isArray(this.order.Lines)) {
            this.order.Lines = [];
        }
        if (!extend.isString(barcode) || barcode.length != 36) {
            return message.showError({
                title: '无效条码',
            });
        }
        let isFind = false;
        let code = analyze.parse(barcode);
        for (let i in this.order.Lines.length) {
            isFind = false;
            if (barcode !== code.InventoryNumber) {
                continue;
            }
            if (barcode === this.order.Lines[i].Barcode) {
                for (let j in this.order.Lines[i].Barcodes) {
                    if (barcode === this.order.Lines[i].Barcodes[j].Barcode) {
                        isFind = true;
                        break;
                    }
                }

                if (!isFind) {
                    lines.push(this.order.Lines[i]);
                }
            }
        }
        return lines;
    }

    /**
     * 设置二维码
     * @param {string} barcode 条码
     */
    async setBarcode(barcode) {
        if (extend.isNull(this.order)) {
            return;
        }
        let isAdd = false;
        let lines = this.searchLinesByBarcode(barcode);

        // 如果有就该状态，没有就新增
        if (lines.length > 0) {} else {
            if (order.order.PlanScanStatus === shipPlanEnum.ScanStatus.Adding || order.order.planScanStatus ===
                shipPlanEnum.ScanStatus.UnAdd) {
                isAdd = true;
                // 获取加货产品行
                let line = await this.getAddLinesByInventoryNumber(barcode);

                if (extend.isObject(line)) {
                    lines.push(line);
                }
            } else {
                // 通过条码和产品编码获取产品列表
                let line = 1;
                lines = this.searchNonBarcodeInLinesByInventoryNumber(barcode);

                // 插入产品行
                this.insertLines(lines);
            }
        }

        if (lines.length === 0 && !isAdd) {
            return message.showError({
                title: '无效条码',
            });
        }

        // 更新产品行
        this.insertLines(lines);
    }

    /**
     * 插入产品行
     */
    insertLines(lines) {
        if (!extend.isArray(lines)) {
            return;
        }
        for (let i in lines) {
            if (this.order.PlanScanStatus === shipPlanEnum.ScanStatus.Default) {
                // 正常
                if (lines[i].ScanQty === lines[i].Quantity) {
                    return message.error({
                        title: '提示',
                        content: '已达数量上限'
                    });
                }
                lines[i].Barcodes.push({
                    ShipPlanPackageId: lines.Id,
                    Barcode: barcode,
                    Status: shipPlanEnum.ShipPlanPackageBarcodeStatus.Scaned,
                    ScanBy: this.user.UserName,
                    ForkNumber: this.order.CurrentFork.ForkNumber
                });
            } else if (this.order.planScanStatus === shipPlanEnum.ScanStatus.Adding) {
                // 加货
                if (!extend.isNumber(lines[i].Quantity)) {
                    lines[i].Quantity = 0;
                }
                lines[i].Quantity++;
                lines[i].Barcodes.push({
                    ShipPlanPackageId: lines.Id,
                    Barcode: barcode,
                    Status: shipPlanEnum.ShipPlanPackageBarcodeStatus.Added,
                    ScanBy: this.user.UserName,
                    ForkNumber: this.order.CurrentFork.ForkNumber
                });
            }
        }
    }

    /**
     * 更新产品行
     */
    updateLines(lines) {
        if (!extend.isArray(lines)) {
            return;
        }
        for (let i in lines) {
            if (this.order.PlanScanStatus === shipPlanEnum.ScanStatus.Default) {
                // 正常
                if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Scaned) {
                    if (extend.isNull(lines[i].ForkNumber)) {
                        lines[i].ForkNumber = this.order.CurrentFork.ForkNumber;
                    }
                } else if(lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Added) {
                    return message.showError({
                        title: '已扫描'
                    });
                } else {
                    lines[i].Status = shipPlanEnum.ShipPlanPackageBarcodeStatus.Scaned;
                    lines[i].ForkNumber = this.order.CurrentFork.ForkNumber;
                }
            } else if (this.order.PlanScanStatus === shipPlanEnum.ScanStatus.Remain) {
                // 剩货
                if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Scaned) {
                    lines[i].Status = shipPlanEnum.ShipPlanPackageBarcodeStatus.Remain;
                } else if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Remain) {
                    return message.showError({
                        title: '已扫描'
                    });
                } else if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Added) {
                    return message.error({
                        title: '提示',
                        content: '此为加货'
                    });
                } else {
                    return message.error({
                        title: '提示',
                        content: '不是本车已扫描的条码！'
                    });
                }
            } else if (this.order.PlanScanStatus === shipPlanEnum.ScanStatus.Adding) {
                // 加货
                if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Added) {
                    return message.showError({
                        title: '已扫描'
                    });
                } else if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.UnAdded) {
                    lines[i].Status = shipPlanEnum.ShipPlanPackageBarcodeStatus.Added;
                    lines[i].ForkNumber = this.order.CurrentFork.ForkNumber;
                } else {
                    return message.error({
                        title: '提示',
                        content: '不是加货条码'
                    });
                }
            } else if (this.order.PlanScanStatus === shipPlanEnum.ShipPlanPackageBarcodeStatus.UnAdded) {
                if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.Added) {
                    lines[i].Status = shipPlanEnum.ShipPlanPackageBarcodeStatus.UnAdded;
                } else if (lines[i].Status === shipPlanEnum.ShipPlanPackageBarcodeStatus.UnAdded) {
                    return message.showError({
                        title: '已扫描',
                        icon: 'error'
                    });
                } else {
                    return message.showError({
                        title: '提示',
                        content: '不是加货条码'
                    });
                }
            }
        }
    }

    /**
     * 获取装车计划
     * @param {string} orderNumber 装车计划号
     */
    async getShipPlan(orderNumber) {
        let res = await request.sendToken({
            url: `api/PDAScan/GetShipPlanLineByOrderNumber?shipOrderNumber=${this.orderNumber}`,
            method: 'post'
        });
        if (res.success) {
            if (extend.isObject(res.data.Result)) {
                this.init(res.data.Result);
            }
        } else {
            message.alert({
                title: '错误',
                content: res.message,
                showCancel: false
            });
        }
    }

    /**
     * 获取单行
     * @param {string} barcode 条码
     */
    async getAddLinesByInventoryNumber(barcode) {
        let coder = analyze.parse(barcode);
        if (coder === null) {
            return;
        }
        let line = null;
        let res = await request.sendToken({
            url: `api/PDAScan/GetShipPlanPackageInfByInventoryNumer?inventoryNumer=${coder.InventoryNumber}`,
            method: 'get'
        });
        if (res.success) {
            if (extend.isObject(res.data.Result)) {
                line = res.data.Result;
                line.Type = shipPlanEnum.ShipPlanPackageInfoType.PDAScan;
                id--;
                line.Id = id;
                line.ShipPlanId = this.order.ShipPlanId;
                this.order.Lines.push(line);
            } else {
                message.error({
                    title: '错误',
                    content: '未获取到数据！'
                });
            }
        } else {
            message.alert({
                title: '错误',
                content: res.message,
                showCancel: false
            });
        }
        return line;
    }
}

class ShipPlanPackageInfo {
    Barcode = '';
    CompletionConfirmed = 0;
    CompletionConfirmedOn = null;
    CompletionOrderLineId = 0;
    WarehouseConfirmed = 0;
    WarehouseConfirmedOn = null;
}