'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/6/29
 * @version
 */

module.exports = app => {

    class MeasurePos extends app.BaseService {

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

        /**
         * 查询中间计量下部位信息
         *
         * @param {Number} tenderId - 标段id
         * @param {uuid} mid - 计量id
         * @returns {Promise<void>}
         */
        async getPosDetail(tenderId, mid) {
            const sql = 'SELECT MP.`tender_id`, MP.`mid`, MP.`pid`, L.`code`, L.`name`, L.`full_path` ' +
                'FROM ?? AS L, ?? AS MP ' +
                'WHERE L.`tender_id` = ? and MP.`tender_id` = ? and MP.`mid` = ?' +
                '    and MP.`pid` = L.`ledger_id`';
            const sqlParam = [this.ctx.service.ledger.tableName, this.tableName, tenderId, tenderId, mid];
            return await this.db.query(sql, sqlParam);
        }

        /**
         * 查询中间计量下，某一条部位信息
         * @param tenderId
         * @param mid
         * @param pid
         * @returns {Promise<*>}
         */
        async getPosData(tenderId, mid, pid) {
            const sql = 'SELECT MP.`tender_id`, MP.`mid`, MP.`pid`, L.`code`, L.`name`, L.`full_path` ' +
                'FROM ?? AS L, ?? AS MP ' +
                'WHERE L.`tender_id` = ? and MP.`tender_id` = ? and MP.`mid` = ? and MP.`pid` = ?' +
                '    and MP.`pid` = L.`ledger_id`';
            const sqlParam = [this.ctx.service.ledger.tableName, this.tableName, tenderId, tenderId, mid, pid];
            return await this.db.queryOne(sql, sqlParam);
        }

        /**
         * 新增计量范围
         *
         * @param {Number} tenderId - 标段id
         * @param {uuid} mid - 计量id
         * @param {Number} pid -- 计量范围id
         * @returns {Promise<*>}
         */
        async addPos(tenderId, mid, pid) {
            const result = await this.db.insert(this.tableName, {
                tender_id: tenderId,
                mid: mid,
                pid: pid,
                in_time: new Date(),
                in_user: this.ctx.session.sessionUser.accountId,
            });
            return await this.getPosData(tenderId, mid, pid);
        }

        /**
         * 删除计量范围
         *
         * @param {Number} tenderId - 标段id
         * @param {uuid} mid - 计量id
         * @param {Number} pid -- 计量范围id
         * @returns {Promise<void>}
         */
        async removePos(tenderId, mid, pid) {
            await this.db.delete(this.tableName, {
                tender_id: tenderId,
                mid: mid,
                pid: pid,
            });
        }
    }

    return MeasurePos;
};