'use strict';

/**
 * 指标库控制器
 *
 * @author Mai
 * @data 2018/4/19
 * @version
 */
const fs = require('fs');
const path = require('path');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
module.exports = app => {

    const libConst = app.libConst;
    const paramConst = app.paramConst;

    class LibController extends app.BaseController {

        /**
         * 指标库页面
         *
         * @param {object} ctx - egg全局context
         * @return {void}
         */
        async index (ctx) {
            let status = ctx.query.status;
            const libList = await ctx.service.quotaLib.getList(status);

            //获取指标源状态数量
            const libStatus = await ctx.service.quotaLib.getStatusNum();
            const renderData = {
                status,
                libList,
                libConst,
                libStatus
            };
            await this.layout('lib/index.ejs', renderData, 'lib/modal.ejs');
        }

        /**
         * 上传指标源
         *
         * @param {object} ctx - egg全局context
         * @return {void}
         */
        async upload(ctx) {
            const parts = ctx.multipart({ autoFields: true });
            let addData = {};
            let stream;
            while ((stream = await parts()) != null) {
                const filename = stream.filename.toLowerCase();
                if(filename === ''){
                    throw '请上传文件';
                    ctx.redirect('/lib');
                }
                const fileInfo = path.parse(filename);
                let create_time = Date.parse( new Date())/1000;
                if(!fs.existsSync(libConst.quotaLibDir)) {
                    fs.mkdirSync(libConst.quotaLibDir);
                }
                let filepath = libConst.quotaLibDir + create_time + fileInfo.ext;

                addData = {
                    name: fileInfo.name,
                    path: filepath,
                    create_time: create_time
                };
                const target = path.join(filepath);
                const writeStream = fs.createWriteStream(target);
                try {
                    await awaitWriteStream(stream.pipe(writeStream));
                } catch (err) {
                    await sendToWormhole(stream);
                    throw err;
                }
            }
            if(addData !== {}){

                let fileStram = fs.readFileSync(addData.path, 'utf8');
                try {
                    const fileResult = JSON.parse(fileStram);

                    //插入数据到数据库
                    const result = await ctx.service.quotaLib.batchAdd(addData,fileResult);

                    // const result = await ctx.service.quotaLib.add(addData);
                    if (!result) {
                        //插入失败则删除文件;
                        fs.unlinkSync(addData.path);
                        throw '新增指标源数据失败';
                    }
                    ctx.redirect('/lib');
                } catch (err) {
                    //插入失败则删除文件;
                    fs.unlinkSync(addData.path);
                    throw err;
                }
            }else{
                throw '请上传文件';
            }
        }

        /**
         * 指标源全局参数页面
         *
         * @param {object} ctx - egg全局context
         * @return {void}
         */
        async global (ctx) {
            let lid = ctx.params.id;
            lid = parseInt(lid);

            try{
                if(isNaN(lid) || lid < 0){
                    throw '参数有误';
                }
                //获取指标源数据
                const libInfo = await ctx.service.quotaLib.getLibDataById(lid);

                //获取全局指标参数
                const condition = {
                    where: {
                        lib_id: lid,
                        node_id: 0,
                    }
                }
                const globalParams = await ctx.service.tenderParam.getAllDataByCondition(condition);
                const renderData = {
                    libInfo,
                    libConst,
                    globalParams,
                    paramConst,
                };
                await this.layout('lib/global.ejs', renderData);
            } catch (error) {
                console.log(error);
                ctx.redirect('/lib');
            }
        }

        /**
         * 指标源详细页面
         *
         * @param {object} ctx - egg全局context
         * @return {void}
         */
        async detail (ctx) {
            let lid = ctx.params.id;
            lid = parseInt(lid);

            try{
                if(isNaN(lid) || lid < 0){
                    throw '参数有误';
                }
                //获取指标源数据
                const libInfo = await ctx.service.quotaLib.getLibDataById(lid);
                //改变是否第一次进入detail页
                if(libInfo.openitem_tab === 0){
                    const reuslt = await ctx.service.quotaLib.updateOpenItemTab(lid);
                }
                const billsData = await ctx.service.bills.getDataByLibId(lid);
                // if(libInfo.status === libConst.status.enter){
                //     throw '指标源已入库';
                // }

                //获取项目节编号
                // const billsList = await ctx.service.bills.getListById(lid);
                const renderData = {
                    libInfo,
                    libConst,
                    billsData: JSON.stringify(billsData),
                };
                await this.layout('lib/detail.ejs', renderData, 'lib/detail-modal.ejs');
            } catch (error) {
                console.log(error);
                ctx.redirect('/lib');
            }
        }

        async getChildren(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const data = JSON.parse(ctx.request.body.data);
                const libId = data.lib_id;
                if (!libId) {
                    throw '当前未打开指标源';
                }
                const id = data.n_id;
                if (isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

                responseData.data = await ctx.service.bills.getChildrenByParentId(libId, id);
            } catch (err) {
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }

        /**
         * 删除指标源
         *
         * @param {Object} ctx -egg全局变量
         * @return {void}
         */
        async delete(ctx) {
            let id = ctx.request.body.del_lib_id;
            let text = ctx.request.body.del_lib_text;
            id = parseInt(id);

            try {
                if (isNaN(id) || id <= 0) {
                    throw '参数错误';
                }
                if(text === undefined || text.trim() !== '确认删除'){
                    throw '参数错误';
                }
                //获取指标源数据
                const libInfo = await ctx.service.quotaLib.getLibDataById(id);
                if(!libInfo){
                    throw '不存在该标段';
                }
                //删清指标源和清单数据
                const result = await ctx.service.quotaLib.deleteLibById(id);

                if (!result) {
                    throw '删除标段失败';
                }

                if(fs.existsSync(libInfo.filepath)) {
                    fs.unlinkSync(libInfo.filepath);
                }
                ctx.redirect('/lib');
            } catch (error) {
                console.log(error);
                ctx.redirect(ctx.request.headers.referer);
            }
        }

        /**
         * 指标源入库
         *
         * @param {Object} ctx -egg全局变量
         * @return {void}
         */
        async enter(ctx) {
            let id = ctx.request.body.enter_lib_id;
            id = parseInt(id);

            try {
                if (isNaN(id) || id <= 0) {
                    throw '参数错误';
                }
                const result = ctx.service.quotaLib.enterLibById(id);

                if (!result) {
                    throw '指标入库失败';
                }

                ctx.redirect('/lib');
            } catch (error) {
                console.log(error);
                ctx.redirect(ctx.request.headers.referer);
            }

        }

        async updateParamValue (ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: {},
            };
            const data = JSON.parse(ctx.request.body.data);
            try {
                if (!data.updateType) {
                    throw '参数修改提交类型未知';
                }
                if ((data.lib_id === undefined) || (data.node_id === undefined) || (data.code === undefined)) {
                    throw '提交信息错误';
                }
                let result;
                if (data.updateType === 'reset') {
                    result = await ctx.service.tenderParam.resetCalcValue(data);
                } else if (data.updateType === 'modify') {
                    result = await ctx.service.tenderParam.updateCalcValue(data);
                }
                if (!result) {
                    throw '提交数据失败';
                }
            } catch (err) {
                console.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            responseData.data.param = await ctx.service.tenderParam.getDataByCondition({
                lib_id: data.lib_id, node_id: data.node_id, code: data.code,
            });
            if (data.node_id !== 0) {
                responseData.data.indexes = await ctx.service.tenderIndex.getAllDataByCondition({
                    where: {lib_id: data.lib_id, node_id: data.node_id,}
                });
            }
            ctx.body = responseData;
        }


        /**
         * 获取指标和参数信息
        *
         * @param {Object} ctx -egg全局变量
         * @return {void}
         */
        async getParamAndIndex(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: {},
            };
            const data = JSON.parse(ctx.request.body.data);
            try {
                if (data.lib_id === undefined || data.node_id === undefined || data.bills_id === undefined) {
                    throw '提交信息错误';
                }
                //取指标编号列表
                responseData.data.indexList = await ctx.service.tenderIndex.getAllDataByCondition({
                    where: {lib_id: data.lib_id, node_id: data.node_id}
                });
                responseData.data.paramList = await ctx.service.tenderParam.getAllDataByCondition({
                    where: {lib_id: data.lib_id, node_id: data.node_id}
                });
            } catch (err) {
                console.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
            }

            ctx.body = responseData;
        }

    }

    return LibController;
}