/**
 * Created by zhang on 2020/2/14.
 */
import BaseController from "../../common/base/base_controller";
import CompilationModel from "../models/compilation_model";
let config = require("../../../config/config.js");
let mongoose = require("mongoose");
let welcomeSettingModel = mongoose.model("welcome_setting");
const uuidV1 = require('uuid/v1');

class WelcomeController extends BaseController {
    async index(request, response) {
        let id = request.query.id;
        let type = request.query.type;
        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 welcome_setting =await welcomeSettingModel.findOne({compilationId:selectedCompilation._id.toString()});
        let setting = null;
        let settingID="";
        if(welcome_setting){
          setting = type== "professional"?welcome_setting.professional:welcome_setting.normal;
          settingID = welcome_setting.ID;
        }
        if(!setting) setting = {showType:0,context:""};
        console.log(setting)
        let renderData = {
            id: id,
            type:type,
            settingID:settingID,
            compilationList: compilationList,
            selectedCompilation: selectedCompilation,
            layout: 'users/views/layout/layout',
            setting:setting,
            LicenseKey:config.getLicenseKey(process.env.NODE_ENV)
        };
        response.render('users/views/welcome/index', renderData);
    }

    async save(request, response){
        let data = request.body;
        let setting = {compilationId:data.compilationId};
        let type = data.type;
        let info = {showType:data.showType,context:data.context}
        type == "professional"?setting.professional = info:setting.normal = info
        if(!data.ID || data.ID == ""){
            setting.ID = uuidV1();
            await welcomeSettingModel.create(setting);
        } else {
            await welcomeSettingModel.update({ID:data.ID},setting);
        }
        response.redirect(request.headers.referer);
    }
}

export default WelcomeController;