/**
 * Created by zhang on 2018/9/3.
 */
import BaseController from "../../common/base/base_controller";
import monomerTemplateFacade from "../facade/monomer_template_facade";
import { checkCompilationPermission } from '../../common/base/base_util';
let config = require("../../../config/config.js");
let logger = require('../../../logs/log_helper').logger;
import CompilationModel from '../../users/models/compilation_model';
let mongoose = require('mongoose');
let monomerTemplateModel = mongoose.model('std_monomer_template');

class MonomerTemplateController extends BaseController {
    async main(request, response) {

        let compilationModel = new CompilationModel();
        let compilationList = await compilationModel.getPermissionCompilationList(request, { _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 filter = request.query.filter ? { compilationID: request.query.filter } : {};
        let templateLibs = await monomerTemplateFacade.findByCondition(filter, { feature: 0 }, false);
        const compilationPermission = request.session.managerData.compilationPermission || [];
        templateLibs = templateLibs.filter(lib => compilationPermission.includes(lib.compilationID))
        let renderData = {
            title: '单体模板库',
            userAccount: request.session.managerData.username,
            userID: request.session.managerData.userID,
            templateLibs: templateLibs,
            compilationList: compilationList,
            layout: 'maintain/common/html/layout'
        };
        response.render("maintain/monomer_template_lib/html/main", renderData);
    }
    async addLib(request, response) {
        try {
            await monomerTemplateFacade.addLib(request.body);
        } catch (error) {
            console.log(error);
        }
        response.redirect(request.headers.referer);
    }
    async findLib(request, response) {
        let result = {
            error: 0
        };
        try {
            let data = request.body.data;
            data = JSON.parse(data);
            let conditions = { 'ID': data.ID };
            let resultData = await monomerTemplateFacade.findByCondition(conditions);
            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);
            console.log(data.data);
            let resultData = await monomerTemplateFacade.saveLib(data);
            result.data = resultData;
        } catch (err) {
            console.log(err);
            result.error = 1;
            result.message = err.message;
        }
        response.json(result);
    }
    async deleteLibByID(request, response) {
        logger.info(`delete projectFeatureLib ${request.ip}`);
        let result = {
            error: 0
        };
        try {
            let data = request.body.data;
            data = JSON.parse(data);
            let resultData = await monomerTemplateFacade.deleteLibByID(data.ID);
            result.data = resultData;
        } catch (err) {
            console.log(err);
            result.error = 1;
            result.message = err.message;
        }
        response.json(result);
    }
    async edit(request, response) {
        //先取出替换库信息：
        let libID = request.params.libID;

        let monomerTemplate = await monomerTemplateFacade.findByCondition({ 'ID': libID });

        if (monomerTemplate) {
            checkCompilationPermission(request, response, monomerTemplate.compilationID, '/monomerTemplate/main');
            let randerData = {
                title: '单体模板库',
                mainURL: '/monomerTemplate/main',
                libName: monomerTemplate.name,
                userAccount: request.session.managerData.username,
                userID: request.session.managerData.userID,
                templateLibs: JSON.stringify(monomerTemplate),
                libID: libID,
                LicenseKey: config.getLicenseKey(process.env.NODE_ENV),
                layout: 'maintain/common/html/edit_layout'
            };
            response.render("maintain/monomer_template_lib/html/edit", randerData);
        } else {
            response.redirect(request.headers.referer);
        }
    }
}
export default MonomerTemplateController;