'use strict';

/**
 *
 *
 * @author EllisRan.
 * @date 2018/4/19
 * @version
 */
const libConst = require('../const/lib');
module.exports = app => {

    class QuotaLib extends app.BaseService {

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

        /**
         * 获取指标源列表
         *
         * @param {Object} status - 指标源状态
         * @return {Array} - 返回列表数据
         */
        async getList(status = 0) {

            this.initSqlBuilder();

            if(status !== 0) {
                this.sqlBuilder.setAndWhere('status', {
                    value: status,
                    operate: '=',
                });
            }
            this.sqlBuilder.orderBy = [['id', 'desc']];
            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);

            return await this.db.query(sql, sqlParam);
        }

        /**
         * 获取指标源各状态数量
         *
         * @return {Array} - 返回数量列表数据
         */
        async getStatusNum() {
            const pend = await this.db.count(this.tableName, { status: libConst.status.pend });
            const enter = await this.db.count(this.tableName, { status: libConst.status.enter });
            const data = {
                pend,
                enter
            };
            return data;
        }

        /**
         * 新增指标源
         *
         * @param {Object} postData - 文件上传过来的数据
         * @return {Boolean} - 返回新增结果
         */
        async add(postData) {
            const insertData = {
                filename: postData.name,
                status: libConst.status.pend,
                filepath: postData.path,
                create_time: postData.create_time,
                enter_time: ''
            };
            const operate = await this.db.insert(this.tableName, insertData);
            return operate;
        }

        /**
         * 获取指标源详细页参数
         *
         * @return {Array} - 返回单条数据
         */
        async getLibDataById(id) {
            return await this.getDataById(id);
        }

        /**
         * 删除指标源
         *
         * @param {Object} id - 删除的id
         * @return {Boolean} - 删除结果
         */
        async deleteLibById(id) {
            const conn = await this.db.beginTransaction(); // 初始化事务
            try{
                const libResult = await this.ctx.service.quotaLib.deleteData({id: id}, conn);
                const billsResult = await this.ctx.service.bills.deleteData({lib_id: id}, conn);
                const indexResult = await this.ctx.service.tenderIndex.deleteData({lib_id: id}, conn);
                const nodeResult = await this.ctx.service.tenderNode.deleteData({lib_id: id}, conn);
                const paramResult = await this.ctx.service.tenderParam.deleteData({lib_id: id}, conn);
                await conn.commit(); // 提交事务
                return true;
            } catch(err) {
                console.log(err);
                await conn.rollback();
                throw err;
                return false;
            }

        }

        /**
         * 指标源入库
         *
         * @param {Object} id - 更新的id
         * @return {Boolean} - 更新结果
         */
        async enterLibById(id) {

            const updateData = {
                status: libConst.status.enter,
                enter_time: Date.parse( new Date())/1000,
                id,
            };

            const result = this.db.update(this.tableName, updateData);

            return result.affectedRows > 0;
        }

        /**
         * 改变第一次进入detail后状态
         *
         * @param {Object} id - 更新的id
         * @return {Boolean} - 更新结果
         */
        async updateOpenItemTab(id) {
            const updateData = {
                openitem_tab: 1,
                id,
            };

            const result = this.db.update(this.tableName, updateData);

            return result.affectedRows > 0;
        }

        /**
         * 指标源批量入库
         *
         * @param {Object} postData - 文件信息数据
         * @param {Object} jsonData - json文件数据
         * @return {Boolean} - 更新结果
         */
        async batchAdd(postData, jsonData) {
            const conn = await this.db.beginTransaction(); // 初始化事务
            try{
                const insertData = {
                    filename: postData.name,
                    status: libConst.status.pend,
                    filepath: postData.path,
                    create_time: postData.create_time,
                    enter_time: '',
                    RoadLevel: jsonData.properties.RoadLevel,
                    StartPegCode: jsonData.properties.StartPegCode,
                    EndPegCode: jsonData.properties.EndPegCode,
                    RoadLength: jsonData.properties.RoadLength,
                    RoadWidth: jsonData.properties.RoadWidth,
                };

                const libResult = await conn.insert(this.tableName, insertData);
                const lib_id = libResult.insertId;
                const billsData = jsonData.bills;
                for(let i = 0; i < billsData.length; i++) {
                    billsData[i] = this.ctx.helper.operationJson(billsData[i],'lib_id',lib_id);
                }
                await this.ctx.service.match.matchBills(billsData);
                const billsResult = await conn.insert('is_quota_bills',billsData);
                if (this.ctx.service.match.nodes.length > 0) {
                    const nodeResult = await this.ctx.service.tenderNode.insertData(this.ctx.service.match.nodes, conn);
                }
                if (this.ctx.service.match.indexes.length > 0) {
                    const indexResult = await this.ctx.service.tenderIndex.insertData(this.ctx.service.match.indexes, conn);
                }
                if (this.ctx.service.match.params.length > 0) {
                    const paramResult = await this.ctx.service.tenderParam.insertData(this.ctx.service.match.params, conn);
                }
                await conn.commit(); // 提交事务
                return true;
            } catch (err) {
                console.log(err);
                await conn.rollback();
                throw err;
                return false;
            }
        }


    }

    return QuotaLib;
}