const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class DomicileService extends ServiceBase {
  constructor() {
    super("common", ServiceBase.getDaoName(DomicileService));
    this.businessscopeDao = system.getObject("db.common.businessscopeDao");
  }

  async apiNameList(params) {
    try {
      return await this.nameList();
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiTree(params) {
    try {
      return await this.tree(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiPage(params) {
    try {
      return await this.page(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiSave(params) {
    try {
      return await this.save(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiInfo(params) {
    try {
      return await this.info(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiDeleteByIds(params) {
    var ids = params.ids;
    if (!ids || ids.length == 0) {
      return system.getResult(null, "传入参数错误：ids=" + JSON.stringify(ids));
    }
    try {
      for (var id of ids) {
        try {
          await this.delById(id);
        } catch (error) {
          console.log(error);
        }
      }
      return system.getResultSuccess(1);
    } catch (error) {
      return system.getResult(null, "接口异常");
    }
  }

  // -----------------------以此间隔，上面为API，下面为service---------------------------------

  async info(params) {
    var id = params.id;
    if (!id) {
      return system.getResult(null, "注册地不存在");
    }
    var sqlWhere = {
      where: {
        id: id
      },
      attributes: ["id", "name", "isEnabled", "created_at"],
      raw: true
    };
    var item = await this.dao.model.findOne(sqlWhere);
    if (!item) {
      return system.getResult(null, "注册地不存在");
    }
    this.handleDate(item, ["created_at"], null, -8);
    await this.setBusinessscopeList([item]);
    return system.getResultSuccess(item);
  }

  async save(params) {
    var id = params.id;
    var domicile;
    if (id) {
      domicile = await this.dao.findById(id);
    } else {
      domicile = {};
    }

    domicile.name = this.trim(params.name);
    domicile.isEnabled = params.isEnabled == 1 ? true : 0;

    if (id) {
      domicile = await domicile.save();
    } else {
      domicile = await this.dao.create(domicile);
    }
    return system.getResultSuccess(domicile);
  }

  async nameList() {
    var list = await this.dao.getList(1, "id, name");
    return system.getResultSuccess(list);
  }

  async tree(isEnabled) {
    var tree = await this.dao.getList(isEnabled, "id, name, created_at");
    if (tree) {
      for (var row of tree) {
        this.handleDate(row, ["created_at"], null, -8);
      }
      await this.setBusinessscopeList(tree);
    }
    return system.getResultSuccess(tree);
  }

  async delById(id) {
    if (!id) {
      return system.getResult(null, "删除失败");
    }
    var self = this;
    await this.db.transaction(async function (t) {
      await self.dao.delById(id, t);
      await self.businessscopeDao.delByDomicileId(id, t);
    });
    return system.getResultSuccess(1);
  }

  async page(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var where = {};

    if (params.id > 0) {
      where.id = params.id;
    }

    var orderby = [
      ["id", 'desc']
    ];

    var attributes = ["id", "name", "isEnabled", "created_at"];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["created_at"], null, -8);
      }
      await this.setBusinessscopeList(page.rows);
    }
    return system.getResultSuccess(page);
  }

  async setBusinessscopeList(rows) {
    if (!rows || rows.length == 0) {
      return rows;
    }
    var ids = [];
    for (var item of rows) {
      ids.push(item.id);
    }
    var bsmap = await this.businessscopeDao.findMapByDomicileIds(ids)
    for (var row of rows) {
      row.businessscopeList = bsmap[row.id] || [];
      for (var item of row.businessscopeList) {
        this.handleDate(item, ["created_at"], null, -8);
      }
    }
  }
}
module.exports = DomicileService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });