'use strict';

/**
 * CLD接口相关控制器
 *
 * @author EllisRan.
 * @date 2018/9/25
 * @version
 */

import CLDModel from "../models/cld_model";
import UserModel from "../models/user_model"
import CompilationModel from "../models/compilation_model";

class CLDController {

    /**
     * 获取cld办事处人员信息
     *
     * @param request
     * @param reponse
     * @return {Promise.<void>}
     */
    async getCategoryStaff(request, response) {
        const zongBuCategoryID = 12;
        let category = request.query.category;
        if (!category || category == -1) {
            category = request.session.sessionCompilation && request.session.sessionCompilation.categoryID ? request.session.sessionCompilation.categoryID : zongBuCategoryID;
            console.log(category);
        }
        try {
            let cldModel = new CLDModel();
            let result = await cldModel.getCategoryStaff(category);
            response.json({error: 0, msg: 'success', data: JSON.parse(result)});
        } catch (err) {
            response.json({error: 1, msg: err});
        }
    }

    /**
     * cld 获取建筑用户和编办接口
     *
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async getUsersAndCompilationList(request, response) {
        let mobile = request.query.mobile;
        let ssoID = request.query.ssoID;
        try {
            //获取用户信息
            if (mobile === undefined && ssoID === undefined) {
                throw '传参有误';
            }
            let userModel = new UserModel();
            let userData = '';
            if (mobile !== undefined) {
                userData = await userModel.findDataByMobile(mobile);
            } else {
                userData = await userModel.findDataBySsoId(ssoID);
            }
            if (userData === null || userData === '') {
                throw '不存在该建筑用户';
            }
            userData = JSON.parse(JSON.stringify(userData));

            userData.company_scale = userData.company_scale === null || userData.company_scale === undefined ? '' : userModel.companyScale[userData.company_scale] + '人';
            userData.company_type = userData.company_type === null || userData.company_type === undefined ? '' : userModel.companyType[userData.company_type];
            userData.province = userModel.province[userData.province];

            let date = new Date(userData.create_time);
            userData.create_time = date.getFullYear() + '年' +
                (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '月' +
                (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日';

            //获取编办列表
            let compilationModel = new CompilationModel();
            let compilationList = JSON.parse(JSON.stringify(await compilationModel.getList()));
            if (userData.upgrade_list !== undefined) {
                let userUpgradeList = userData.upgrade_list;
                for (let i in userUpgradeList) {
                    let oneCompilationIndex = await compilationList.findIndex(function (item) {
                        return item._id === userUpgradeList[i].compilationID;
                    });
                    if (oneCompilationIndex !== -1) {
                        compilationList[oneCompilationIndex].isUpgrade = userUpgradeList[i].isUpgrade;
                    }
                }
            }
            response.json({error: 0, msg: 'success', data: { userInfo: userData, compilationList: compilationList }});
        } catch (err) {
            response.json({error: 1, msg: err});
        }
    }

    /**
     * 设置用户编办专业版
     *
     * @param request
     * @param response
     * @return {Promise.<void>}
     */
    async setUsersUpgrade(request, response) {
        let ssoID = request.body.ssoId;
        let compilationID = request.body.cid;
        try {

            let userModel = new UserModel();

            let userData = await userModel.findDataBySsoId(ssoID);

            let compilationModel = new CompilationModel();

            let compilationData = compilationModel.getCompilationById(compilationID);

            if (compilationData === null || compilationData === undefined) {
                throw '不存在该编办或者编办未发布';
            }

            let upgrade_list = userData.upgrade_list !== undefined ? JSON.parse(JSON.stringify(userData.upgrade_list)) : [];

            let upgradeIndex = upgrade_list.findIndex(function (item) {
                return item.compilationID === compilationID
            });

            let upgradeInfo = {
                compilationID:compilationID,//编办ID
                upgrade_time:new Date().getTime(),
                isUpgrade:true,
                remark: ''
            };

            if (upgradeIndex === -1) {
                upgrade_list.push(upgradeInfo);
            } else {
                upgrade_list.splice(upgradeIndex, 1, upgradeInfo);
            }

            let condition = {ssoId: ssoID};
            let result = await userModel.updateUser(condition, {upgrade_list: upgrade_list});

            if (result) {
                response.json({error: 0, msg: 'success'});
            } else {
                throw '更新失败';
            }
        } catch (err) {
            response.json({error: 1, msg: err});
        }
    }
}

export default CLDController;