'use strict';

/**
 *
 *
 * @author Mai
 * @date
 * @version
 */

const officeList = require('../const/cld_office').list;
const settingConst = require('../const/setting.js');
const settingMenu = require('../../config/menu').settingMenu;

module.exports = app => {

    class SettingController extends app.BaseController {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局context
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            ctx.subMenu = settingMenu;
        }

        /**
         * 项目信息页面(Get)
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async info(ctx) {
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionProject.id;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }

                // 获取销售人员数据
                const salesmanData = await ctx.service.manager.getDataById(projectData.manager_id);

                // 数据规则
                const rule = ctx.service.project.rule('saveInfo');
                const jsValidator = await this.jsValidator.convert(rule).build();
                const officeName = officeList[salesmanData.office];
                const date = new Date(projectData.create_time * 1000);// 如果date为10位不需要乘1000
                const Y = date.getFullYear() + '-';
                const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
                const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
                const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
                const s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
                const dateStr = Y + M + D + h + m + s;
                const renderData = {
                    projectData,
                    salesmanData,
                    officeName,
                    officeList,
                    jsValidator,
                    dateStr,
                };
                await this.layout('setting/info.ejs', renderData);
            } catch (error) {
                console.log(error);
                ctx.redirect('/dashboard');
            }
        }

        /**
         * 项目设置 -- 账号设置(Get)
         * @param ctx
         * @return {Promise<void>}
         */
        async user(ctx) {
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionProject.id;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }

                const renderData = {
                    projectData,
                };
                await this.layout('setting/user.ejs', renderData, 'setting/user_modal.ejs');
            } catch (error) {
                console.log(error);
                ctx.redirect('/dashboard');
            }
        }

        /**
         * 项目设置 -- 自定义标段分类(Get)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async category(ctx) {
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionProject.id;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }

                const categoryData = await ctx.service.category.getAllCategory(projectId);
                const tenderData = await ctx.service.tender.getList();
                const renderData = {
                    projectData,
                    categoryType: settingConst.cType,
                    categoryData,
                    tenderData,
                };
                await this.layout('setting/category.ejs', renderData, 'setting/category_modal.ejs');
            } catch (error) {
                console.log(error);
                ctx.redirect('/dashboard');
            }
        }

        /**
         * 新增分类(Ajax)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async addCategory(ctx) {
            try {
                const projectId = ctx.session.sessionProject.id;
                const responseData = {
                    err: 0, msg: '', data: null,
                };

                const data = JSON.parse(ctx.request.body.data);
                if (!data.name || !data.type) {
                    throw '提交数据错误';
                }

                responseData.data = await ctx.service.category.addCategory(projectId, data.name, data.type);
                ctx.body = responseData;
            } catch (err) {
                this.log(err);
                ctx.body = { err: 1, msg: err.toString(), data: null };
            }
        }

        /**
         * 编辑分类(Ajax)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async updateCategory(ctx) {
            try {
                const projectId = ctx.session.sessionProject.id;
                const responseData = { err: 0, msg: '', data: null };

                const data = JSON.parse(ctx.request.body.data);
                if (!data.id) {
                    throw '提交数据错误';
                }
                if (data.name) {
                    const count = await ctx.service.category.count({ pid: projectId, name: data.name });
                    if (count >= 1) {
                        throw '存在同名类别';
                    }
                }

                const result = await ctx.service.category.update(data, { id: data.id });
                if (!result) {
                    throw '提交数据失败';
                }

                responseData.data = await ctx.service.category.getCategory(data.id);

                ctx.body = responseData;
            } catch (err) {
                this.log(err);
                ctx.body = { err: 1, msg: err.toString(), data: null };
            }
        }

        async setCategoryValue(ctx) {
            try {
                const responseData = { err: 0, msg: '', data: {} };

                const data = JSON.parse(ctx.request.body.data);
                if (!data.id) {
                    throw '提交数据错误';
                }
                await ctx.service.categoryValue.setCategoryValue(data.id, data.updateValue);

                responseData.data.category = await ctx.service.category.getCategory(data.id);
                responseData.data.tenders = await ctx.service.tender.getList();

                ctx.body = responseData;
            } catch (err) {
                this.log(err);
                ctx.body = { err: 1, msg: err instanceof String ? err : '提交数据失败', data: null };
            }
        }

        /**
         * 删除分类(Ajax)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async deleteCategory(ctx) {
            try {
                const projectId = ctx.session.sessionProject.id;
                const responseData = {
                    err: 0, msg: '', data: null,
                };

                const data = JSON.parse(ctx.request.body.data);
                if (!data.id) {
                    throw '提交数据错误';
                }

                await ctx.service.category.deleteCategory(projectId, data.id);

                ctx.body = responseData;
            } catch (err) {
                this.log(err);
                ctx.body = { err: 1, msg: err.toString(), data: null };
            }
        }

        /**
         * 调整分类层次排序(Ajax)
         *
         * @param ctx
         * @return {Promise<void>}
         */
        async resetCategoryLevel(ctx) {
            try {
                const projectId = ctx.session.sessionProject.id;
                const responseData = {
                    err: 0, msg: '', data: null,
                };
                const data = JSON.parse(ctx.request.body.data);

                await ctx.service.category.resetCategoryLevel(data);
                responseData.data = await ctx.service.category.getAllCategory(projectId);
                ctx.body = responseData;
            } catch (err) {
                this.log(err);
                ctx.body = { err: 1, msg: err.toString(), data: null };
            }
        }

        /** update porject info
         * @author wangfeng
         * @date 2018-10-12 15:48:05
         * @param ctx
         * @return {Promise<void>}
         */
        async updateinfo(ctx) {
            try {
                const projectId = ctx.params.id;
                const responseData = {
                    err: 0, msg: '', data: null,
                };
                const conditionData = {
                    id: projectId,
                };
                const data = ctx.request.body;
                const result = await ctx.service.project.update(data, conditionData);
                if (!result) {
                    throw '提交数据失败';
                }

                ctx.redirect('/setting/info');
            } catch (err) {
                this.log(err);
                ctx.body = { err: 1, msg: err.toString(), data: null };
            }
        }
    }

    return SettingController;
};
