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

    this.businessmeninvoicecontentDao = system.getObject("db.business.businessmeninvoicecontentDao");
  }

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

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


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

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

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

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

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

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


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

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

  // -----------------------以此间隔，上面为API，下面为service---------------------------------
  async method(params) {
    return system.getResultSuccess();
  }

  async addContract(params) {
    var merchantId = params.merchant_id || params.merchantId;
    var channelOrderNo = this.trim(params.channelOrderNo);

    var businessmen = await this.dao.findOne({
      merchant_id: merchantId,
      channelOrderNo: channelOrderNo,
    });

    if (!businessmen) {
      return system.getResult(null, "个体户不存在");
    }

    businessmen.contract = this.trim(params.contract);
    businessmen.contractStartData = params.contractStartData;
    businessmen.contractEndData = params.contractEndData;

    await businessmen.save();
    return system.getResultSuccess();
  }

  async byOrderId(params) {
    var businessmen = await this.dao.getByOrderId(param.orderId);

    if (businessmen) {
      await this.dao.setRowCodeName(businessmen, "bstatus");
      await this.dao.setRowCodeName(businessmen, "gstatus");
      await this.dao.setRowCodeName(businessmen, "dstatus");

      this.handleDate(businessmen, ["created_at", "updated_at", "signTime"], "YYYY-MM-DD HH:mm:ss", -8);
      this.handleDate(businessmen, ["regDate", "taxRegDay", "contractEndData", "contractStartData"], "YYYY-MM-DD", -8);
    }

    return system.getResultSuccess(businessmen);
  }

  async byChannelOrderNo(params) {
    var businessmen = await this.dao.getByChannelOrderNo(params.merchantId, params.channelOrderNo);

    if (businessmen) {
      await this.dao.setRowCodeName(businessmen, "bstatus");
      await this.dao.setRowCodeName(businessmen, "gstatus");
      await this.dao.setRowCodeName(businessmen, "dstatus");

      this.handleDate(businessmen, ["created_at", "updated_at", "signTime"], "YYYY-MM-DD HH:mm:ss", -8);
      this.handleDate(businessmen, ["regDate", "taxRegDay", "contractEndData", "contractStartData"], "YYYY-MM-DD", -8);
    }

    return system.getResultSuccess(businessmen);
  }

  async nameList(params) {
    var list = await this.dao.nameList(params.bstatuses);
    return system.getResultSuccess(list);
  }

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

    var orderId = this.trim(params.orderId);
    var bstatus = this.trim(params.bstatus);
    var merchantId = this.trim(params.merchantId);

    var where = {};

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

    if (params.businessmenId) {
      where.id = params.businessmenId;
    }

    if (merchantId) {
      where.merchant_id = merchantId;
    }
    if (orderId) {
      where.order_id = orderId;
    }
    if (bstatus) {
      where.bstatus = bstatus;
    }

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);

    var page = await this.getPageList(currentPage, pageSize, where, orderby);
    if (page && page.rows) {
      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "bstatus");
        await this.dao.setRowCodeName(row, "gstatus");
        await this.dao.setRowCodeName(row, "dstatus");

        this.handleDate(row, ["created_at", "updated_at", "signTime"], null, -8);
        this.handleDate(row, ["regDate", "taxRegDay"], "YYYY-MM-DD", -8);
      }

      // 设置开票内容
      await this.setInvoiceContent(page.rows);

    }
    return system.getResultSuccess(page);
  }

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

    var orderId = this.trim(params.orderId);
    var status = this.trim(params.status);
    var merchantId = this.trim(params.merchantId);

    var where = {};

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

    if (params.businessmenId) {
      where.id = params.businessmenId;
    }
    where.bstatus = "2020";

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);

    var page = await this.getPageList(currentPage, pageSize, where, orderby);
    if (page && page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["created_at", "updated_at", "signTime"], null, -8);
        this.handleDate(row, ["regDate", "taxRegDay"], "YYYY-MM-DD", -8);
      }

      await this.setInvoiceContent(page.rows);
    }
    return system.getResultSuccess(page);
  }

  async getCompleteMapByCreditCodes(params) {
    var result = {};
    var attrs = "id, creditCode, name, isBank, taxOrg, taxUpType, addValueUpType, costRate, " +
      "taxRate, serviceRate,commonTaxLadder,commonOtherLadder,specialTaxLadder,specialOtherLadder";

    var condition = {
      creditCodes: params.creditCodes,
      statuses: ["2020"],
    }
    var list = await this.dao.getByCreditCodes(condition, attrs);
    if (!list || list.length == 0) {
      return result;
    }

    var ids = [];
    for (var item of list) {
      ids.push(item.id);
    }

    var icmap = await this.businessmeninvoicecontentDao.mapByBusinessmenIds(ids);
    for (var item of list) {
      item.invoicecontents = icmap[item.id] || [];
      result[item.creditCode] = item;
    }
    return system.getResultSuccess(result);
  }

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

    var merchantId = this.trim(params.merchantId);
    var orderId = this.trim(params.orderId);
    var status = this.trim(params.status);

    // TODO 有可能根据这个鸡巴玩意进行查询
    var deliverId = this.trim(params.deliverId);

    var where = {};

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

    if (params.businessmenId) {
      where.id = params.businessmenId;
    }

    if (merchantId) {
      where.merchant_id = merchantId;
    }
    if (orderId) {
      where.order_id = orderId;
    }
    if (status) {
      where.status = status;
    }

    var attrs = ["id", "order_id", "legalName", "creditCode", "status"];

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attrs);
    if (page && page.rows) {
      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "status");
      }
    }
    return system.getResultSuccess(page);
  }

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

    var userId = this.trim(params.userId);
    var orderId = this.trim(params.orderId);
    var gstatuses = params.gstatuses;

    var where = {};
    if (userId) {
      where.userId = userId;
    }

    if (orderId) {
      where.order_id = orderId;
    }
    if (gstatuses && gstatuses.length > 0) {
      where.gstatus = {
        [this.db.Op.in]: gstatuses
      }
    }

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

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);
    var page = await this.getPageList(currentPage, pageSize, where, orderby);
    if (page && page.rows) {
      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "bstatus");
        await this.dao.setRowCodeName(row, "gstatus");
        await this.dao.setRowCodeName(row, "dstatus");
        this.handleDate(row, ["created_at", "updated_at"], null, -8);
        this.handleDate(row, ["regDate", "taxRegDay"], "YYYY-MM-DD", -8);
      }
    }
    return system.getResultSuccess(page);
  }
  
  async deliverPage(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var deliverId = this.trim(params.deliverId);
    var orderId = this.trim(params.orderId);
    var dstatus = params.dstatus;

    var where = {};
    if (deliverId) {
      // TODO 查询个体户下所有订单id
    }

    if (orderId) {
      where.order_id = orderId;
    }
    if (dstatus) {
      where.dstatus = dstatus
    }

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

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd);
    var page = await this.getPageList(currentPage, pageSize, where, orderby);
    if (page && page.rows) {
      for (var row of page.rows) {
        await this.dao.setRowCodeName(row, "dstatus");
        this.handleDate(row, ["created_at", "updated_at"], null, -8);
        this.handleDate(row, ["regDate", "taxRegDay"], "YYYY-MM-DD", -8);
      }
    }
    return system.getResultSuccess(page);
  }

  async info(params) {
    var info = await this.dao.getById(params.id);

    await this.dao.setRowCodeName(info, "bstatus");
    await this.dao.setRowCodeName(info, "gstatus");
    await this.dao.setRowCodeName(info, "dstatus");

    this.handleDate(info, ["created_at", "updated_at"], null, -8);
    this.handleDate(info, ["regDate", "taxRegDay"], "YYYY-MM-DD", -8);
    await this.setInvoiceContent([info]);
    return system.getResultSuccess(info);
  }

  async sign(params) {
    var bm = await this.dao.findById(params.id);
    if (!bm) {
      return system.getResult(null, "个体户不存在");
    }

    if (bm.bstatus != "2010" && bm.bstatus != "2020") {
      return system.getResult(null, "个体户状态错误，不允许进行签约");
    }

    bm.bstatus = "2020";
    bm.gstatus = "2020";

    bm.taxUpType = params.taxUpType || "1";
    bm.addValueUpType = params.addValueUpType || "1";
    bm.costRate = params.costRate;
    bm.taxRate = params.taxRate;
    bm.serviceRate = params.serviceRate;
    bm.signNotes = this.trim(params.signNotes);

    bm.commonTaxLadder = params.commonTaxLadder || "";
    bm.commonOtherLadder = params.commonOtherLadder || "";
    bm.specialTaxLadder = params.specialTaxLadder || "";
    bm.specialOtherLadder = params.specialOtherLadder || "";
    bm.signTime = new Date();
    await bm.save();

    var iclist = params.invoicecontents || [];
    await this.businessmeninvoicecontentDao.delByBusinessmenId(bm.id);
    var icobjs = [];
    for(var ic of iclist) {
      if(!ic) {
        continue;
      }
      delete ic.id;
      ic.businessmen_id = bm.id;
      icobjs.push(ic);
    }
    if(icobjs.length > 0) {
      await this.businessmeninvoicecontentDao.bulkCreate(icobjs);
    }
    return system.getResultSuccess();
  }

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

    var ids = [];
    for (var row of rows) {
      ids.push(row.id);
    }

    var icmap = await this.businessmeninvoicecontentDao.mapByBusinessmenIds(ids);
    for (var row of rows) {
      ids.push(row.id);
      row.invoicecontents = icmap[row.id] || [];
    }
  }
}
module.exports = BusinessmenService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });