/**
 * 编办控制控制器
 *
 * @author CaiAoLin
 * @date 2017/7/28
 * @compilation
 */
import BaseController from "../../common/base/base_controller";
import CompilationModel from "../models/compilation_model";
import STDRationLibMapModel from "../../common/std/std_ration_lib_map_model";
import STDBillLibListsModel from "../../common/std/std_bills_lib_lists_model";
import STDGLJLibMapModel from "../../common/std/std_glj_lib_map_model";
import STDFeeRateLibsModel from "../../common/std/std_fee_rate_libs_model";
import {default as EngineeringConst, List as EngineeringList} from "../../common/const/engineering";
import BillsTemplateModel from "../models/bills_template_model";
import {default as BillsFixedFlagConst, List as BillsFixedFlagList} from "../../common/const/bills_fixed.js";
import {default as BillsTypeFlagConst, List as BillsTypeFlagList} from "../../common/const/bills_type.js";
import EngineeringLibModel from "../models/engineering_lib_model";
import STDLabourCoesModel from "../../common/std/std_labour_coes_model";
import STDCalcProgramModel from "../../common/std/std_calc_program_model";
const billsGuidanceFc = require('../../std_billsGuidance_lib/facade/facades');
import mainColFacade from "../../main_col_lib/facade/main_col_facade";
import billTemplateFacade from "../../bills_template_lib/facade/bills_template_facade";
import projectFeatureFacade from "../../project_feature_lib/facade/project_feature_facade";
import progressiveFacade from "../../progressive_interval_lib/facade/progressive_facade";
import vvTaxFacade from "../../vehicleVessel_lib/facade/vvTax_facade";
import {default as category, List as categoryList} from "../../common/const/category_const.js";
let config = require("../../../config/config.js");
const fs = require('fs');

class CompilationController extends BaseController {

    /**
     * 编办管理控制页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async index(request, response) {
        let id = request.query.id;

        let compilationList = [];
        let selectedCompilation = {};
        try {
            let compilationModel = new CompilationModel();
            compilationList = await compilationModel.getCompilationList();

            if (compilationList.length <= 0) {
                throw '没有数据';
            }
            // 循环查找数据
            for (let tmp of compilationList) {
                if (tmp._id.toString() === id) {
                    selectedCompilation = tmp;
                    break;
                }
            }

            selectedCompilation = Object.keys(selectedCompilation).length <= 0 ? compilationList[0] : selectedCompilation;
            request.session.selectedCompilation = selectedCompilation;

        } catch (error) {
            console.log(error);
        }
        if (selectedCompilation.example && Array.isArray(selectedCompilation.example)) {
            selectedCompilation.example = selectedCompilation.example.join(';');
        }
        let renderData = {
            id: id,
            compilationList: compilationList,
            categoryList: categoryList,
            selectedCompilation: selectedCompilation,
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };

        response.render('users/views/compilation/index', renderData);
    }

    /**
     * 新增计价页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async addValuation(request, response) {
        let name = request.body.name;
        let id = request.body.id;
        let section = request.body.section;

        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            if (id === undefined || id === '') {
                throw '参数错误';
            }

            let insertData = {
                name: name,
            };

            let compilationModel = new CompilationModel();
            let valuationId = await compilationModel.addValuation(id, section, insertData);
            if (!valuationId) {
                throw '新增计价规则失败';
            }
            //添加标准工程专业  2018-08-24 不自动添加标准工程了
            /*let engineeringLibModel = new EngineeringLibModel();
            let stdEngs = await engineeringLibModel.addStdLib(valuationId);
            console.log(stdEngs);*/
        } catch (error) {
            console.log(error);
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    /**
     * 修改计价规则页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async editValuation(request, response) {
        let selectedCompilation = request.session.selectedCompilation;
        let valuationId = request.params.id;
        let section = request.params.section;

        let compilationList = [];
        let engineeringList = [];
        let valuationData = {};
        let valuationList = {};
        try {
            let compilationModel = new CompilationModel();
            compilationList = await compilationModel.getCompilationList();

            // 获取对应的计价规则数据
            [valuationData, valuationList] = await compilationModel.getValuation(selectedCompilation._id, valuationId, section);
            if (Object.keys(valuationData).length <= 0) {
                throw '不存在数据';
            }

            // 获取计价规则中对应的标准库数据
            let engineeringLibModel = new EngineeringLibModel();
            engineeringList = await engineeringLibModel.getLibsByValuationID(valuationId);

        } catch (error) {
            console.log(error);
        }

        let renderData = {
            compilationList: compilationList,
            engineeringList: engineeringList,
            selectedCompilation: selectedCompilation,
            valuationData: valuationData,
            valuationList: valuationList,
            valuationId: valuationId,
            section: section,
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/compilation/add', renderData);
    }

    /**
     * 编辑工程专业页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async editEngineering(request, response) {
        let engineerID = request.params.engineerID;
        let valuationId = request.params.id;
        let section = request.params.section;
        let selectedCompilation = request.session.selectedCompilation;

        let compilationList = [],
            billList = [],
            rationList = [],
            gljList = [],
            feeRateList = [],
            libData = {},
            billsTemplateData = [],
            featureList = [],
            progressiveList = [],
            vvTaxList = [];
        let valuationData = {}, valuationList = {}, artificialCoefficientList = [], calculationList = [], billsGuidanceList = [], mainTreeColList = [];
        let billTemplateList = [];
        try {
            let compilationModel = new CompilationModel();
            compilationList = await compilationModel.getCompilationList();

            // 获取标准清单，不绑定编办
            let stdBillLibListsModel = new STDBillLibListsModel();
            billList = await stdBillLibListsModel.getBillList();

            // 获取定额库
            let stdRationLibMapModel = new STDRationLibMapModel();
            //rationList = await stdRationLibMapModel.getRationLib(selectedCompilation._id);
            rationList = await stdRationLibMapModel.getAllRationLibs();

            // 获取工料机库
            let stdGLJLibMapModel = new STDGLJLibMapModel();
            gljList = await stdGLJLibMapModel.getGLJLibList(selectedCompilation._id);

            // 获取费率标准库
            let stdFeeRateLibsModel = new STDFeeRateLibsModel();
            feeRateList = await stdFeeRateLibsModel.getFeeRateList(selectedCompilation._id);

            // 获取人工系数标准库
            let stdLabourCoesModel = new STDLabourCoesModel();
            artificialCoefficientList = await stdLabourCoesModel.getLabourCoesList();

            // 获取计算程序库
            let stdCalcProgramModel = new STDCalcProgramModel();
            calculationList = await stdCalcProgramModel.getProgramList(selectedCompilation._id);

            //获取列设置库
             mainTreeColList = await mainColFacade.getColLibsByCompilationID(selectedCompilation._id);

             //获取清单模板库
            billTemplateList = await billTemplateFacade.getTemplateLibByCompilationID(selectedCompilation._id);

            // 获取对应的计价规则数据
            [valuationData, valuationList] = await compilationModel.getValuation(selectedCompilation._id, valuationId, section);
            if (Object.keys(valuationData).length <= 0) {
                throw '不存在数据';
            }

            // 获取对应专业工程下的标准库数据
            let engineeringLibModel = new EngineeringLibModel();
            libData = await engineeringLibModel.findDataByCondition({_id:engineerID});

            // 获取清单模板数据
            let billsTemplateModel = new BillsTemplateModel();
            billsTemplateData = await billsTemplateModel.getTemplateData(valuationId, libData.engineering);

            //获取清单指引数据
            billsGuidanceList = await billsGuidanceFc.getBillsGuideLibs({compilationId: selectedCompilation._id, $or: [{deleted: null}, {deleted: false}]});

            //获取工程特征库
            featureList = await projectFeatureFacade.findByCondition({compilationId: selectedCompilation._id},null,false);

            //获取累进区间库
            progressiveList = await progressiveFacade.findByCondition({},null,false);

            //获取车船税库
            vvTaxList = await vvTaxFacade.findByCondition({}, false, false);

        } catch (error) {
            console.log(error);
        }
        //example Array to example String
        if (selectedCompilation.example && Array.isArray(selectedCompilation.example)) {
            selectedCompilation.example = selectedCompilation.example.join(';');
        }
        let renderData = {
            section: section,
            valuationId: valuationId,
            compilationList: compilationList,
            selectedCompilation: selectedCompilation,
            libData: libData,
            billList: JSON.stringify(billList),
            rationList: JSON.stringify(rationList),
            gljList: JSON.stringify(gljList),
            artificialCoefficientList: JSON.stringify(artificialCoefficientList),
            feeRateList: JSON.stringify(feeRateList),
            billsTemplateData: JSON.stringify(billsTemplateData),
            billTemplateList:JSON.stringify(billTemplateList),
            mainTreeColList: JSON.stringify(mainTreeColList),
            gljCol:JSON.stringify(libData.glj_col),
            calculationList: JSON.stringify(calculationList),
            billsGuidanceList: JSON.stringify(billsGuidanceList),
            featureList:JSON.stringify(featureList),
            progressiveList:JSON.stringify(progressiveList),
            vvTaxList: JSON.stringify(vvTaxList),
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/compilation/engineering', renderData);
    }

    /**
     * 保存工程专业标准库
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async saveEngineering(request, response) {
        let engineerId = request.body.id;

        try {
            if (engineerId === '') {
                throw 'id参数错误';
            }

            // 先存入工程专业标准库表
            let engineeringLibModel = new EngineeringLibModel();
            let result = await engineeringLibModel.addLib(engineerId, request.body);

            if (!result) {
                throw '保存失败';
            }

        } catch (error) {
            console.log(error);
        }

        response.redirect(request.headers.referer);
    }

    /**
     * 通过工程专业ID删除工程专业
     * @param request
     * @param response
     * @returns {Promise.<void>}
     */
    async deleteEngineer(request,response){
        let result={
            error:0
        };
        try {
            let data = request.body.data;
            data = JSON.parse(data);
            if(data.id ){
                let engineeringLibModel = new EngineeringLibModel();
                result.data = await engineeringLibModel.deleteById(data.id,true);
            }else {
                throw new Error("提交数据有误");
            }
        }catch (err){
            console.log(err);
            result.error=1;
            result.message = err.message;
        }
        response.json(result);
    }

    /**
     * 修改保存工程专业信息-用于异步操作
     * @param request
     * @param response
     * @returns {Promise.<void>}
     */
    async updateEngineer(request,response){
        let result={
            error:0
        };
        try {
            let data = request.body.data;
            data = JSON.parse(data);
            if(data.id && data.updateData){
                let engineeringLibModel = new EngineeringLibModel();
                result.data = await engineeringLibModel.updateById(data.id,data.updateData);
            }else {
                throw new Error("提交数据有误");
            }

        }catch (err){
            console.log(err);
            result.error=1;
            result.message = err.message;
        }
        response.json(result);
    }

    /**
     * 保存计价规则
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async saveValuation(request, response) {
        let valuationId = request.body.id;
        try {
            if (valuationId === '') {
                throw 'id参数错误';
            }

            let compilationModel = new CompilationModel();
            let result = await compilationModel.saveValuation(valuationId, request.body);
            if (!result) {
                throw '保存失败';
            }

        } catch (error) {
            console.log(error);
        }

        response.redirect(request.headers.referer);
    }

    /**
     * 删除计价规则
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async deleteValuation(request, response) {
        let id = request.params.id;
        let section = request.params.section;
        let selectedCompilation = request.session.selectedCompilation;

        try {
            if (id === undefined || id === '' || section === undefined || section === '') {
                throw '参数错误';
            }

            //先删除对应的工程专业
            let engineeringLibModel = new EngineeringLibModel();
            await engineeringLibModel.deleteByValuationID(id);

            //删除计价规则
            let compilationModel = new CompilationModel();
            let result = compilationModel.deleteValuation(selectedCompilation._id, id, section);
            if (!result) {
                throw '删除失败';
            }

        } catch (error) {
            console.log(error);
        }

        response.redirect(request.headers.referer);
    }

    /**
     * 快速切换启用/禁用
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async enableSwitch(request, response) {
        let id = request.body.id;
        let section = request.params.section;
        let enable = request.body.enable;

        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            let compilationModel = new CompilationModel();
            let result = await compilationModel.switchEnable(id, section, enable);

            if (!result) {
                throw '新增编办失败';
            }
        } catch (error) {
            console.log(error);
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    /**
     * 发布/取消编办
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async release(request, response) {
        let id = request.body.id;
        let release = request.body.status;
        release = parseInt(release);

        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            let compilationModel = new CompilationModel();
            let result = await compilationModel.release(id, release);

            if (!result) {
                throw '发布编办失败';
            }
        } catch (error) {
            console.log(error);
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    /**
     * 新增编办操作
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async addCompilation(request, response) {
        let name = request.body.name;
        let responseData = {
            err: 0,
            msg: ''
        };
        try {
            let sessionManager = request.session.managerData;
            let insertData = {
                name: name,
                creator: sessionManager.userID
            };

            let compilationModel = new CompilationModel();
            let result = await compilationModel.add(insertData);

            if (!result) {
                throw '新增编办失败';
            }
        } catch (error) {
            console.log(error);
            responseData.err = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

    async setDescription(request, response){
        let compilationId = request.body.id;
        let description = request.body.description;
        try{
            let compilationModel = new CompilationModel();
            await compilationModel.setDescription(compilationId, description);
            response.json({err: 0, msg: '', data: null});
        }
        catch (err){
            response.json({err: 1, msg: err, data: null});
        }
    }
    async setOverWriteUrl(request, response){
        let compilationId = request.body.id;
        let overWriteUrl = request.body.overWriteUrl;
        try{
            let compilationModel = new CompilationModel();
            //绝对路径
            let absoluteUrl = request.app.locals.rootDir + overWriteUrl;
            //文件是否存在
            let fileExists = fs.existsSync(absoluteUrl);
            let pricePropertiesTemplate = [],
                consumeAmtPropertiesTemplate = [];
            if(fileExists && fs.statSync(absoluteUrl).isFile()){
                //读取配置文件并赋值
                let overWriteExports = require(absoluteUrl);
                if(overWriteExports){
                    pricePropertiesTemplate = overWriteExports.pricePropertiesTemplate ? overWriteExports.pricePropertiesTemplate : [];
                    consumeAmtPropertiesTemplate = overWriteExports.consumeAmtPropertiesTemplate ? overWriteExports.consumeAmtPropertiesTemplate : [];
                }
            }
            await compilationModel.setOverWriteUrl(compilationId, overWriteUrl, pricePropertiesTemplate, consumeAmtPropertiesTemplate);
            response.json({err: 0, msg: '', data: null});
        }
        catch (err){
            console.log(err);
            response.json({err: 1, msg: err, data: null});
        }
    }
    async setExample(request, response){
        let compilationId = request.body.id,
            example = request.body.example;
        try {
            let compilationModel = new CompilationModel();
            await compilationModel.setExample(compilationId, example);
            response.json({err: 0, msg: 'success', data: null});
        }
        catch (err){
            console.log(err);
            response.json({err: 1, msg: err, data: null});
        }
    }

    /**
     * 模板设置页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async billsTemplate(request, response) {
        let billList = {};
        let valuationList = {};
        let valuationData = {};
        let compilationList = [];
        let billsTemplateData = [];

        let selectedCompilation = request.session.selectedCompilation;
        let engineering = request.params.engineering;
        let valuationId = request.params.id;
        let section = request.params.section;

        try {
            let compilationModel = new CompilationModel;
            // 获取对应的计价规则数据
            [valuationData, valuationList] = await compilationModel.getValuation(selectedCompilation._id, valuationId, section);
            compilationList = await compilationModel.getCompilationList();

            // 获取标准清单
            let stdBillLibListsModel = new STDBillLibListsModel();
            billList = await stdBillLibListsModel.getBillList(selectedCompilation._id);

            // 获取清单模板数据
            let billsTemplateModel = new BillsTemplateModel();
            billsTemplateData = await billsTemplateModel.getTemplateData(valuationId, engineering);
        } catch (error) {
            console.log(error);
        }

        let renderData = {
            engineering: engineering,
            billList: JSON.stringify(billList),
            billsTemplateData: JSON.stringify(billsTemplateData),
            billsFixedFlagList: JSON.stringify(BillsFixedFlagList),
            billsTypeFlagList: JSON.stringify(BillsTypeFlagList),
            valuationData: valuationData,
            valuationList: valuationList,
            selectedCompilation: selectedCompilation,
            compilationList: compilationList,
            valuationId: valuationId,
            section: section,
            layout: 'users/views/layout/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/compilation/template', renderData);
    }

    /**
     * 清单模板，更新数据操作
     *
     * @param request
     * @param response
     */
    async updateBillsTemplate(request, response) {
        let engineering = request.params.engineering;
        let valuationId = request.params.id;
        let section = request.params.section;
        let data = JSON.parse(request.body.data);

        let billsTemplateModel = new BillsTemplateModel();
        let result = await billsTemplateModel.updateTemplate(valuationId, engineering, data);

        if (result) {
            response.json({error: 0, message: '', data: data});
        } else {
            response.json({error: 1, message: '更新数据错误', data: null});
        }
    }

    async addEngineer(request,response){
        let engineeringLibModel = new EngineeringLibModel();
        try {
            await engineeringLibModel.addEngineer(request.body);
        }catch (error) {
            console.log(error);
        }
        response.redirect(request.headers.referer);
    }

    /**
     * 更改编办所属办事处信息
     *
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async changeCategory(request, response) {
        let valuationId = request.body.id;
        let category = request.body.category;
        category = parseInt(category);
        try {
            let compilationModel = new CompilationModel();
            let result = await compilationModel.updateCategory(valuationId, category);
            if (result) {
                response.json({error: 0, message: '', data: null});
            } else {
                response.json({error: 1, message: '更新数据错误', data: null});
            }
        } catch(error) {
            response.json({error: 1, message: '更新数据错误', data: null});
        }
    }

}

export default CompilationController;