'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/10/30
 * @version
 */

const infoConst = require('../const/tender_info');
const parseInfo = infoConst.parseInfo;
const defaultInfo = infoConst.defaultInfo;

module.exports = app => {

    class TenderInfo extends app.BaseService {

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

        /**
         * 新增 标段相关信息
         *
         * @param tenderId - 标段Id
         * @param projectId - 项目Id
         * @param transaction - 事务
         * @returns {Promise<void>}
         */
        async addTenderInfo(tenderId, projectId, transaction) {
            const info = JSON.parse(JSON.stringify(defaultInfo));
            info.tid = tenderId;
            info.pid = projectId;
            for (const pi of parseInfo) {
                info[pi] = JSON.stringify(info[pi])
            }

            if (transaction) {
                await transaction.insert(this.tableName, info);
            } else {
                await this.db.insert(this.tableName, info);
            }
            return info;
        }

        /**
         * 获取标段相关信息
         * @param tenderId
         * @returns {Promise<void>}
         */
        async getTenderInfo(tenderId) {
            let info = await this.getDataByCondition({tid: tenderId});
            // 兼容不存在info的情况
            if (!info) {
                info = await this.addTenderInfo(tenderId, this.ctx.session.sessionProject.id);
            }
            for (const pi of parseInfo) {
                info[pi] = !info[pi] || info[pi] === '' ? defaultInfo[pi] : JSON.parse(info[pi]);
            }
            return info;
        }

        /**
         * 保存标段相关信息
         *
         * @param data
         * @returns {Promise<void>}
         */
        async saveTenderInfo(tenderId, data) {
            for (const di in data) {
                if (parseInfo.indexOf(di) >= 0) {
                    data[di] = JSON.stringify(data[di]);
                }
            }
            await this.db.update(this.tableName, data, {where: {tid: tenderId}});
        }
    }

    return TenderInfo;
};