'use strict';

/**
 * 指标模板控制器
 *
 * @author Mai
 * @data 2018/4/19
 * @version
 */

// excel解析
const path = require('path');
const excel = require('node-xlsx');
const sendToWormhole = require('stream-wormhole');
module.exports = app => {

    const paramConst = app.paramConst;
    const nodeConst = app.nodeConst;

    class TemplateController extends app.BaseController {
        /**
         * 指标模板页面
         *
         * @param {object} ctx - egg全局context
         * @return {void}
         */
        async index (ctx) {
            const id = ctx.queries.id ? ctx.queries.id[0] : 1;
            const node = await ctx.service.templateNode.getAllDataByCondition({ where: { template_id: 1 } });
            for (const n of node) {
                n.url = '/template?id=' + n.node_id;
                n.target = '_self';
            }
            const treeNode = ctx.helper.convertData(node, true, 'node_id', 'node_pid');
            const condition = {template_id: 1, node_id: id};
            let selectNode = await ctx.service.templateNode.getDataByCondition(condition);
            if (!selectNode) {
                selectNode = {template_id: null, node_id: null, node_pid: null, code: '', name: '', match_type: null, match_key: ''}
            }
            const selectIndex = await ctx.service.templateIndex.getAllDataByCondition({ where: condition });
            const globalParams = await ctx.service.templateParam.getAllDataByCondition({ where: {template_id: 1, node_id: 0}});
            const nodeParams = await ctx.service.templateParam.getAllDataByCondition({ where: condition});
            const renderData = {
                nodes: JSON.stringify(treeNode),
                selectNode: selectNode,
                selectIndex: selectIndex,
                globalParams: globalParams,
                nodeParams: nodeParams,
                paramConst: paramConst,
                nodeConst: nodeConst,
            }
            await this.layout('template/index.ejs', renderData, 'template/modal.ejs');
        }

        /**
         * 导出Excel数据
         * @param ctx
         * @returns {Promise<void>}
         */
        async uploadExcel(ctx) {
            let stream;
            try {
                stream = await ctx.getFileStream();
                const create_time = Date.parse( new Date())/1000;
                const fileInfo = path.parse(stream.filename);
                const fileName = this.app.baseDir + '/app/public/template/uploads/' + 'template' + create_time + fileInfo.ext;
                // 保存文件
                await ctx.helper.saveStreamFile(stream, fileName);
                // 读取文件
                const sheet = excel.parse(fileName);
                if (!sheet || sheet.length === 0 || sheet[0] === undefined || sheet[0].data === undefined) {
                    throw 'excel没有对应数据';
                }
                const result = await ctx.service.templateNode.importData(sheet);
                if (!result) {
                    throw '导入数据失败';
                }
                ctx.redirect('/template');
            } catch (err) {
                console.log(err);
                // 失败需要消耗掉stream 以防卡死
                if (stream) {
                    await sendToWormhole(stream);
                }
                //this.setMessage(err.toString(), this.messageType.ERROR);
                ctx.redirect('/template');
            }
        }

        /**
         * 指标节点，绑定匹配规则
         * @param ctx
         * @returns {Promise<void>}
         */
        async updateNodeMatch(ctx) {
            const data =  JSON.parse(ctx.request.body.data);
            const condition = {
                template_id: 1,
                node_id: data.id
            };
            delete data.id;
            const responseData = {
                err: 0,
                msg: '',
                data,
            };
            try {
                responseData.data =  await ctx.service.templateNode.updateNodeMatch(data, condition);
            } catch (err) {
                console.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
                responseData.data = await ctx.service.templateNode.getDataByCondition(condition);
            }
            if (responseData.data.match_type) {
                responseData.data.match_type_str = nodeConst.matchTypeStr[responseData.data.match_type];
            } else {
                responseData.data.match_type_str = '';
            }
            ctx.body = responseData;
        }

        /**
         * 设置指标计算规则
         * @param ctx
         * @returns {Promise<void>}
         */
        async setIndexRule(ctx) {
            const result = await ctx.service.templateIndex.setRule(JSON.parse(ctx.request.body.data));
            const responseData = result ? { err: 0, msg: '', data: [], } : { err: 1, msg: '提交数据失败', data: [], };
            ctx.body = responseData;
        }

        /**
         * 指标参数，绑定参数取值等
         * @param ctx
         * @returns {Promise<void>}
         */
        async updateParamMatch(ctx) {
            const data =  JSON.parse(ctx.request.body.data);
            const condition = {
                template_id: 1,
                node_id: data.node_id,
                code: data.code,
            };
            delete data.node_id;
            delete data.code;
            const responseData = {
                err: 0,
                msg: '',
                data,
            };
            try {
                responseData.data =  await ctx.service.templateParam.updateNodeMatch(data, condition);
            } catch (err) {
                console.log(err);
                responseData.err = 1;
                responseData.msg = err.toString();
                responseData.data = await ctx.service.templateParam.getDataByCondition(condition);
            }
            if (responseData.data.match_num) {
                responseData.data.match_num_str = paramConst.matchNumStr[responseData.data.match_num];
            } else {
                responseData.data.match_num_str = '';
            }
            ctx.body = responseData;
        }
    }

    return TemplateController;
}