/**
 * Created by zhang on 2019/12/31.
 */
import BaseController from "../../common/base/base_controller";
let mongoose = require("mongoose");
let systemSettingModel = mongoose.model("system_setting");
const uuidV1 = require('uuid/v1');
let config = require("../../../config/config.js");
const company = '珠海纵横创新软件有限公司';
const product = '大司空云计价';

class SystemController extends BaseController {
    async index(request, response) {
        let setting = await systemSettingModel.findOne({});
        if (!setting) {
            setting = { 
                professional: { project: 100, ration: 2000 },
                normal: { project: 50, ration: 1000 },
                company,
                product,
                version: ''
            };
        }
        if (!setting.company) {
            setting.company = company;
        }
        if (!setting.product) {
            setting.product = product;
        }

        // 渲染数据
        let renderData = {
            layout: 'users/views/layout/layout',
            LicenseKey: config.getLicenseKey(process.env.NODE_ENV),
            setting: setting,
            superAdmin: request.session.managerData.superAdmin
        };
        response.render('users/views/system/index', renderData);
    }

    async save(request, response) {
        let data = request.body;
        const superAdmin = request.session.managerData.superAdmin;
        let setting = {
            professional: {
                project: data.professional_project,
                ration: data.professional_ration
            },
            normal: {
                project: data.normal_project,
                ration: data.normal_ration
            }
        };
        // 超级管理员才能修改
        if (superAdmin === 1) {
            setting.company = data.company;
            setting.product = data.product;
            setting.version = data.version;
        }
        if (!data.ID || data.ID == "") {
            setting.ID = uuidV1();
            await systemSettingModel.create(setting);
        } else {
            await systemSettingModel.update({ ID: data.ID }, setting);
        }
        response.redirect(request.headers.referer);
    }

}

export default SystemController;