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 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;