'use strict';

/**
 * 部位明细
 *
 * @author Mai
 * @date
 * @version
 */

module.exports = app => {

    class Pos extends app.BaseService {
        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            this.tableName = 'pos';
        }

        async getPosData(condition) {
            return await this.db.select(this.tableName, {
                where: condition,
                columns: ['id', 'tid', 'lid', 'name', 'quantity', 'drawing_code'],
            });
        }

        async _insertPosData(transaction, data, tid) {
            data.tid = tid;
            // todo 新增期
            data.add_stage = 0;
            data.add_times = 0;
            data.add_user = this.ctx.session.sessionUser.accountId;
            if (data.quantity) {
                const bills = await this.ctx.service.ledger.getDataById(data.lid);
                const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
                data.quantity = this._.round(data.quantity, precision.value);
            }
            const addRst = await transaction.insert(this.tableName, data);
            data.id = addRst.insertId;
        }

        /**
         * 保存部位明细数据
         * @param data
         * @param {Number} tid - 标段id
         * @returns {Promise<{ledger: {}, pos: null}>}
         */
        async savePosData(data, tid) {
            console.log(data);
            const transaction = await this.db.beginTransaction();
            try {
                const result = { ledger: {}, pos: null };
                if (data.updateType === 'add') {
                    const tender = await this.ctx.service.tender.getTender(tid);
                    if (data.updateData instanceof Array) {
                        for (const d of data.updateData) {
                            this._insertPosData(transaction, d, tid);
                        }
                    } else {
                        this._insertPosData(transaction, data.updateData, tid);
                    }
                } else if (data.updateType === 'update') {
                    const datas = data.updateData instanceof Array ? data.updateData : [data.updateData];
                    result.ledger.update = [];
                    const orgPos = await this.getPosData({tid: tid, id: this._.map(datas, 'id')});
                    for (const d of datas) {
                        const op = this._.find(orgPos, function (p) { return p.id = d.id; });
                        if (d.quantity) {
                            const bills = await this.ctx.service.ledger.getDataById(op.lid);
                            const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
                            d.quantity = this._.round(d.quantity, precision.value);
                        }
                        await transaction.update(this.tableName, d, {tid: tid, id: d.id});
                        if (d.quantity && op && (result.ledger.update.indexOf(op.lid) === -1)) {
                            result.ledger.update.push(op.lid);
                        }
                    }
                    for (const lid of result.ledger.update) {
                        await this.ctx.service.ledger.calc(tid, lid, transaction);
                    }
                } else if (data.updateType === 'delete') {
                    if (!data.updateData || data.updateData.length === 0) {
                        throw '提交数据错误';
                    }
                    const pos = await this.getPosData({tid: tid, id: data.updateData});
                    const ledgerIds = this._.map(pos, 'lid');
                    await transaction.delete(this.tableName, {tid: tid, id: data.updateData});
                    for (const lid of ledgerIds) {
                        await this.ctx.service.ledger.calc(tid, lid, transaction);
                    }
                    result.ledger.update = ledgerIds;
                } else {
                    throw '提交数据错误';
                }
                await transaction.commit();
                result.pos = data.updateData;
                result.ledger.update = await this.ctx.service.ledger.getDataByIds(result.ledger.update);
                return result;
            } catch (err) {
                await transaction.rollback();
                throw err;
            }
        }

        /**
         * 复制粘贴 部位明细数据
         * @param {Array} data - 复制粘贴的数据
         * @param {Number} tid - 标段id
         * @returns {Promise<{ledger: {}, pos: null}>}
         */
        async pastePosData(data, tid) {
            if (!(data instanceof Array)) {
                throw '提交数据错误';
            }

            const transaction = await this.db.beginTransaction();
            const result = { ledger: {}, pos: null }, updateLid = [];
            try {
                for (const d of data) {
                    if (d.quantity) {
                        const bills = await this.ctx.service.ledger.getDataById(d.lid);
                        const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
                        d.quantity = this._.round(d.quantity, precision.value);
                        console.log(updateLid);
                        if (updateLid.indexOf(d.lid) === -1) {
                            updateLid.push(d.lid);
                        }
                        console.log(updateLid);
                    }
                    if (d.id) {
                        await transaction.update(this.tableName, d);
                    } else {
                        this._insertPosData(transaction, d, tid);
                    }
                    for (const lid of updateLid) {
                        await this.ctx.service.ledger.calc(tid, lid, transaction);
                    }
                }
                await transaction.commit();
            } catch (err) {
                await transaction.rollback();
                throw err;
            }
            result.pos = data;
            if (updateLid.length > 0) {
                result.ledger.update = await this.ctx.service.ledger.getDataByIds(updateLid);
            }
            return result;
        }

        /**
         * 删除清单下部位明细数据(删除清单时调用)
         *
         * @param transaction - 事务
         * @param tid - 标段id
         * @param lid - 清单id
         * @returns {Promise<void>}
         */
        async deletePosData(transaction, tid, lid) {
            await transaction.delete(this.tableName, {tid: tid, lid: lid});
        }

        /**
         * 复制整块 拷贝部位明细数据
         * @param {Number} orgLid - 拷贝的部位明细所属台账id
         * @param {Number} newLid - 新的台账id
         * @param transaction - 复制整块事务
         * @returns {Promise<void>}
         */
        async copyBillsPosData(orgLid, newLid, transaction) {
            const posData = await this.getAllDataByCondition({ where: { lid: orgLid } });
            if (posData.length > 0) {
                for (const pd of posData) {
                    delete pd.id;
                    pd.lid = newLid;
                }
                await transaction.insert(this.tableName, posData);
            }
        }

        /**
         * 批量插入部位数据 - 仅供批量插入清单部位调用
         * @param transaction - 所属事务
         * @param {Number} tid - 标段id
         * @param {Number} lid - 台账id
         * @param {Array} data - 新增数据
         * @returns {Promise<void>}
         */
        async insertLedgerPosData(transaction, tid, bills, data) {
            const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
            for (const d of data) {
                d.tid = tid;
                d.lid = bills.id;
                // todo 新增期
                d.add_stage = 0;
                d.add_times = 0;
                d.add_user = this.ctx.session.sessionUser.accountId;
                if (d.quantity) {
                    d.quantity = this._.round(d.quantity, precision.value);
                }
            }
            await transaction.insert(this.tableName, data);
        }
    }

    return Pos;
};