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

    this.saasmerchantsignDao = system.getObject("db.merchant.saasmerchantsignDao");
    this.saasmainDao = system.getObject("db.main.saasmainDao");
    this.saasmerchantsettingsDao = system.getObject("db.merchant.saasmerchantsettingsDao");
    this.saasmerchanttitleDao = system.getObject("db.merchant.saasmerchanttitleDao");
    this.saasmerchantaddrDao = system.getObject("db.merchant.saasmerchantaddrDao");
  }
  // -----------------------以此间隔，上面为API，下面为service---------------------------------

  async idsLikeName(params) {
    let name = this.trim(params.name);
    let saas_id = this.trim(params.saas_id);
    let saas_merchant_id = this.trim(params.saas_merchant_id);

    let ids = await this.dao.idsLikeName({
      name: `%${name}%`,
      saas_id: saas_id,
      saas_merchant_id: saas_merchant_id
    });
    return system.getResultSuccess(ids);
  }

  async mapByIds(params) {
    if (!params.ids || params.ids.length == 0) {
      return system.getResultSuccess({});
    }
    let rs = await this.dao.mapByIds(params.ids, params.attrs);
    return system.getResultSuccess(rs);
  }

  async dics(params) {
    params.attrs = "id, name, short_name";
    let list = await this.dao.dics(params);
    return system.getResultSuccess(list);
  }

  async info(params) {
    if (!params.id) {
      return system.getResult(null, "id不存在");
    }

    let merchant = await this.dao.getById(params.id);
    if (!merchant) {
      return system.getResult(null, "商户不存在");
    }

    this.handleDate(merchant, ["created_at"], null, -8);
    let sign = await this.saasmerchantsignDao.getById(params.id);
    this.handleDate(sign, ["created_at"], null, -8);
    this.handleDate(sign, ["begin_date", "end_date"], "YYYY-MM-DD");
    /**
     * TODO:这里只查询个体户注册签约的主题，如果以后添加发票等签约主体，需要新增查询
     */
    let saas_main =null;
    if(sign.main_id) {
      saas_main = await this.saasmainDao.getById(sign.main_id);
    }
    sign.saas_main = saas_main || {};
    merchant.sign = sign;
    return system.getResultSuccess(merchant);
  }

  async signInfo(params) {
    if (!params.id) {
      return system.getResult(null, "id不存在");
    }

    let sign = await this.saasmerchantsignDao.getById(params.id);
    if (!sign) {
      return system.getResult(null, "商户不存在");
    }

    this.handleDate(sign, ["created_at"], null, -8);
    this.handleDate(sign, ["begin_date", "end_date"], "YYYY-MM-DD", -8);
    return system.getResultSuccess(sign);
  }

  async save(params) {
    let id = Number(params.id || 0);
    let saas_id = Number(params.saas_id || 0);

    let term = Number(params.term || 1);
    let term_end = this.trim(params.term_end);

    let validity = Number(params.validity || 1);
    let validity_end = this.trim(params.validity_end);

    if (!saas_id) {
      return getResult(null, "saas不存在");
    }

    if (!this.trim(params.name)) {
      return system.getResult(null, "请填写渠道名称");
    }
    if (!this.trim(params.short_name)) {
      return system.getResult(null, "请填写渠道简称");
    }
    if (!this.trim(params.credit_code)) {
      return system.getResult(null, "请填写统一社会信用代码");
    }
    // if(!this.trim(params.business_lincense_img)) {return system.getResult(null, ""); }   // 营业执照暂不验证
    if (!this.trim(params.tax_type)) {
      return system.getResult(null, "请选择纳税人类型");
    }
    if (!this.trim(params.residence)) {
      return system.getResult(null, "请填写住所");
    }
    if (!this.trim(params.business_scope)) {
      return system.getResult(null, "请填写经营范围");
    }
    if (term == 2 && !term_end) {
      return system.getResult(null, "请填写营业期限固定日期");
    }

    // if(!this.trim(params.idcard_front)) {return system.getResult(null, "idcard_front为空"); } 
    // if(!this.trim(params.idcard_back)) {return system.getResult(null, "idcard_back为空"); } 
    // if (!this.trim(params.legal_name)) {
    //   return system.getResult(null, "请填写法人姓名");
    // }
    // if (!this.trim(params.legal_idno)) {
    //   return system.getResult(null, "请填写法人身份证");
    // }
    if (validity == 2 && !validity_end) {
      return system.getResult(null, "请填写有效期限固定日期");
    }

    if (!this.trim(params.account_name)) {
      return system.getResult(null, "请填写账户名称");
    }
    if (!this.trim(params.account_bank_name)) {
      return system.getResult(null, "请填写开户行");
    }
    if (!this.trim(params.account_bank_no)) {
      return system.getResult(null, "请填写开户账号");
    }
    if (!this.trim(params.account_mobile)) {
      return system.getResult(null, "请填写联系电话");
    }

    if (!this.trim(params.contact_man)) {
      return system.getResult(null, "请填写联系人姓名");
    }
    if (!this.trim(params.contact_mobile)) {
      return system.getResult(null, "请填写联系人电话");
    }
    if (!this.trim(params.contact_email)) {
      return system.getResult(null, "请填写联系人邮箱");
    }
    if (!this.trim(params.contact_addr)) {
      return system.getResult(null, "请填写联系人地址");
    }

    let merchant;
    if (id) {
      merchant = await this.dao.findById(id);
    } else {
      merchant = {};
      merchant.saas_id = saas_id;
      merchant.channel_id = this.trim(params.channel_id);
    }
    merchant.name = this.trim(params.name);
    merchant.short_name = this.trim(params.short_name);
    merchant.credit_code = this.trim(params.credit_code);
    merchant.business_lincense_img = this.trim(params.business_lincense_img);
    merchant.residence = this.trim(params.residence);
    merchant.tax_type = this.trim(params.tax_type);
    merchant.business_scope = this.trim(params.business_scope);
    merchant.idcard_front = this.trim(params.idcard_front);
    merchant.idcard_back = this.trim(params.idcard_back);
    merchant.legal_idno = this.trim(params.legal_idno);
    merchant.legal_name = this.trim(params.legal_name);
    merchant.account_name = this.trim(params.account_name);
    merchant.account_bank_name = this.trim(params.account_bank_name);
    merchant.account_bank_no = this.trim(params.account_bank_no);
    merchant.account_mobile = this.trim(params.account_mobile);
    merchant.contact_man = this.trim(params.contact_man);
    merchant.contact_mobile = this.trim(params.contact_mobile);
    merchant.contact_email = this.trim(params.contact_email);
    merchant.contact_addr = this.trim(params.contact_addr);

    merchant.term = term;
    if (term_end) {
      merchant.term_end = term_end;
    }
    if (term == 1) {
      merchant.term_end = null;
    }
    merchant.validity = validity;
    if (validity_end) {
      merchant.validity_end = validity_end;
    }
    if (validity == 1) {
      merchant.validity_end = null;
    }

    let self = this;
    if (merchant.id) {
      await merchant.save();
    } else {
      merchant = await self.db.transaction(async function (t) {
        // 创建商户
        merchant = await self.dao.create(merchant, t);
        await self.saasmerchantsignDao.create({
          id: merchant.id
        }, t);
        return merchant;
      });
    }
    return system.getResultSuccess(merchant);
  }

  async pageByCondition(params) {
    let currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);
    params.startRow = (currentPage - 1) * params.pageSize;

    var page = {
      count: 0,
      rows: []
    };

    page.count = await this.dao.countByCondition(params);
    if (page.count == 0) {
      return system.getResultSuccess(page);
    }

    page.rows = await this.dao.listByCondition(params) || [];
    if (page.rows) {
      for (let item of page.rows) {
        this.handleDate(item, ["created_at"], null, -8);
        this.handleDate(item, ["begin_date", "end_date"], "YYYY-MM-DD");
      }
    }
    return system.getResultSuccess(page);
  }

  async sign(params) {
    if (!params.id) {
      return system.getResult(null, "id不存在");
    }

    if (!this.trim(params.main_id)) {
      return system.getResult(null, "请选择签约主体");
    }
    if (!this.trim(params.begin_date)) {
      return system.getResult(null, "请选择签约开始时间");
    }
    if (!this.trim(params.end_date)) {
      return system.getResult(null, "请选择签约失效时间");
    }
    let merchant = await this.dao.findById(params.id);
    let sign = await this.saasmerchantsignDao.findById(params.id);
    sign.main_id = this.trim(params.main_id);
    sign.main_id_trade = this.trim(params.main_id_trade);
    sign.main_id_invoice = this.trim(params.main_id_invoice);
    sign.begin_date = this.trim(params.begin_date);
    sign.end_date = this.trim(params.end_date);
    sign.bm_reg_price = Number(params.bm_reg_price || 0);
    sign.invoice_service_rate = Number(params.invoice_service_rate || 0);
    sign.trans_service_rate = Number(params.trans_service_rate || 0);

    await sign.save();
    merchant.is_sign = true;
    await merchant.save();
    return system.getResultSuccess();
  }

  async getSettings(params) {
    let rs = await this.saasmerchantsettingsDao.getById(params.id);
    return system.getResultSuccess({
      appid: rs.appid,
      secret: rs.secret,
    });
  }


  /**
   * 商户抬头地址列表
   * @param {*} params 
   */
  async merchantTitleAddrPage(params) {
    try {
      var currentPage = Number(params.currentPage || 1);
      var pageSize = Number(params.pageSize || 10);
      let where = {};
      if (params.merchant_name) {
        where = {
          merchant_name: this.trim(params.merchant_name)
        };
      }
      if (params.saas_merchant_id) {
        where = {
          saas_merchant_id: this.trim(params.saas_merchant_id)
        };
      }
      if (params.saas_id) {
        where = {
          saas_id: this.trim(params.saas_id)
        };
      }
      var orderby = [
        ["id", 'desc']
      ];
      var page = await this.saasmerchanttitleDao.getPageList(currentPage, pageSize, where, orderby);
      if (page && page.rows) {
        for (var row of page.rows) {
          this.handleDate(row, ["created_at"], null, -8);
        }
      }
      return system.getResultSuccess(page);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误`);
    }
  }

  /**
   * 查询发票抬头和地址
   * @param {*} params 
   */
  async queryInvoiceTitleAndAddr(params) {
    if (!params.id) {
      return system.getResult(null, `参数错误 ID不能为空`);
    }
    try {
      let _saasmerchant = await this.dao.getById(this.trim(params.id));
      if (!_saasmerchant) {
        return system.getResult(null, `系统错误 商户不存在`);
      }
      let saas_merchant_title = await this.saasmerchanttitleDao.getAllByMerchantId(_saasmerchant.id);
      let saas_merchant_addr = await this.saasmerchantaddrDao.getAllByMerchantId(_saasmerchant.id);
      let res = {
        saas_merchant_title,
        saas_merchant_addr
      };
      return system.getResult(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误`);
    }
  }

  async updateOrSaveTitleAndAddr(params) {
    if (!params.id) {
      return system.getResult(null, `参数错误 ID不能为空`);
    }
    try {
      let _saasmerchant = await this.dao.getById(this.trim(params.id));
      if (!_saasmerchant) {
        return system.getResult(null, `系统错误 商户不存在`);
      }
      let saas_merchant_title_res = await this.saasmerchanttitleDao.getAllByMerchantId(_saasmerchant.id);
      let saas_merchant_addr_res = await this.saasmerchantaddrDao.getAllByMerchantId(_saasmerchant.id);

      let _saasmerchanttitlePorperty = {saas_merchant_id:_saasmerchant.id, saas_id: _saasmerchant.saas_id};
      if (params.merchant_name) {
        _saasmerchanttitlePorperty.merchant_name = this.trim(params.merchant_name);
      }
      if (params.merchant_credit_code) {
        _saasmerchanttitlePorperty.merchant_credit_code = this.trim(params.merchant_credit_code);
      }
      if (params.merchant_tax_type) {
        _saasmerchanttitlePorperty.merchant_tax_type = this.trim(params.merchant_tax_type);
      }
      if (params.merchant_addr) {
        _saasmerchanttitlePorperty.merchant_addr = this.trim(params.merchant_addr);
      }
      if (params.merchant_mobile) {
        _saasmerchanttitlePorperty.merchant_mobile = this.trim(params.merchant_mobile);
      }
      if (params.merchant_bank) {
        _saasmerchanttitlePorperty.merchant_bank = this.trim(params.merchant_bank);
      }
      if (params.merchant_account) {
        _saasmerchanttitlePorperty.merchant_account = this.trim(params.merchant_account);
      }

      let _saasmerchantaddrPorperty = {saas_merchant_id:_saasmerchant.id, saas_id: _saasmerchant.saas_id};
      if (params.mail_addr) {
        _saasmerchantaddrPorperty.mail_addr = this.trim(params.mail_addr);
      }
      if (params.mail_mobile) {
        _saasmerchantaddrPorperty.mail_mobile = this.trim(params.mail_mobile);
      }
      if (params.mail_to) {
        _saasmerchantaddrPorperty.mail_to = this.trim(params.mail_to);
      }
      let res = await this.db.transaction(async t => {
        if (saas_merchant_title_res.length == 0) {
          await this.saasmerchanttitleDao.create(_saasmerchanttitlePorperty, t);
        } else {
          _saasmerchanttitlePorperty.id = saas_merchant_title_res[0].id;
          await this.saasmerchanttitleDao.update(_saasmerchanttitlePorperty, t);
        }
        if (saas_merchant_addr_res.length == 0) {
          await this.saasmerchantaddrDao.create(_saasmerchantaddrPorperty, t);
        } else {
          _saasmerchantaddrPorperty.id = saas_merchant_addr_res[0].id;
          await this.saasmerchantaddrDao.update(_saasmerchantaddrPorperty, t);
        }
      });
      return system.getResultSuccess(res);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误`);
    }
  }

  /**
   * fn:根据渠道ID查询所有的商户Id
   * @param params
   * @returns {Promise<void>}
   */
  async queryMerchantByChannelId(params) {
    if (!params.channel_id) {
      return system.getResult(null, `参数错误 渠道ID 不能为空`);
    }
    try{
      let ids =await this.dao.queryMerchantByChannelId(params);
      return system.getResult(ids);
    }catch (e) {
      console.log(e);
      return system.getResult(null, `系统错误`);
    }
  }
}
module.exports = SaasMerchantService;