const system = require("../system");
var moment = require('moment')
class ServiceBase {
  constructor(daoName) {
    //this.dbf=system.getObject("db.connection");
    this.db = system.getObject("db.connection").getCon();
    this.cacheManager = system.getObject("db.cacheManager");
    this.daoName = daoName;
    this.dao = system.getObject("db." + daoName);
  }
  static getDaoName(ClassObj) {
    return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Service")).toLowerCase() + "Dao";
  }
  async findAll(obj) {
    var objs = await this.dao.model.findAll({ where: obj, raw: true, });
    return objs;
  }
  async findAndCountAll(obj) {

    const apps = await this.dao.findAndCountAll(obj);
    return apps;
  }
  async refQuery(qobj) {
    return this.dao.refQuery(qobj);
  }
  async bulkDelete(ids) {
    var en = await this.dao.bulkDelete(ids);
    return en;
  }
  async bulkDeleteByWhere(whereParam, t) {
    return await this.dao.bulkDelete(whereParam, t);
  }
  async afteraudit(obj, tm) {

  }
  async audit(userinfo, audlist, notes, status) {
    var self = this;
    if (status == "btg" && !notes.value) {
      throw new Error("不通过失败，请输入审核不通过的理由");
    }
    var tmpFilter = audlist.filter(f => f.auditStatus == "dsh");
    if (audlist.length != tmpFilter.length) {
      throw new Error("目前只能对审核状态为【待审核】的数据进行审核");
    }
    return this.db.transaction(async function (t) {
      for (var i = 0; i < audlist.length; i++) {
        if (audlist[i]) {
          audlist[i].auditStatus = status;
          audlist[i].opNotes = notes.value || "";
          await self.afteraudit(audlist[i], t);
          var param = {
            id: audlist[i].id,
            auditor: userinfo.nickName,
            audituser_id: userinfo.id,
            updator: userinfo.nickName,
            updateuser_id: userinfo.id,
            opNotes: notes.value || "",
            auditStatus: status
          };
          await self.dao.update(param, t);
        }
      }
    });

  }
  async bulkCreate(ids, t) {
    var en = await this.dao.bulkCreate(ids, t);
    return en;
  }
  async beforedelete(qobj, t) {

  }
  async delete(qobj) {
    var self = this;
    return this.db.transaction(async function (t) {
      await self.beforedelete(qobj, t);
      return self.dao.delete(qobj, t);;
    });
  }

  async aftercreate(result, t) {

  }
  async create(qobj) {
    var self = this;
    return this.db.transaction(async function (t) {
      var result = await self.dao.create(qobj, t);
      await self.aftercreate(result, t);
      return result;
    });
  }

  async update(qobj, tm = null) {
    return this.dao.update(qobj, tm);
  }
  async updateByWhere(setObj, whereObj, t) {
    return this.dao.updateByWhere(setObj, whereObj, t);
  }
  async customExecAddOrPutSql(sql, paras = null) {
    return this.dao.customExecAddOrPutSql(sql, paras);
  }
  async customQuery(sql, paras, t) {
    return this.dao.customQuery(sql, paras, t);
  }
  async findCount(whereObj = null) {
    return this.dao.findCount(whereObj);
  }
  async findSum(fieldName, whereObj = null) {
    return this.dao.findSum(fieldName, whereObj);
  }
  async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
    return this.dao.getPageList(pageIndex, pageSize, whereObj, orderObj, attributesObj, includeObj);
  }
  async findOne(obj) {
    return this.dao.findOne(obj);
  }
  async findById(oid) {
    return this.dao.findById(oid);
  }
  /*
  返回20位业务订单号
  prefix：业务前缀
  */
  async getBusUid(prefix) {
    prefix = (prefix || "");
    if (prefix) {
      prefix = prefix.toUpperCase();
    }
    var prefixlength = prefix.length;
    var subLen = 8 - prefixlength;
    var uidStr = "";
    if (subLen > 0) {
      uidStr = await this.getUidInfo(subLen, 60);
    }
    var timStr = moment().format("YYYYMMDDHHmm");
    return prefix + timStr + uidStr;
  }
  /*
  len：返回长度
  radix：参与计算的长度，最大为62
  */
  async getUidInfo(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62，到yz长度为长36
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
  async isCheckRole(user, roleCode) {//判断用户是否存在某种角色
    var isRole = false;
    if (user.Roles && user.Roles.length > 0) {
      var roleList = user.Roles.filter(f => f.code == roleCode);
      if (roleList && roleList.length > 0) {
        isRole = true;
      }
    }
    return isRole;
  }
}
module.exports = ServiceBase;
