/**
 * 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';

/**
 * OEM单总编号多仓位送货单
 */
export default class {
    /**
     * 订单
     */
    order = {
        SystemUserId: 0,
        LocationId: 0,
        Order: {
            Barcodes: [],
        }
    };

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

    constructor() {
        this.init();
    }

    /**
     * 初始化
     */
    async init() {
        this.user = await this.getUser();
        this.order.SystemUserId = this.user.SystemUserId;
        this.order.LocationId = 0;
        this.order.Order.Barcodes = [];
    }

    /**
     * 获取总数量
     * @returns {number}
     */
    get quantity() {
        let res = this.order.Order.Barcodes.length;
        return res;
    }

    /**
     * 所有行
     */
    get lines() {
        let lines = [];
        for (let i in this.order.Order.Barcodes) {
            let row = analyze.parse(this.order.Order.Barcodes[i].Text);
            if (extend.isNull(row)) {
                continue;
            }
            lines.push(row);
        }
        analyze.sortASC(lines);
        return lines;
    }

    /**
     * 查找行
     * @param {string} barcode 二维码
     */
    findBarcode(barcode) {
        let res = null;
        if (!extend.isString(barcode)) {
            return res;
        }
        for (let i in this.order.Order.Barcodes) {
            if (this.order.Order.Barcodes[i].Text === barcode) {
                res = this.order.Order.Barcodes[i];
                break;
            }
        }
        return res;
    }

    /**
     * 设置二维码
     * @param {string} barcode 二维码
     */
    async setBarcode(barcode) {
        let res = false;
        let code = analyze.parse(barcode);
        if (extend.isNull(code)) {
            message.showError({
                title: '无效条码'
            });
            return res;
        }
        let row = this.findBarcode(barcode);
        if (extend.isObject(row)) {
            message.showError({
                title: '已经扫描过！'
            });
            return res;
        }
        res = true;
        this.order.Order.Barcodes.push({
            Text: barcode,
            Scaned: true
        });
        return res;
    }

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