/**
 * 清单模板控制控制器
 *
 * @author CaiAoLin
 * @date 2017/7/28
 * @compilation
 */
import BaseController from "../../common/base/base_controller";
import CompilationModel from '../../users/models/compilation_model';
import billsTemplateFacade from "../facade/bills_template_facade";
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";
let config = require("../../../config/config.js");

class BillsTemplateController extends BaseController {

    /**
     * 清单模板库页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async main(request, response) {
        let filter = request.query.filter ? {compilationId: request.query.filter} : null;
        let templateLibs = await billsTemplateFacade.getAllLibs(filter);
        let compilationModel = new CompilationModel();
        let compilationList = await compilationModel.getCompilationList({_id: 1, name: 1});
        compilationList.unshift({_id: 'all', name: '所有'});
        let activeCompilation = compilationList.find(compilation => compilation._id.toString() === request.query.filter);
        if (activeCompilation) {
            activeCompilation.active = 'active';
        } else {
            compilationList[0].active = 'active'
        }
        let randerData = {
            title:'清单模板',
            userAccount: request.session.managerData.username,
            userID: request.session.managerData.userID,
            templateLibs:templateLibs,
            compilationList: compilationList,
            layout: 'maintain/common/html/layout',
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };

        response.render("maintain/bill_template_lib/html/main", randerData);
    }
    async updateBillsTemplateItem(request, response) {
        let libID = request.params.libID;
        let result = {error: 1, message: '更新数据错误', data: null};
        try {
            let data = JSON.parse(request.body.data);
            if(libID){
                 result = await await billsTemplateFacade.updateTemplateItem(libID,data);
                if (result) {
                    result = {error: 0, message: '', data: data};
                }
            }

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

    async editTemplate(request, response){

        //先取出清单库信息：
        let libID = request.params.libID;
        let templateLib = await billsTemplateFacade.getLibByID(libID);
        if(templateLib){

            let templateDatas = await billsTemplateFacade.getTemplateDatasByLibID(libID);

            let randerData = {
                title:'清单模板',
                mainURL:'/billsTemplate/main',
                libName:templateLib.name,
                userAccount: request.session.managerData.username,
                userID: request.session.managerData.userID,
                billsTemplateData:JSON.stringify(templateDatas),
                billsFixedFlagList: JSON.stringify(BillsFixedFlagList),
                billsTypeFlagList: JSON.stringify(BillsTypeFlagList),
                libID:libID,
                LicenseKey:config.getLicenseKey(process.env.NODE_ENV),
                layout: 'maintain/common/html/edit_layout'
            };
            response.render("maintain/bill_template_lib/html/edit", randerData);
        }else {
            response.redirect(request.headers.referer);
        }
    }

    async deleteLibByID(request,response){
        let result={
            error:0
        };
        try {
            let data = request.body.data;
            data = JSON.parse(data);
            let resultData= await billsTemplateFacade.deleteLibByID(data.ID);
            result.data=resultData;
        }catch (err){
            console.log(err);
            result.error=1;
            result.message = err.message;
        }
        response.json(result);
    }

    async saveLib(request, response){
        let result={
            error:0
        };
        try {
            let data = request.body.data;
            data = JSON.parse(data);
            let resultData= await billsTemplateFacade.saveLib(data);
            result.data=resultData;
        }catch (err){
            console.log(err);
            result.error=1;
            result.message = err.message;
        }
        response.json(result);
    }

    async getLibByID(request, response){
        let result={
            error:0
        };
        try {
            let data = request.body.data;
            data = JSON.parse(data);
            let resultData= await billsTemplateFacade.getLibByID(data.libID);
            result.data=resultData;
        }catch (err){
            console.log(err);
            result.error=1;
            result.message = err.message;
        }
        response.json(result);
    }

    async addLib(request, response){
        try {
            await billsTemplateFacade.addLib(request.body);
        }catch (error) {
            console.log(error);
        }
        response.redirect(request.headers.referer);
    }

    async copyLib(req, res) {
        try {
            const data = JSON.parse(req.body.data);
            const userName = req.session.managerData.username;
            await billsTemplateFacade.copyLib(data.libID, data.name, userName);
            res.json({error: 0, data: null, message: 'success'})
        } catch (err) {
            console.log(err);
            res.json({error: 1, data: null, message: 'fail'});
        }
    }
}

export default BillsTemplateController;