const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class BusinessscopeService extends ServiceBase {
  constructor() {
    super("common", ServiceBase.getDaoName(BusinessscopeService));

    this.domicileDao = system.getObject("db.common.domicileDao");
    this.dictionary = system.getObject("util.dictionary");
  }

  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 apiDomicileList(params) {
    try {
      return await this.ListByDomicileId(params.domicileId);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiDeleteByIds(params) {
    var ids = params.ids || [];
    try {
      for(var id of ids) {
        // 单条删除，方便以后有级联删除时使用事务
        await this.delById(id);
      }
      return system.getResultSuccess(1);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  // where: {
  //   id: id
  // },
  // attrs: ["id", "domicile_id", "businessType", "businessscope", "isEnabled", "created_at",],
  // raw: true

  // -----------------------以此间隔，上面为API，下面为service---------------------------------
  async ListByDomicileId(domicileId) {
    var list = await this.dao.findListByDomicileIds([domicileId]) || [];
    for(var item of list) {
      this.handleDate(item, ["created_at"], null, -8);
    }
    await this.setDomicile(list);
    return system.getResultSuccess(list);
  }

  async info(params) {
    var id = params.id;
    var sqlWhere = {
      where: {
        id: id
      },
      attributes: ["id", "domicile_id", "businessType", "businessscope", "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.setDomicile([item]);
    return system.getResultSuccess(item);
  }

  async delById(id) {
    if(!id) {
      return;
    }
    await this.dao.delById(id);
    return system.getResultSuccess(1);
  }

  async save(params) {
    let domicileId = this.trim(params.domicileId);
    let saas_id = this.trim(params.saas_id);
    let id = this.trim(params.id);
    let bsc;
    if (id) {
      bsc = await this.dao.findById(id);
    } else {
      bsc = {domicile_id: domicileId};
    }

    bsc.businessType = this.trim(params.businesssType);
    bsc.businessscope = this.trim(params.businessscope);
    bsc.isEnabled = true;
    bsc.saas_id = saas_id;

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

  async businessscopeBulkSave(params) {
    try {
      let list = params.list;
      if (!list || list.length == 0) {
        return system.getResult(null, "缺少经营范围数据");
      }
      let rs = await this.dao.bulkCreate(list);
      return system.getResultSuccess(rs);
    } catch (e) {
      console.log(e.stack);
      return system.getResult(null, e.stack);
    }
  }

  async saveDefaultBusinessScope(params) {
    let saas_id = this.trim(params.saas_id);
    if (!saas_id) {
      return system.getResult(null, "saas_id不存在");
    }
    let defaultList = this.dictionary.getDefaultList("BUSINESS_SCOPE_DEFAULT", {saas_id: saas_id});
    return await this.businessscopeBulkSave({list: defaultList});
  }

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

    var where = {};
    if (params.saas_id) {
      where.saas_id = params.saas_id;
    }
    if (params.domicileId) {
      where.domicile_id = params.domicileId;
    }
    if (params.businessType) {
      where.businessType = {
        [this.db.Op.like]: params.businessType + "%"
      };
    }
    if (params.isEnabled) {
      where.isEnabled = params.isEnabled || 1;
    }

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

    var attributes = ["id", "domicile_id", "businessType", "businessscope", "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);
        row.isEnabled = row.isEnabled == 1 ? '启用' : '未启用';
      }
      await this.setDomicile(page.rows);
    }
    return system.getResultSuccess(page);
  }

  async setDomicile(rows) {
    if(!rows || rows.length == 0) {
      return;
    }

    let ids = [];
    for (var item of rows) {
      if (item.domicile_id) {
        ids.push(item.domicile_id);
      }
    }
    let map = await this.domicileDao.findMapByIds(ids);
    for (var item of rows) {
      item.domicile = map[item.domicile_id] || {};
      this.handleDate(item.domicile, ["created_at"], null, -8);
    }
  }
}
module.exports = BusinessscopeService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });