/**
 * Created by jimiz on 2017/4/16.
 */
var Project = require('../models/project');
let logger = require('../../../logs/log_helper').logger;
let project_facade = require("../facade/project_facade");
const redirectToImportServer = require('../../pm/controllers/pm_controller').redirectToImportServer;
const multiparty = require("multiparty");
const iconv = require('iconv-lite'); 

//统一回调函数
var callback = function(req, res, err, message, data){
    res.json({error: err, message: message, data: data});
};

module.exports = {
    save: function (req, res) {
        if(typeof req.body.data === 'object'){
            req.body.data = JSON.stringify(req.body.data);
        }
        var data = JSON.parse(req.body.data);
        Project.save(data, function (err, message, result) {
            if (err) {
                logger.err(err);
                callback(req, res, err, message, null);
            } else {
                callback(req, res, err, message, result);
            }
        });
    },
    getData: function (req, res) {
        //add
        console.log(`------------------------------------------`);
        console.log(`${req.session.sessionUser.real_name}--id:${req.session.sessionUser.id}--取getdata数据`);
        console.log(`------------------------------------------`);
        //add
        if(typeof req.body.data === 'object'){
            req.body.data = JSON.stringify(req.body.data);
        }
        var data = JSON.parse(req.body.data);
        // 注释代码用于测试getFilterData
        // Project.getFilterData(data.project_id, ['bills', 'projectGLJ'], function (err, result) {
        //     console.log(result);
        // });
        const isReport = false;
        Project.getData(data.project_id, function (err, message, result) {
            if (!err) {
                callback(req, res, err, message, result);
            } else {
                callback(req, res, err, message, null);
            }
        }, isReport, req.session.sessionUser.id);
    },
    getDataForInterface: async function (req, res) {
        const data = JSON.parse(req.body.data);
        let result={
            error:0
        };
        try {
            result = await redirectToImportServer(data,"getDataForInterface",req);
        } catch (err) {
            console.log(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
    markUpdateProject:async function (req,res) {
        let result={
            error:0
        }
        try {
            let data = req.body.data;
            data = JSON.parse(data);
            let resultData= await project_facade.markUpdateProject(data.updateInfo,data.type);
            result.data=resultData;
        }catch (err){
            logger.err(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
    removeProjectMark:async function(req,res){
        let result={
            error:0
        }
        try {
            let data = req.body.data;
            data = JSON.parse(data);
            let resultData= await project_facade.removeProjectMark(data.projectID);
            result.data=resultData;
        }catch (err){
            logger.err(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
    updateNodes:async function (req,res) {
        let result={
            error:0
        }
        try {
            let data = req.body.data;
            if(typeof data === 'object'){
                data = JSON.stringify(data);
            }
            data = JSON.parse(data);
            let resultData= await project_facade.updateNodes(data);
            result.data=resultData;
        }catch (err){
            logger.err(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);

    },
    calcInstallationFee:async function(req,res){
        let result={
            error:0
        }
        try {
            let data =  JSON.parse(req.body.data);
            let resultData= await project_facade.calcInstallationFee(data);
            result.data=resultData;
        }catch (err){
            logger.err(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
    async calcOverHeightFee (req, res) {
        try {
            const data = JSON.parse(req.body.data);
            const rst = await project_facade.calcOverHeightFee(data);
            res.json({ error: 0, data: rst, message: 'success' });
        } catch (err) {
            console.log(err);
            res.json({ error: 1, data: null, message: err.message });
        }
    },
    saveProperty: function(req, res){
        let result = {error: 0, message: '', data: null};
        let data = JSON.parse(req.body.data);
        project_facade.saveProperty(data, function (err, data) {
            if (err == ''){
                result.data = data;
            }else{
                result.error = 1;
                result.message = err;
            }
            res.json(result);
        })
    },
    getDefaultColSetting: async function(req, res){
        let data = JSON.parse(req.body.data);
        let result={
            error: 0,
            data: null
        };
        try{
            result.data = await project_facade.getDefaultColSetting(data.libID);
        }
        catch(err){
            logger.err(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
    getSEIProjects:async function(req,res){
        let data = JSON.parse(req.body.data);
        let result={
            error: 0,
            data: null
        };
        try{
            result.data = await project_facade.getSEIProjects(data.projectID);
        }
        catch(err){
            logger.err(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
    loadSEIProjectData:async function(req,res){
        const data = JSON.parse(req.body.data);
        let result={
            error:0
        };
        try {
            result = await redirectToImportServer(data,"loadSEIProjectData",req);
        } catch (err) {
            console.log(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
    getDecodedData: async function(req, res) {
        const responseData = {
            err: 0,
            msg: '',
            data: null
        };
        try {
            const { unit8ArraySouces, encoding } = JSON.parse(req.body.data);
            responseData.data = unit8ArraySouces.map(unit8ArraySrc => {
                const buffer = toArrayBuffer(unit8ArraySrc);
                return iconv.decode(Buffer.from(buffer), encoding);
            });;
        } catch (err) {
            responseData.err = 1;
            responseData.msg = typeof error === 'object' ? '解码失败' : error;
        } finally {
            res.json(responseData);
        }

        function toArrayBuffer(src) {
            const ab = new ArrayBuffer(src.length);
            const view = new Uint8Array(ab);
            for (let i = 0; i < src.length; i++) {
                view[i] = +src[i];
            }
            return ab;
        }
    },
    getEncodedData: async function(req, res) {
        const responseData = {
            err: 0,
            msg: '',
            data: null
        };
        try {
            const { source, encoding, toBase64 } = JSON.parse(req.body.data);
            const data = {};
            source.forEach(str => {
                const u8 = iconv.encode(str, encoding);
                data[str] = toBase64 
                    ? Buffer.from(u8).toString('base64')
                    : u8;
            });
            responseData.data = data;
        } catch (err) {
            responseData.err = 1;
            responseData.msg = typeof error === 'object' ? '编码失败' : error;
        } finally {
            res.json(responseData);
        }
    },
    getCompareProjects:async function(req,res){
        let result={
            error:0
        };
        try {

            result = await project_facade.getCompareProjects(req.session.sessionUser.id, req.session.sessionCompilation._id);
        } catch (err) {
            console.log(err.stack);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    },
};