var system = require("../../../system")
const CtlBase = require("../../ctlms.base");
const md5 = require("MD5");
const uuidv4 = require('uuid/v4');
const logCtl = system.getObject("web.common.oplogCtl");
const settings = require("../../../../config/settings");

class UserCtl extends CtlBase {
  constructor() {
    super();
    this.userSve = system.getObject("service.uc.userSve");
    this.redisClient = system.getObject("util.redisClient");
    this.captchaSve = system.getObject("service.common.captchaSve");
  }

  async login(pobj, pobj2, req, res) {
    var loginName = this.trim(pobj.loginName);
    var password = this.trim(pobj.password);
    // var captchaKey = this.trim(pobj.captchaKey);
    // var captchaCode = this.trim(pobj.captchaCode);

    try {
      // var vrs = await this.captchaSve.valid({
      //   key: captchaKey,
      //   code: captchaCode,
      // });
      // if (vrs.status !== 0) {
      //   return vrs;
      // }

      var loginUser = await this.userSve.login({
        ucname: loginName,
        password: password,
      });
      if(loginUser.status != 0) {
        return loginUser;
      }

      loginUser = loginUser.data;

      // 处理用户菜单
      this.buildMenu(loginUser);

      var xggadminsid = await this.setLogin(loginUser);

      return system.getResultSuccess({key: xggadminsid, menus: loginUser.menus});
    } catch (error) {
      console.log(error);
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  buildMenu(loginUser) {
    if (!loginUser || !loginUser.menus || loginUser.menus.length == 0) {
      return;
    }

    let menus = loginUser.menus;
    let sysMenus = [];

    for (let menu of menus) {
      let sm = {
        name: menu.name || "",
        icon: menu.icon || "",
      }
      let team = [];
      if(menu.childs) {
        for (let child of menu.childs) {
          team.push({
            name: child.name || "",
            path: child.path || "",
          });
        }
      }

      sm.team = team;
      sysMenus.push(sm);
    }
    loginUser.menus = sysMenus;
  }

  async setLogin(user) {
    var xggadminsid = "pt_" + uuidv4();
    // if(settings.env == 'dev') {
    //   xggadminsid = "pt_" + "3cb49932-fa02-44f0-90db-9f06fe02e5c7";
    // }
    await this.redisClient.setWithEx(xggadminsid, JSON.stringify(user), 60 * 60);
    return xggadminsid;
  }

  async getMenu(qobj, pobj, req) {
    return system.getResultSuccess(req.loginUser.menus);
  }

  /**
   *   添加 
   * @param {*} params 
   */
  async addUser(params, pobj2, req) {
    try {
      if(!req.loginUser || !req.loginUser.saas_id){
        return system.getResult(null,`登录失效，请重新登陆`);
      }
      var user = {
        saas_id: req.loginUser.saas_id,
        org_id: Number(params.org_id || 0),
        ucname: this.trim(params.ucname),
        password: this.trim(params.password),
        uctype: Number(params.uctype || 1),
        uctypeId: this.trim(params.uctypeId),
        mobile: this.trim(params.mobile),
        realName: this.trim(params.realName),
        roles: params.roles || [],
      };
      if (!user.ucname) {
        return system.getResult(null, "请填写用户名");
      }
      if (!user.password) {
        return system.getResult(null, "请填写密码");
      }
      if (!user.mobile) {
        return system.getResult(null, "请填写手机号");
      }
      if (!user.realName) {
        return system.getResult(null, "请填写姓名");
      }
      if (user.uctype == 1 && !user.org_id) {
        return system.getResult(null, "请选择用户组织机构");
      }


      if (user.uctype != 1) {
        user.org_id = null;
        user.roles = [];
      }
      user.roles = this.transRoles(user.roles);
      return await this.userSve.addUser(user);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   *   更新
   * @param {*} params 
   */
  async updUser(params, pobj2, req) {
    var user = {
      id: Number(params.id || 0),
      saas_id: params.saas_id,
      org_id: Number(params.org_id || 0),
      uctype: Number(params.uctype || 1),
      isMain: Number(params.isMain || 0),
      uctypeId: this.trim(params.uctypeId),
      mobile: this.trim(params.mobile),
      realName: this.trim(params.realName),
      roles: params.roles || [],
    };

    if (!user.id) {
      return system.getResult(null, "用户不存在");
    }

    if (!user.mobile) {
      return system.getResult(null, "请填写手机号");
    }

    if (!user.realName) {
      return system.getResult(null, "请填写姓名");
    }

    if (user.uctype == 1 && !user.org_id) {
      return system.getResult(null, "请选择用户组织机构");
    }

    if (user.uctype != 1) {
      user.org_id = null;
      user.roles = [];
    }
    user.roles = this.transRoles(user.roles);
    try {
      return await this.userSve.updUser(user);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async saveUser(params, pobj2, req) {
    if(!req.loginUser || !req.loginUser.saas_id){
      return system.getResult(null,`登录失效，请重新登陆`);
    }
    
    try {
      var user = {
        id: params.id,
        saas_id:req.loginUser.saas_id,
        ucname: this.trim(params.ucname),
        realName: this.trim(params.realName),
        password: this.trim(params.password),
        mobile: this.trim(params.mobile),
        org_id: Number(params.org_id || 0),
        roles: params.roles || [],
      };
      if (!user.ucname) {
        return system.getResult(null, "请填写用户名");
      }
      if (!user.realName) {
        return system.getResult(null, "请填写姓名");
      }
      if (!user.mobile) {
        return system.getResult(null, "请填写手机号");
      }
      if (!user.org_id) {
        return system.getResult(null, "请选择组织机构");
      }
      if (user.id && !user.password) {
        return system.getResult(null, "请填写密码");
      }
      if (!user.roles || user.roles.length == 0) {
        return system.getResult(null, "请选择角色");
      }

      return await this.userSve.saveUser(user);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async currentUser(qobj, pobj, req) {
    return system.getResultSuccess(req.loginUser);
  }

  /**
   * 启用禁用
   * @param {*} params 
   * @param {*} pobj2 
   * @param {*} req 
   */
  async enabled(params, pobj2, req) {
    try {
      params.id = Number(params.id || 0);
      params.enabled = Number(params.enabled || 0);
      return await this.userSve.enabled(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async delUser(params, pobj2, req) {
    try {
      return await this.userSve.delUser(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   *   查询明细
   * @param {*} params 
   */
  async queryById(params, pobj2, req) {
    try {
      return await this.userSve.queryById(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async orgUsers(params, pobj2, req) {
    params.org_id = params.id;
    delete params.id;
    if (!params.org_id) {
      return system.getResultSuccess([]);
    }
    try {
      let rs = await this.userSve.orgUsers(params);
      return rs;
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }


  async resetPassword(params, pobj2, req) {
    params.password = this.trim(params.password);
    if(!params.password) {
      return system.getResult(null, `请填写密码`);
    }

    try {
      return await this.userSve.updPassword(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 根据pid查出子目录
   * @param {*} params 
   */
  async page(params, pobj2, req) {
    try {
      return await this.userSve.page(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async salesmanList(params, pobj2, req) {
    try {
      params.uctype = 1;
      params.roleCodes = ['ywy'];
      console.log(JSON.stringify(params));
      return await this.userSve.findByRoleCodes(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  transRoles(roles) {
    let rs = [];
    if (!roles || roles.length == 0) {
      return;
    }
    for (let role of roles) {
      rs.push({role_id: role});
    }
    return rs;
  }
}
module.exports = UserCtl;