/**
 * Created by chen on 2017/6/29.
 */
let mongoose = require("mongoose")
let ration_glj_facade = require('../facade/ration_glj_facade')
const EngineeringLibModel = require("../../users/models/engineering_lib_model");
let logger = require("../../../logs/log_helper").logger;
const { COMPILATION, COMPLEMENTARY_LIB, ShareLibType } = require('../../../public/common_constants');
const pmFacade = require('../../pm/facade/pm_facade');

module.exports={
    createRationGLJ:createRationGLJ,
    testGetQuantify:testGetQuantify,
    getGLJData:getGLJData,
    getGLJDataPaging: getGLJDataPaging,
    getGLJDataByCodes:getGLJDataByCodes,
    addGLJ:addGLJ,
    replaceGLJ:replaceGLJ,
    mReplaceGLJ:mReplaceGLJ,
    updateRationGLJByEdit:updateRationGLJByEdit,
    getGLJClass:getGLJClass
}
function createRationGLJ() {
    let gls = mongoose.model('ration_glj');
    gls.create({'GLJID':1,'basePrice':23.23,'name':"testgls"},function(err, gls){
        console.log(gls)
    })
}

//测试获取消耗量：
async function testGetQuantify() {
    var condition = {
        projectID:99,
        projectGLJIDList:[60,61,62]
    }

    try{
        let result = await ration_glj_facade.getQuantityByProjectGLJ(condition);
        console.log(result)
    }catch (err){
        console.log(err);
    }
}

async function getGLJDataByCodes(req,res){
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let datas= await ration_glj_facade.getGLJDataByCodes(data,req.session.sessionCompilation);
        result.data=datas;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async function getGLJDataPaging(req, res) {
    let result={
        error:0
    };
    let { condition } = JSON.parse(req.body.data);
    try {
        const compilationId = req.session.sessionCompilation._id;
        const userID = req.session.sessionUser.id;
        let libData = null;
        const cptLibReg = new RegExp(COMPLEMENTARY_LIB);
        if (!cptLibReg.test(condition.gljLibID)) {
            condition.gljLibID = +condition.gljLibID;
        }
        if (condition.initLibs) {
            libData = await ration_glj_facade.getLibOptionsForCompilation(compilationId);
            libData.push({ name: '我的补充人材机库', gljLibId: COMPLEMENTARY_LIB });
            // 设置被分享的人材机库
            const receiveData = await pmFacade.getReceiveLibList(userID, compilationId, ShareLibType.GLJ_LIB);
            receiveData.forEach(user => {
                libData.push({ name: `${user.real_name}的补充人材机库`, gljLibId: `${COMPLEMENTARY_LIB}*${user._id}` });
            });
            if (condition.gljLibID) { // 替换人材机初始化会触发此条件(初始化库且定位了库)
                const orgDefalutLib = libData.find(lib => lib.isDefault);
                const newDefaultLib = libData.find(lib => lib.gljLibId === condition.gljLibID);
                if (orgDefalutLib && newDefaultLib) {
                    orgDefalutLib.isDefault = false;
                    newDefaultLib.isDefault = true;
                }
            }
        }
        if (!condition.gljLibID && libData) {
            condition.gljLibID = (libData.find(lib => lib.isDefault) || {}).gljLibId;
        }
        let info;
        if (cptLibReg.test(condition.gljLibID)) {
            const owner = condition.gljLibID.split('*')[1] || userID;
            info = { gljLibId: null, userID: owner, compilationId  };
        } else {
            info = { gljLibId: condition.gljLibID, userID: null, compilationId: null };
        }
        /* const info = condition.gljLibID === COMPLEMENTARY_LIB
            ? { gljLibId: null, userID, compilationId  }
            : { gljLibId: condition.gljLibID, userID: null, compilationId: null }; */
        result.data = await ration_glj_facade.getGLJDataPaging(info, condition);
        if (req.session.sessionCompilation.priceProperties) {
            result.data.priceProperties = req.session.sessionCompilation.priceProperties
        }
        result.data.libData = libData;
        res.json(result);
    } catch (err) {
        logger.err(err);
        result.error=1;
        result.message = err.message;
        res.json(result);
    }
}

/* async function getGLJData(req, res) {
    let result={
        error:0
    }
    try {
        let info = await ration_glj_facade.getLibInfo(req);
        ration_glj_facade.getGLJData(info,function (err,datas) {
            if(err){
                result.error=1;
                result.message = err.message;
            }else {
                //多单价字段
                if(req.session.sessionCompilation.priceProperties) datas.priceProperties = req.session.sessionCompilation.priceProperties;
                result.datas = datas;
            }
            res.json(result);
        });
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
        res.json(result);
    }
} */
async function getGLJData(req, res) {
    let result={
        error:0
    }
    try {
        let libData = null;
        let { engineerID, gljLibId, isInitial } = req.params;
        const userID = req.session.sessionUser.id;
        const compilationId = req.session.sessionCompilation._id;
        const cptLibReg = new RegExp(COMPLEMENTARY_LIB);
        if (!cptLibReg.test(gljLibId)) {
            gljLibId = +gljLibId;
        }
        isInitial = JSON.parse(isInitial);
        if (!gljLibId || isInitial) { // 替换人材机的话，可能存在gljLibID，但是是初始化的操作
            libData = engineerID === COMPILATION 
            ? await ration_glj_facade.getLibOptionsForCompilation(compilationId)
            : await ration_glj_facade.getLibOptions(engineerID);
            libData.push({ name: '我的补充人材机库', gljLibId: COMPLEMENTARY_LIB });
            // 设置被分享的人材机库
            const receiveData = await pmFacade.getReceiveLibList(userID, compilationId, ShareLibType.GLJ_LIB);
            receiveData.forEach(user => {
                libData.push({ name: `${user.real_name}的补充人材机库`, gljLibId: `${COMPLEMENTARY_LIB}*${user._id}` });
            });
            if (gljLibId) { // 替换人材机初始化会触发此条件
                const orgDefalutLib = libData.find(lib => lib.isDefault);
                const newDefaultLib = libData.find(lib => lib.gljLibId === gljLibId);
                if (orgDefalutLib && newDefaultLib) {
                    orgDefalutLib.isDefault = false;
                    newDefaultLib.isDefault = true;
                }
            }
        }
        let skipGLJ = gljLibId === 0;
        if (!gljLibId && libData) {
            gljLibId = (libData.find(lib => lib.isDefault) || {}).gljLibId;
        }
        let info;
        if (cptLibReg.test(gljLibId)) {
            const owner = gljLibId.split('*')[1] || userID;
            info = { gljLibId: null, userID: owner, compilationId  };
        } else {
            info = { gljLibId, userID: null, compilationId: null };
        }
/*         const info = gljLibId === COMPLEMENTARY_LIB 
            ? { gljLibId: null, userID: req.session.sessionUser.id, compilationId: req.session.sessionCompilation._id }
            : { gljLibId, userID: null, compilationId: null }; */
        info.skipGLJ = skipGLJ;
        ration_glj_facade.getGLJData(info,function (err,datas) {
            if(err){
                result.error=1;
                result.message = err.message;
            }else {
                //多单价字段
                if(req.session.sessionCompilation.priceProperties) datas.priceProperties = req.session.sessionCompilation.priceProperties;
                result.datas = datas;
                result.datas.libData = libData;
            }
            res.json(result);
        });
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
        res.json(result);
    }
}

async function addGLJ(req, res){
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let datas= await ration_glj_facade.addGLJ(data,req.session.sessionCompilation);
        result.data=datas;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async function replaceGLJ(req, res){
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let rdata= await ration_glj_facade.replaceGLJ(data,req.session.sessionCompilation);
        result.data=rdata;
    }catch (err){
        logger.err(err.stack);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async function mReplaceGLJ(req, res){
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let mresult= await ration_glj_facade.mReplaceGLJ(data,req.session.sessionCompilation);
        result.data=mresult;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async  function updateRationGLJByEdit(req, res) {
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let uresult= await ration_glj_facade.updateRationGLJByEdit(data);
        result.data=uresult;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async  function getGLJClass(req, res) {
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let info = await ration_glj_facade.getLibInfo(req);
        let tresult= await ration_glj_facade.getGLJClass(info,data);
        result.data=tresult;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}