/**
 * 孵化器用户逻辑层 
 * 作者: 陈金晶
 * 主要包括有 孵化器账号的登录 
 * 预留好  重置密码  退出登录 接口  
 */
import { FuHuaQiUserConfig } from "../../config/checkParamConfig";
import { ERRORENUM } from "../../config/errorEnum";
import { FuHuaQiListConfig } from "../../config/ojbectResultKeyConfig";
import * as fuhuaqiData from "../../data/fuHuaQi/fuhuaqi"
import { BizError } from "../../util/bizError";
import { checkChange, checkParamater, extractData, getPwdMd5, getToken } from "../../util/tools";


/**
 * 小程序的孵化器登录
 * 小程序端
 * @param uscc 信用代码
 * @param pwd 密码
 * @returns fuhuaqiUserInfo:{uscc, name} 登录后的信息
 */
export async function login(uscc:string, pwd:string) {
    let fuhuaqiInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    if(!fuhuaqiInfo) throw new BizError(ERRORENUM.账号不存在);

    let checkPwd = getPwdMd5(fuhuaqiInfo.uscc, pwd);
    if (fuhuaqiInfo.pwd != checkPwd) throw new BizError(ERRORENUM.密码错误);

    const Token = getToken(uscc);
    
    let fuhuaqiUserInfo = {
        uscc: fuhuaqiInfo.uscc,
        // name: fuhuaqiInfo.name,
        firstLogin : !fuhuaqiInfo.firstLoginIsChangePwd,
        token:Token
    };

    fuhuaqiInfo.token = Token;
    fuhuaqiInfo.tokenMs = new Date().valueOf();

    await fuhuaqiInfo.save();
    
    return fuhuaqiUserInfo;
}


/**
 * 首次登录修改密码
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param pwd 新密码
 * @param confirmPwd 确认密码 
 * @returns 
 */
export async function firstLoginChangePwd(uscc:string, pwd:string, confirmPwd:string ) {
    let dataBaseInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    if (dataBaseInfo.firstLoginIsChangePwd) throw new BizError(ERRORENUM.不能重复修改密码, `重复调用了首次登录之后的修改密码接口${uscc}`);
    //todo 校验密码
    dataBaseInfo.pwd = getPwdMd5(uscc, pwd);
    dataBaseInfo.firstLoginIsChangePwd = true;
    await dataBaseInfo.save();

    return {isSuccess:true};
}


/**
 * 重置密码
 * 小程序端
 * @param uscc 信用代码
 * @param pwd 原密码
 * @param newPwd 修改后的密码
 * @returns {isSuccess:true/false}
 */
export async function changePassword(uscc:string, pwd:string, newPwd:string) {
    let reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
    if (reg.test(newPwd)) {
        throw new BizError(ERRORENUM.密码不允许有特殊字符, uscc, pwd);
    }
    if (pwd.length > 24) {
        throw new BizError(ERRORENUM.密码长度不能超过24个字符, uscc, pwd);
    }
    let fuhuaqiInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    if (!fuhuaqiInfo) throw new BizError(ERRORENUM.未找到数据);
    let checkPwd = getPwdMd5(fuhuaqiInfo.uscc, pwd);
    if (fuhuaqiInfo.pwd != checkPwd) throw new BizError(ERRORENUM.密码错误);
    fuhuaqiInfo.pwd = getPwdMd5(uscc, newPwd);
    await fuhuaqiInfo.save();

    return {isSuccess:true};
}


/**
 * 退出登录
 * 小程序端
 * @param uscc 信用代码
 * @returns {isSuccess:true/false}
 */
export async function logout(uscc:string):Promise<object> {
    if (typeof uscc != "string") throw new BizError(ERRORENUM.参数错误, uscc);
    let fuhuaqiInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    await fuhuaqiInfo.save();
    return {isSuccess:true};
}


/**
 * 孵化器账号信息列表
 * 管理后台使用
 * @param operationName 运营机构名称
 * @param page 页数
 * @returns 
 */
 export async function fuHuaQiUserList(operationName:string, page:number) {
    let selectParam:any = {};
    if (operationName) selectParam.operationName = operationName;

    let enterpriseMap = await fuhuaqiData.groupFindFuHuaQi();
    let dataBaseList = await fuhuaqiData.findFuHuaQiUserList(selectParam, (page-1)*10 );
    let count = await fuhuaqiData.findFuHuaQiUserCount(selectParam);
    let dataList = [];
    dataBaseList.forEach( info => {
        let changeData = extractData(FuHuaQiListConfig, info);
        const Count = enterpriseMap[info.uscc] || 0;
        dataList.push(changeData);
    });

    return {count, dataList};
}


/**
 * 修改账号状态
 * 管理后台端  禁用/启用 
 * @param uscc 孵化器统一信用代码
 * @param userStatem 是否禁用  true=启用 false=禁用
 * @returns 
 */
export async function updateState(uscc:string, userState:boolean) {
    let fuhuaqiInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    if(!fuhuaqiInfo) throw new BizError(ERRORENUM.账号不存在);
    
    fuhuaqiInfo.userState = userState;
    await fuhuaqiInfo.save();
    
    return {isSuccess:true};
}


/**
 * 添加孵化器账号
 * 管理后台端
 * @param param 表单信息
 * @returns 
 */
export async function addUser(param) {
    checkParamater("新增孵化器账号信息", FuHuaQiUserConfig, param);//校验表单参数


    let fuhuaqiInfo = await fuhuaqiData.findFuHuaQiByUSCC(param.uscc);
    if ( fuhuaqiInfo ) throw new BizError(ERRORENUM.该孵化器账号信息已存在, `${param.uscc}`);
    
    const Pwd = param.uscc.slice(param.uscc.length-3);
    param.pwd = Pwd;
    await fuhuaqiData.createFuHuaQiUser(param);
    
    return {isSuccess:true};
}
