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

class ChannelService extends ServiceBase {
  constructor() {
    super("channel", ServiceBase.getDaoName(ChannelService));
    this.originDao = system.getObject("db.channel.originDao");
    this.channelmerchantDao = system.getObject("db.channel.channelmerchantDao");
  }

  async suggest(params) {
    let name = this.trim(params.name);
    if (!name) {
      return system.getResultSuccess([]);
    }

    let list = await this.dao.suggest(name);
    return system.getResultSuccess(list);
  }

  async dics() {
    var list = await this.dao.dicList(1);
    return system.getResultSuccess(list);
  }

  async info(params) {
    let channel = await this.dao.getById(params.id);
    return system.getResultSuccess(channel);
  }

  async save(params) {
    let channel;
    if (params.id) {
      channel = await this.findById(params.id);
    } else {
      channel = { isEnabled: 1 };
    }

    channel.name = this.trim(params.name);
    channel.idcode = this.trim(params.idcode);
    channel.business_license = this.trim(params.business_license);
    channel.idcard_front = this.trim(params.idcard_front);
    channel.idcard_back = this.trim(params.idcard_back);
    channel.contact_man = this.trim(params.contact_man);
    channel.contact_mobile = this.trim(params.contact_mobile);
    channel.contact_email = this.trim(params.contact_email);
    channel.contact_addr = this.trim(params.contact_addr);

    if (channel.id) {
      channel.save();
    } else {
      channel.ctype = Number(params.ctype);
      channel = await this.dao.create(channel);
    }
    return system.getResultSuccess(channel);
  }

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

    let where = {};
    if (params.name) {
      where.name = {
        [this.db.Op.like]: "%" + params.name + "%"
      };
    }
    let orderby = [
      ["id", 'desc']
    ];

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

module.exports = ChannelService;
