const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")

class UserService extends ServiceBase {
  constructor() {
    super("user", ServiceBase.getDaoName(UserService));
    this.dictionary = system.getObject("util.dictionary");
  }

  async adminLogin(obj) {
    obj.uctype = 1;
    let res = await this.login(obj);
    return res;
  }

  async merchantLogin(obj) {
    obj.uctype = 2;
    let res = await this.login(obj);
    return res;
  }

  async login(obj) {
    let uctype = obj.uctype;
    if ([1, 2].indexOf(uctype) == -1) {
      return system.getResult(null, "用户类型错误");
    }

    let user = await this.dao.getByUcname(obj.ucname, uctype);
    // 验证登录合法
    if (!user) {
      return system.getResult(null, "用户名或密码错误");
    }
    if (!user.is_enabled) {
      return system.getResult(null, "用户已禁用");
    }

    if (uctype && uctype != user.uctype) {
      return system.getResult(null, "用户类型错误");
    }

    let loginPwd = await this.getEncryptStr(obj.password);
    if (loginPwd != user.password) {
      return system.getResult(null, "用户名或密码错误");
    }
    await this.setLogin(user);
    return system.getResultSuccess(user);
  }

  async setLogin(user) {
    console.log("设置登录信息，权限，角色等");
  }

  async saveAdminUser(obj) {
    obj.uctype = 1;
    return await this.saveUser(obj);
  }

  async saveMerchantUser(obj) {
    obj.uctype = 2;
    if (!obj.uctype_id) {
      return system.getResult(null, "未选择用户所属商户");
    }
    return await this.saveUser(obj);
  }

  async userResetPassword(params) {
    let id = params.id;
    let oldPassword = await this.getEncryptStr(this.trim(params.oldPassword));
    let newPassword = this.trim(params.newPassword);
    let newPasswordConfirm = this.trim(params.newPasswordConfirm);
    let user = await this.findById(id);
    if (!user) {
      return system.getResult(null, "修改密码失败，用户不存在");
    }
    if (!newPassword) {
      return system.getResult(null, "修改密码失败，新密码不能为空");
    }
    if (newPassword != newPasswordConfirm) {
      return system.getResult(null, "修改密码失败，两次密码输入不一致");
    }
    if (user.password != oldPassword) {
      return system.getResult(null, "修改密码失败，原密码错误");
    }
    user.password = await this.getEncryptStr(newPassword);
    await user.save();
    return system.getResultSuccess();
  }

  async saveUser(obj) {
    let id = obj.id;
    let password = this.trim(obj.password);
    let uctype_id = this.trim(obj.uctype_id);
    let user = {};
    try {
      if (id) {
        user = await this.findById(id);
      } else {
        if (!password) {
          return system.getResult(null, "密码不能为空");
        }
      }
      user.uctype = obj.uctype;
      user.uctype_id = uctype_id;
      user.ucname = this.trim(obj.ucname);
      user.mobile = this.trim(obj.mobile);
      user.real_name = this.trim(obj.real_name);
      user.is_enabled = obj.is_enabled || false;
      if (password) {
        user.password = await this.getEncryptStr(password);
      }

      let exists = await this.dao.findOne({uctype: user.uctype, ucname: user.ucname});
      if (user.id) {
        if (exists && exists.id != user.id) {
          return system.getResult(-1, `用户名[${user.ucname}]重复`);
        }
        user = await user.save();
      } else {
        if (exists) {
          return system.getResult(-1, `用户名[${user.ucname}]重复`);
        }
        user.autoIncrement = true;
        user = await this.dao.create(user);
      }
    } catch (e) {
      if (e.name == 'SequelizeValidationError') {
        return system.getResult(-1, `用户名[${user.ucname}]重复`);
      }
      console.log(new Date(), e);
      return system.getResult(-1, `服务错误`);
    }
    return system.getResultSuccess(user);
  }

  async info(params) {
    let id = Number(params.id || 0);
    let user = await this.dao.getById(id);
    if (!user) {
      return system.getResult(null, "用户不存在");
    }
    user.password = "";
    this.handleDate(user, ["created_at", "updated_at"], null);
    return system.getResultSuccess(user);
  }

  async enabled(params) {
    let user = await this.dao.findById(params.id);
    if (!user) {
      return system.getResult(null, "用户不存在");
    }
    user.is_enabled = Number(params.is_enabled || 0) == 0 ? false : true;
    await user.save();
    return system.getResultSuccess();
  }

  async pageByCondition(params) {
    let result = {
      count: 0,
      rows: []
    };
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);
    params.startRow = (params.currentPage - 1) * params.pageSize;

    if (params.orgpath) {
      params.orgpath = params.orgpath + "%";
    }
    var total = await this.dao.countByCondition(params);
    if (total == 0) {
      return result;
    }
    result.count = total;
    result.rows = await this.dao.listByCondition(params) || [];
    if (result.rows) {
      for (let item of result.rows) {
        this.handleDate(item, ["created_at"], null);
      }
    }
    return system.getResultSuccess(result);
  }

  async updPassword(params) {
    let user = await this.findById(params.id);
    if (!user) {
      return system.getResult(null, "用户不存在");
    }

    user.password = await this.getEncryptStr(params.password);
    await user.save();
    return system.getResultSuccess();
  }

  async mapByIds(params) {
    let rs = await this.dao.findMapByIds(params.ids, params.attrs);
    return system.getResultSuccess(rs);
  }

}

module.exports = UserService;