'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;
const accountGroup = require('../const/account_group').group;
const permission = require('../const/account_permission').permission;

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 '没有对应的项目数据';
                }
                if (ctx.session.sessionUser.is_admin === 0) {
                    throw '没有访问权限';
                }

                // 获取数据规则
                // const rule = ctx.service.projectAccount.rule('updateUser');
                // const frontRule = ctx.helper.validateConvert(rule);

                // 获取项目用户列表
                const accountData = await ctx.service.projectAccount.getAllDataByCondition({
                    where: { project_id: projectId },
                    columns: ['id', 'account', 'name', 'company', 'role', 'mobile', 'telephone', 'enable', 'is_admin', 'account_group'],
                });

                const renderData = {
                    projectData,
                    accountData,
                    accountGroup,
                    permission,
                    // rule: JSON.stringify(frontRule),
                };
                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 userPermissionSet(ctx) {
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionProject.id;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }
                if (ctx.session.sessionUser.is_admin === 0) {
                    throw '没有访问权限';
                }

                // 获取数据规则
                // const rule = ctx.service.projectAccount.rule('updateUser');
                // const frontRule = ctx.helper.validateConvert(rule);

                // 获取项目用户列表
                const accountData = await ctx.service.projectAccount.getAllDataByCondition({
                    where: { project_id: projectId },
                    columns: ['id', 'account', 'name', 'company', 'role', 'is_admin', 'account_group', 'permission', 'cooperation'],
                });

                const renderData = {
                    projectData,
                    accountData,
                    accountGroup,
                    permission,
                    // rule: JSON.stringify(frontRule),
                };
                await this.layout('setting/user_permission.ejs', renderData, 'setting/user_permission_modal.ejs');
            } catch (error) {
                console.log(error);
                ctx.redirect('/dashboard');
            }
        }

        /**
         * 项目设置 -- 账号启用和停用设置(Post)
         * @param ctx
         * @return {Promise<void>}
         */
        async userSwitch(ctx) {
            const responseData = {
                err: 0, msg: '', data: null,
            };
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionProject.id;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }
                if (ctx.session.sessionUser.is_admin === 0) {
                    throw '没有访问权限';
                }
                const data = JSON.parse(ctx.request.body.data);
                const result = await ctx.service.projectAccount.update(data, { id: data.id });
                if (!result) {
                    throw '提交数据失败';
                }
            } catch (err) {
                this.log(err);
                responseData.err = 1;
                responseData.msg = err;
            }
            ctx.body = responseData;
        }

        /**
         * 项目设置 -- 账号添加(Post)
         * @param ctx
         * @return {Promise<void>}
         */
        async addUser(ctx) {
            const projectData = ctx.session.sessionProject;
            try {
                // 验证数据
                if (projectData.id === undefined) {
                    throw '不存在对应的项目数据';
                }

                // 获取验证规则
                const rule = ctx.service.projectAccount.rule('add');
                ctx.validate(rule);

                const result = await ctx.service.projectAccount.save(ctx.request.body);
                if (!result) {
                    throw '保存账号数据失败';
                }

                this.setMessage('保存账号数据成功', this.messageType.SUCCESS);
                ctx.redirect('/' + ctx.controllerName + '/user');
            } catch (error) {
                console.log(error);
                this.setMessage(error.toString(), this.messageType.ERROR);
                ctx.redirect(ctx.request.headers.referer);
            }
        }

        /**
         * 项目设置 -- 账号编辑(Post)
         * @param ctx
         * @return {Promise<void>}
         */
        async updateUser(ctx) {
            const projectData = ctx.session.sessionProject;
            try {
                // 验证数据
                if (projectData.id === undefined) {
                    throw '不存在对应的项目数据';
                }

                // 获取验证规则
                const rule = ctx.service.projectAccount.rule('modify');
                ctx.validate(rule);

                const result = await ctx.service.projectAccount.save(ctx.request.body);
                if (!result) {
                    throw '保存账号数据失败';
                }

                this.setMessage('保存账号数据成功', this.messageType.SUCCESS);
                ctx.redirect('/' + ctx.controllerName + '/user');
            } catch (error) {
                console.log(error);
                this.setMessage(error.toString(), this.messageType.ERROR);
                ctx.redirect(ctx.request.headers.referer);
            }
        }

        async resetUserPassword(ctx) {
            const response = {
                err: 0,
                msg: '',
            };
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionProject.id;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }
                if (ctx.session.sessionUser.is_admin === 0) {
                    throw '没有访问权限';
                }

                const accountId = parseInt(ctx.request.body.id);
                let password = ctx.request.body.reset_password;
                password = password.toString();
                if (isNaN(accountId) || accountId <= 0 || password.length < 6) {
                    throw '参数错误';
                }
                const result = await ctx.service.projectAccount.resetPassword(accountId, password);
                if (!result) {
                    throw '重置密码失败!';
                }
            } catch (error) {
                response.err = 1;
                response.msg = error;
            }

            ctx.body = response;
        }

        /**
         * 项目设置 -- 账号权限编辑(Post)
         * @param ctx
         * @return {Promise<void>}
         */
        async permission(ctx) {
            const projectData = ctx.session.sessionProject;
            try {
                // 验证数据
                if (projectData.id === undefined) {
                    throw '不存在对应的项目数据';
                }

                const accountId = parseInt(ctx.request.body.id);
                const accountInfo = await ctx.service.projectAccount.getDataById(accountId);
                if (accountInfo === null) {
                    throw '不存在该客户';
                }

                const result = await ctx.service.projectAccount.permissionSave(accountId, ctx.request.body);
                if (!result) {
                    throw '修改权限失败!';
                }

                this.setMessage('保存账号数据成功', this.messageType.SUCCESS);
                ctx.redirect('/' + ctx.controllerName + '/user/permission/set');
            } catch (error) {
                console.log(error);
                this.setMessage(error.toString(), this.messageType.ERROR);
                ctx.redirect(ctx.request.headers.referer);
            }
        }

        /**
         * 项目设置 -- 自定义标段分类(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 '没有对应的项目数据';
                }
                if (ctx.session.sessionUser.is_admin === 0) {
                    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 };
            }
        }

        /**
         * 检测账户是否存在
         *
         * @param {Object} ctx -egg全局变量
         * @return {void}
         */
        async accountExist(ctx) {
            const projectData = ctx.session.sessionProject;
            const responseData = {
                err: 0, msg: '', data: null,
            };
            try {
                const data = JSON.parse(ctx.request.body.data);
                const account = data.account;
                if (projectData.id === undefined) {
                    throw '不存在对应项目';
                }
                responseData.data = await ctx.service.projectAccount.isAccountExist(account, projectData.id);
                ctx.body = responseData;
            } catch (error) {
                ctx.body = { err: 1, msg: error.toString(), data: null };
            }
        }
    }

    return SettingController;
};
