'use strict';

/**
 * 期计量 数据模型
 *
 * @author Mai
 * @date 2018/8/13
 * @version
 */

const audit = require('../const/audit');

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

        /**
         * 获取标段下的全部计量期，按倒序
         * @param tenderId
         * @returns {Promise<void>}
         */
        async getValidStages(tenderId) {
            return await this.db.select(this.tableName, {
                where: {tid: tenderId},
                orders: [['order', 'desc']],
            });
        }

        /**
         *
         * @param tenderId - 标段id
         * @param date - 计量年月
         * @param period - 开始-截止日期
         * @returns {Promise<void>}
         */
        async addStage(tenderId, date, period) {
            const stages = await this.getAllDataByCondition({
                where: {tid: tenderId},
                order: ['order'],
            });
            if (stages.length > 0 && stages[stages.length - 1].status !== audit.flow.status.checked) {
                throw '上一期未审批通过，请等待上一期审批通过后，再新增数据';
            };
            const order = stages.length + 1;
            const newStage = {
                sid: this.uuid.v4(),
                tid: tenderId,
                order: order,
                in_time: new Date(),
                s_time: date,
                period: period,
                times: 1,
                status: audit.flow.status.uncheck,
                user_id: this.ctx.session.sessionUser.accountId,
            };
            const result = await this.db.insert(this.tableName, newStage);
            return result.affectedRows === 1 ? newStage : null;
        }

        /**
         * 编辑计量期
         *
         * @param {Number} tenderId - 标段Id
         * @param {Number} order - 第N期
         * @param {String} date - 计量年月
         * @param {String} period - 开始-截止时间
         * @returns {Promise<void>}
         */
        async saveStage(tenderId, order, date, period) {
            await this.db.update(this.tableName, {
                s_time: date,
                period: period,
            }, { where: { tid: tenderId, order: order } });
        }

        /**
         * 设置 中间计量 生成规则，并生成数据
         * @param {Number} tenderId - 标段id
         * @param {Number} order - 期序号
         * @param {Number} data - 中间计量生成规则
         * @returns {Promise<void>}
         */
        async buildDetailData(tenderId, order, data) {
            const conn = await this.db.beginTransaction();
            try {
                await conn.update(this.tableName, { im_type: data.im_type, im_pre: data.im_pre }, { where: { tid: tenderId, order: order } });
                // to do 生成中间计量数据
                await conn.commit();
            } catch (err) {
                await conn.rollback();
                throw err;
            }
        }
    }

    return Stage;
};