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


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

  async apiGetById(params) {
    try {
      if(!params.id){
        return system.getResult(null, "参数错误");
      }
      return await this.getById(params.id);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiList(params) {
    try {
      console.log("--"+JSON.stringify(params));
      return await this.invoiceList(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

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

  /**--------------------------------------------------------------------- */

  async getById(id){
    let res = await this.dao.findById(id);
    return system.getResultSuccess(res);
  }

  async save(params) {
    let id = params.id;
    let invoicecontent;
    
    if(id){
      invoicecontent=await this.dao.findById(id); 
    }else{ 
      invoicecontent={};
    }
    invoicecontent.name=this.trim(params.name);
    invoicecontent.isEnabled=(params.isEnabled)==1?true:false;
    if(id){
      await invoicecontent.save();
    }else{
      invoicecontent = await this.dao.create(invoicecontent);
    }
    return system.getResultSuccess(invoicecontent);
  }

  async bulkDelete(ids) {
    if (!ids || ids.length == 0) {
      return system.getResult(null, "删除失败");
    }
    await this.dao.bulkDelete(ids);
  }

  async invoiceList(params) {
    console.log(JSON.stringify(params));
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);
    var where = {};
    if (params.domicileId) {
      where.domicile_id = params.domicileId;
    }
    if (params.name) {
      where.name = {
        [this.db.Op.like]: "%" + decodeURIComponent(params.name) + "%"
      };
    }
    var orderby = [
      ["id", 'desc']
    ];
    var attributes = ["id", "name", "isEnabled",  "created_at",  "updated_at",  "deleted_at"];
    let res = await this.dao.getPageList(currentPage, pageSize, where, orderby, attributes);
    return res;
  }
  
}

module.exports = InvoicecontentService;
