'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', 'sgfh_qty', 'sjcl_qty', 'qtcl_qty', 'in_time', 'porder'],
                order: [['porder', 'ASC']],
            });
        }

        async getPosDataByIds(ids) {
            if (ids instanceof Array && ids.length > 0) {
                const sql = 'SELECT id, tid, lid, name, quantity, drawing_code, sgfh_qty, sjcl_qty, qtcl_qty' +
                    '  FROM ' + this.tableName +
                    '  WHERE id in (' + this.ctx.helper.getInArrStrSqlFilter(ids) + ')';
                return await this.db.query(sql, []);
            } else {
                return [];
            }
            // this.initSqlBuilder();
            // this.sqlBuilder.setAndWhere('id', {
            //     operate: 'in',
            //     value: ids
            // });
            // this.sqlBuilder.columns = ['id', 'tid', 'lid', 'name', 'quantity', 'drawing_code', 'sgfh_qty', 'sjcl_qty', 'qtcl_qty'];
            // const [sql, sqlParam] = this.sqlBuilder.build(this.tableName)
            // return await this.db.query(sql, sqlParam);
        }

        async _insertPosData(transaction, data, tid) {
            data.id = this.uuid.v4();
            data.tid = tid;
            // todo 新增期
            data.add_stage = 0;
            data.add_times = 0;
            data.in_time = new Date();
            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);
        }

        /**
         * 保存部位明细数据
         * @param data
         * @param {Number} tid - 标段id
         * @returns {Promise<{ledger: {}, pos: null}>}
         */
        async savePosData(data, tid) {
            const result = { ledger: {}, pos: null };
            const transaction = await this.db.beginTransaction();
            try {
                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.sgfh_qty !== undefined || d.qtcl_qty !== undefined || d.sjcl_qty !== undefined) {
                            const bills = await this.ctx.service.ledger.getDataById(op.lid);
                            const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
                            if (d.sgfh_qty !== undefined) {
                                d.sgfh_qty = this.round(d.sgfh_qty, precision.value);
                            } else if (op) {
                                d.sgfh_qty = op.sgfh_qty;
                            }
                            if (d.sjcl_qty !== undefined) {
                                d.sjcl_qty = this.round(d.sjcl_qty, precision.value);
                            } else if (op) {
                                d.sjcl_qty = op.sjcl_qty;
                            }
                            if (d.qtcl_qty !== undefined) {
                                d.qtcl_qty = this.round(d.qtcl_qty, precision.value);
                            } else if (op) {
                                d.qtcl_qty = op.qtcl_qty;
                            }
                            d.quantity = this.ctx.helper.sum([d.sgfh_qty, d.qtcl_qty, d.sjcl_qty]);
                        }
                        await transaction.update(this.tableName, d, {tid: tid, id: d.id});
                        if (d.quantity !== undefined && 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();
            } catch (err) {
                await transaction.rollback();
                throw err;
            }
            result.pos = data.updateData;
            result.ledger.update = await this.ctx.service.ledger.getDataByIds(result.ledger.update);
            return result;
        }

        /**
         * 复制粘贴 部位明细数据
         * @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 = [];
            const orgPos = await this.getPosData({tid: tid, id: this._.map(data, 'id')});
            let bills = null, precision = null;
            try {
                for (const d of data) {
                    const op = d.id ? this._.find(orgPos, {id: d.id}) : null;
                    if (d.sgfh_qty || d.sjcl_qty || d.qtcl_qty) {
                        if (!bills || bills.id !== d.lid) {
                            bills = await this.ctx.service.ledger.getDataById(d.lid);
                            precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, bills.unit);
                            updateLid.push(d.lid);
                        }
                        if (d.sgfh_qty !== undefined) {
                            d.sgfh_qty = this.round(d.sgfh_qty, precision.value);
                        } else if (op) {
                            d.sgfh_qty = op.sgfh_qty;
                        }
                        if (d.sjcl_qty !== undefined) {
                            d.sjcl_qty = this.round(d.sjcl_qty, precision.value);
                        } else if (op) {
                            d.sjcl_qty = op.sjcl_qty;
                        }
                        if (d.qtcl_qty) {
                            d.qtcl_qty = this.round(d.qtcl_qty, precision.value);
                        } else if (op) {
                            d.qtcl_qty = op.qtcl_qty;
                        }
                        d.quantity = this.ctx.helper.sum([d.sgfh_qty, d.qtcl_qty, d.sjcl_qty]);
                    }
                    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) {
                    pd.id = this.uuid.v4();
                    pd.lid = newLid;
                    pd.tid = this.ctx.tender.id;
                    pd.in_time = new Date();
                }
                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);
            const insertDatas = [];
            for (const d of data) {
                const inD = {
                    id: this.uuid.v4(), tid: tid, lid: bills.id,
                    add_stage: 0, add_times: 0, add_user: this.ctx.session.sessionUser.accountId,
                    in_time: new Date(), porder: d.order,
                    name: d.name, drawing_code: d.drawing_code,
                };
                if (d.quantity) {
                    inD.sgfh_qty = this.round(d.quantity, precision.value);
                    inD.quantity = inD.sgfh_qty;
                }
                insertDatas.push(inD);
            }
            await transaction.insert(this.tableName, insertDatas);
        }
    }

    return Pos;
};