import { GMUserModel } from '@db/GMUser';
import { GMGroupModel } from '@db/GMGroup';
import { Service } from 'egg';
import { BACKEND_37_CODE, SDK_37_CONST, STATUS } from '@consts';
import { gameData } from '@pubUtils/data';
import { nowSeconds } from '@pubUtils/timeUtil';
import { isNumber } from 'util';
import { get37BackendMd5Sign } from '@pubUtils/sdkUtil';

/**
 * Test Service
 */
export default class GMUsers extends Service {

  /**
   * 后台账号登录
   */
  public async login(username: string, password: string) {
    console.log('******', username, password)
    try {
      const {ctx} = this;
      let token = ctx.service.utils.genCode(256);
      let user = await GMUserModel.login(username, password, token);
  
      console.log('******', user)
      if(!user) {
        return ctx.service.utils.resResult(STATUS.GM_ERR_PASSWORD);
      }
      if(!user.isEnable) {
        return ctx.service.utils.resResult(STATUS.GM_NO_AUTHORITY_GET);
      }
      if(user.type != 1) {
        return ctx.service.utils.resResult(STATUS.GM_USER_TYPE_ERR);
      }
      let group = new Array();
      if(user.groupId != undefined) {
        let g = await GMGroupModel.getGroupById(user.groupId);
        if(g) group.push(g.group);
      }
      console.log('******', group, token)

      return ctx.service.utils.resResult(STATUS.SUCCESS, {
        ...user, group, token
      });
    }catch(e) {
      console.log(e)
    }
  }

  public async currentUser() {
    const {ctx} = this;
    let user = ctx.user;
    let group = new Array();
    if(user.groupId != undefined) {
      let g = await GMGroupModel.getGroupById(user.groupId);
      if(g) group.push(g.group);
    }

    return ctx.service.utils.resResult(STATUS.SUCCESS, { user: ctx.user, group });
  }

  public async channelLogin(uname: string, _time: string, sign: string) {
    const {ctx} = this;
    let time = parseInt(_time);
    if(!uname || !time || !isNumber(time) || !sign) {
      return  ctx.service.utils.resResult(BACKEND_37_CODE.WRONG_PARAM);
    }

    if(nowSeconds() - time > 15 * 60) {
      return  ctx.service.utils.resResult(BACKEND_37_CODE.TIME_IS_EXPIRED);
    }

    let checkResult = this.check37Sign({ uname, time, sign });
    if(!checkResult) {
      return  ctx.service.utils.resResult(BACKEND_37_CODE.MD5_ERR); 
    }
    let token = ctx.service.utils.genCode(256);
    let user = await GMUserModel.channelLogin(uname, token);
    if(!user) {
      return  ctx.service.utils.resResult(BACKEND_37_CODE.USER_NOT_FOUND); 
    }
    if(user.type != 2) {
      return  ctx.service.utils.resResult(BACKEND_37_CODE.LOGIN_FAIL); 
    }
    return  ctx.service.utils.resResult(BACKEND_37_CODE.SUCCESS, { token: user.token }); 
  }

  private check37Sign(params: { uname: string, time: number, sign: string }) {
    let sign = get37BackendMd5Sign(params, SDK_37_CONST.BACKEND_KEY);
    console.log('******37Sign', sign, params.sign, sign == params.sign);
    return sign == params.sign;
  }


  /**
   * 修改我的密码
   */
  public async changeMyPass(uid: number, password: string) {
    const {ctx} = this;
    let user = ctx.user;
    if(uid != user.uid) return ctx.service.utils.resResult(STATUS.GM_NO_AUTHORITY_POST);

    let result = await GMUserModel.changePass(uid, password);
    if(result) {
      return ctx.service.utils.resResult(STATUS.SUCCESS);
    } else {
      return ctx.service.utils.resResult(STATUS.INTERNAL_ERR);
    }
  }

  /**
   * 后台账号列表
   */
  public async getGmList() {
    let list = await GMUserModel.getGmAccountList();
    if(list) {
      let result = new Array();
      for(let user of list) {
        let groupId = 0, groupStr = '暂无', envs = [];
        if(user.groupId != undefined) {
          let group = await GMGroupModel.getGroupById(user.groupId);
          if(group) {
            groupId = user.groupId;
            envs = user.envs
            groupStr = group.name;
          }
        }
        result.push({...user, group: groupId,  groupStr, env: envs});
      }

      return this.ctx.service.utils.resResult(STATUS.SUCCESS, {
        gmlist: result
      });

    
    } else {
      return this.ctx.service.utils.resResult(STATUS.INTERNAL_ERR);
    }
  }
  
  /**
   * 创建后台账号
   */
  public async createGmAccount(name: string, username: string, password: string) {
    const {ctx} = this;
    let token = ctx.service.utils.genCode(256);

    let user = await GMUserModel.getGmAccountByUsername(username);
    if(user) {
      return ctx.service.utils.resResult(STATUS.GM_DUPLICATE_GM_ACCOUNT)
    } else {
      user = await GMUserModel.createGmAccount(username, password, name, token);
      return ctx.service.utils.resResult(STATUS.SUCCESS);
    }
  }

  /**
   * 后台Api列表
   */
  public async getApiList() {
    const {ctx} = this;
    let list = [];
    for(let [_, obj] of gameData.apiByUrl) {
      list.push(obj);
    }

    if(list) {
      return ctx.service.utils.resResult(STATUS.SUCCESS, {
        list
      });
    } else {
      return ctx.service.utils.resResult(STATUS.INTERNAL_ERR);
    }
  }

  /**
   * 后台用户组列表
   */
  public async getGroupList() {
    const {ctx} = this;
    let list = await GMGroupModel.getAllGroup();

    if(list) {
      return ctx.service.utils.resResult(STATUS.SUCCESS, { list });
    } else {
      return ctx.service.utils.resResult(STATUS.INTERNAL_ERR);
    }
  }

  /**
   * 创建用户组
   */
  public async createGmGroup(group:string, name:string, desc: string) {
    const {ctx} = this;
    let result = await GMGroupModel.getGroup(group);
    if(result) {
      return ctx.service.utils.resResult(STATUS.GM_DUPLICATE_GROUP);
    } else {
      let result = await GMGroupModel.createGroup(group, name, desc);
      if(result) {
        return ctx.service.utils.resResult(STATUS.SUCCESS);
      } else {
        return ctx.service.utils.resResult(STATUS.INTERNAL_ERR);
      }
    }
  }

  /**
   * 修改用户组
   */
  public async saveGmGroup(groupId: number, group:string, name:string, desc: string) {
    const {ctx} = this;

    let result = await GMGroupModel.editGroup(groupId, group, name, desc);
    if(result) {
      return ctx.service.utils.resResult(STATUS.SUCCESS);
    } else {
      return ctx.service.utils.resResult(STATUS.INTERNAL_ERR);
    }
  }

  /**
   * 用户组添加接口
   */
  public async saveGmApiToGroup(apiId: number, apis: Array<number>) {
    const {ctx} = this;
    let result = await GMGroupModel.saveApiToGroup(apiId, apis);
    if(result) {
      return ctx.service.utils.resResult(STATUS.SUCCESS);
    } else {
      return ctx.service.utils.resResult(STATUS.INTERNAL_ERR);
    }
  }

  /**
   * 用户组添加接口
   */
  public async saveGmGroupToUser(uid: number, groupId: number, envs: string[], isEnable: boolean, type: number) {
    await GMUserModel.updateInfo(uid, { groupId, envs, isEnable, type });
    return this.ctx.service.utils.resResult(STATUS.SUCCESS);

  }
}
