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

class SaasMerchantUserService extends ServiceBase {
  constructor() {
    super("user", ServiceBase.getDaoName(SaasMerchantUserService));
  }

  async login(params) {
    let user = await this.dao.byUcname(params.ucname, params.saas_merchant_id);
    // 验证登录合法
    if (!user) {
      return system.getResult(null, "用户名或密码错误");
    }
    if (!user.isEnabled) {
      return system.getResult(null, "用户已禁用");
    }

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

  async save(params) {
    let id = Number(params.id || 0);
    let saas_merchant_id = this.trim(params.saas_merchant_id);
    let saas_id = this.trim(params.saas_id);
    let ucname = this.trim(params.ucname);
    let mobile = this.trim(params.mobile);
    let realName = this.trim(params.realName);
    let password = this.trim(params.password);
    let isEnabled = Number(params.isEnabled || 0);
    if (!realName) {
      return system.getResult(null, "请输入用户姓名");
    }
    if (!mobile) {
      return system.getResult(null, "请输入联系手机");
    }
    if (!ucname) {
      return system.getResult(null, "请输入账号");
    }

    try {
      let exists = await this.dao.findOne({
        saas_merchant_id: saas_merchant_id,
        ucname: ucname
      });
      let user;
      if (id) {
        if (exists && exists.id != id) {
          return system.getResult(null, `账号名称[${ucname}]已存在`);
        }
        user = await this.dao.findById(id);
        user.realName = realName;
        user.ucname = ucname;
        user.isEnabled = isEnabled;
        if (password && password != user.password) {
          user.password = await this.getEncryptStr(password);
        }
        await user.save();
      } else {
        if (exists) {
          return system.getResult(null, `账号名称[${ucname}]已存在`);
        }
        if (!saas_merchant_id) {
          return system.getResult(null, "请选择商户");
        }
        if (!password) {
          return system.getResult(null, "请输入密码");
        }
        user = {
          saas_id: saas_id,
          saas_merchant_id: saas_merchant_id,
          password: await this.getEncryptStr(password),
          realName: realName,
          ucname: ucname,
          mobile: mobile,
          isEnabled: isEnabled,
        };
        user = await this.dao.model.create(user);
      }
      return system.getResultSuccess(user);
    } catch (error) {
      console.log(error);
      if (error.name == 'SequelizeValidationError') {
        return system.getResult(null, `账号名称[${ucname}]已存在`);
      }
      return system.getResult(-1, `系统错误 错误信息${error}`);
    }
  }

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

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

  async pageByCondition(params) {
    var result = {
      count: 0,
      rows: []
    };
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);
    var total = await this.dao.countByCondition(params);
    if (total == 0) {
      return system.getResultSuccess(result);
    }

    result.count = total;
    params.startRow = (currentPage - 1) * pageSize;
    result.rows = await this.dao.listByCondition(params) || [];
    if (result.rows) {
      for (let item of result.rows) {
        this.handleDate(item, ["created_at"], null, -8);
      }
    }
    return system.getResultSuccess(result);
  }

  async updPassword(params) {
    var 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.mapByIds(params.ids, params.attrs);
    return system.getResultSuccess(rs);
  }
}

module.exports = SaasMerchantUserService;