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

/**
 * 订单产品表
 */
class IinvoicestatusService extends ServiceBase {
  constructor() {
    super("invoice", ServiceBase.getDaoName(IinvoicestatusService));

    this.iinvoicesummaryinfoDao = system.getObject("db.invoice.iinvoicesummaryinfoDao");
    this.iinvoiceprocessDao = system.getObject("db.invoice.iinvoiceprocessDao");
    this.iinvoiceinforegDao = system.getObject("db.invoice.iinvoiceinforegDao");
    this.iinvoicedeliverDao = system.getObject("db.invoice.iinvoicedeliverDao");
    this.iproductDao = system.getObject("db.product.iproductDao");
    this.iprocessDao = system.getObject("db.product.iprocessDao");
    this.iproductprocessDao = system.getObject("db.product.iproductprocessDao");
    this.PALTFORM_DELIVER_AUDIT_SUCCESS_CODE="1070";
    this.PALTFORM_DELIVER_AUDIT_FILE_CODE="1080";
    this.RULE_INVOICE_TYPE =["10",'20','30'];      //发票类型
    this.RULE_BUSINESSMEN_TYPE=['10','20'];        //销售方类型
    this.RULE_INVOICE_JOIN=['10','20','30','40'];  //发票联次
  }

  /***************************************以下是订单处理的分发器***************************************************************** */

  /**
   * 验证订单状态
   * @param params
   * @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}>}
   * @id   订单ID
   * @status 订单下一个状态
   * @other  其他参数
   */
  async handleStatus(params) {
    try {
      let _invoice = await this.dao.findById(this.trim(params.invoice_id ));
      if (!_invoice) {
        return system.getResult(null, `发票不存在`);
      }

      let _invoiceStatus = await this.getInvoiceProcessStatus(_invoice.id, _invoice.status);
      let nextList = JSON.parse(_invoiceStatus.next_status);
      _invoiceStatus.next_status = nextList;
      let flag = false;
      let nextNames = [];
      let nextName = "";
      for (var nextItem of nextList) {
        nextNames.push(nextItem.next_name);
        if (nextItem.next_status == params.status) {
          flag = true;
          nextName = nextItem.next_name;
          break;
        }
      }
      if (!flag) {
        nextNames = nextNames.join("或");
        return system.getResult(null, `订单状态错误，下一订单状态应该是${nextNames}`);
      }

      params._invoice = _invoice;
      params._invoiceStatus = _invoiceStatus;
      params.nextName = nextName;
      //调用对应的方法 TODO SOMETHING .....

      // 调用func
      return await this[_invoiceStatus.func](params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }

  }


  /**
   * 获取订单状态对象
   * @param order_id
   * @param status
   * @returns {Promise<*|{}>}
   */
  async getInvoiceProcessStatus(invoice_id, status) {
    let map = await this.iinvoiceprocessDao.mapByInvoiceIdsAndStatus([invoice_id], [status]);
    return map[invoice_id + "_" + status] || {};
  }

  /*******************************以下是订单处理进度（平台）**************************************************** */

  /**
   * 完善信息
   * @param {*} params 
   * @contract
   * @status
   * @invoice_id
   */
  async perfectInformation(params){
    if(!params.invoice_id){
      return system.getResult(null,`发票ID不能为空`);
    }
    if(!params.contract){
      return system.getResult(null,`合同不能为空`);
    }
    try {
      let  _invoice =  await this.findById(this.trim(params.invoice_id));
      if(!_invoice){
        return system.getResult(null,`发票不存在`);
      }
      _invoice.contract= this.trim(params.contract);
      _invoice.status = this.trim(params.status);
      await _invoice.save();
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 分配业务员
   * @param {*} params
   * @invoice_id     String  订单ID
   * @bd_id  String  业务员ID
   * @status String 下一个状态码
   * @bd_path String 业务员权限
   */
  async platformAassignSalesman(params) {
    if (!params.bd_id) {
      return system.getResult(null, `参数错误 业务员ID不能为空`);
    }
    try {
      //更新订单业务员
      let _invoice = await this.findById(this.trim(params.invoice_id));
      if (!_invoice) {
        return system.getResult(null, `发票不存在不存在`);
      }
      _invoice.bd_id = this.trim(params.bd_id);
      _invoice.status = this.trim(params.status);
      _invoice.bd_path = this.trim(params.bd_path);
      await _invoice.save();
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 分配交付商
   * @param {*} params
   * @id  String 订单ID
   * @deliver_id String 交付商ID
   * @deliver_name String 交付商名称
   * @deliver_deliver String 交付商分成
   * @status String 下一个状态码 
   */
  async assignDeliver(params) {
    //参数验证
    if (!params.invoice_id) {
      return system.getResult(null, `参数错误 发票ID不能为空`);
    }
    if (!params.deliver_id) {
      return system.getResult(null, `参数错误 交付商ID不能为空`);
    }
    if (!params.hasOwnProperty(`deliver_delive`)) {
      return system.getResult(null, `参数错误 交付商分成不能为空`);
    }

    try {
      let self = this;
      await this.db.transaction(async t => {
        //创建invoicedeliver记录
        let _iinvoicedeliver = await self.iinvoicedeliverDao.create({
          invoice_id: self.trim(params.invoice_id),
          deliver_id: self.trim(params.deliver_id),
          deliver_name: self.trim(params.deliver_name),
          deliver_delive: self.trim(params.deliver_delive),
        }, t);

        //更新iinvoice发票记录
        await self.dao.update({
          deliver_id:self.trim(params.deliver_id),
          id: self.trim(params.invoice_id),
          status: self.trim(params.status),
          invoice_deliver_id:_iinvoicedeliver.id
        }, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 平台交付审核（审核成功OR失败）
   * @param {*} params 
   * @invoice_id String 订单ID
   * 
   */
  async deliverAudit(params) {
    let iinvoiceinforegProperty = {};
    if (this.trim(params.status) == this.PALTFORM_DELIVER_AUDIT_SUCCESS_CODE) { //成功
      if (!params.audit_content) {
        return system.getResult(null, `参数错误 交付审核备注不能为空`);
      }
      if (!params.deliver_content) {
        return system.getResult(null, `参数错误 交付内容注不能为空`);
      }
      if (!params.deliver_mail_addr) {
        return system.getResult(null, `参数错误 交付地址不能为空`);
      }
      if (!params.deliver_mail_to) {
        return system.getResult(null, `参数错误 收件人不能为空`);
      }
      if (!params.deliver_mail_mobile) {
        return system.getResult(null, `参数错误 联系电话不能为空`);
      }
      iinvoiceinforegProperty.audit_content = this.trim(params.audit_content);
      iinvoiceinforegProperty.deliver_content = this.trim(params.deliver_content);
      iinvoiceinforegProperty.deliver_mail_addr = this.trim(params.deliver_mail_addr);
      iinvoiceinforegProperty.deliver_mail_to = this.trim(params.deliver_mail_to);
      iinvoiceinforegProperty.deliver_mail_mobile = this.trim(params.deliver_mail_mobile);
      iinvoiceinforegProperty.audit_result = "审核成功";
    } else if (this.trim(params.status) == this.PALTFORM_DELIVER_AUDIT_FILE_CODE) {//失败
      // todo somthing...

      if (!this.trim(params.audit_content)) {
        return system.getResult(null, `参数错误 交付审核备注不能为空`);
      }
      iinvoiceinforegProperty.audit_content = this.trim(params.audit_content);
      iinvoiceinforegProperty.audit_result = "审核失败";
    } else {
      return system.getResult(null, `参数错误 非法的订单状态`);
    }
    iinvoiceinforegProperty.id = params._invoice.id;
    let iinvoiceProperty = {};
    iinvoiceProperty.id = params.invoice_id;
    iinvoiceProperty.status = this.trim(params.status);

    try {
      let self = this;
      await this.db.transaction(async t => {
        //更新交付orderdeliver记录
        await self.iinvoiceinforegDao.update(iinvoiceinforegProperty, t);
        //更新oorder订单记录
        await self.dao.update(iinvoiceProperty, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }


  /**
   * 平台验收
   * @param {*} params 
   */
  async deliveryAcceptance(params) {
    if(!params.province){
      return system.getResult(null,`发票省份不能为空`);
    }
    if(this.RULE_INVOICE_TYPE.indexOf(this.trim(params.invoice_type)) ==-1){
      return system.getResult(null,`发票类型不存在`);
    }
    if(this.RULE_INVOICE_JOIN.indexOf(this.trim(params.invoice_join)) ==-1){
      return system.getResult(null,`发票联次不存在`);
    }
    if(!params.invoice_no){
      return system.getResult(null,`发票号码错误`);
    }
    if(!params.invoice_number){
      return system.getResult(null,`开票内不能为空`);
    }
    if(!params.invoice_time){
      return system.getResult(null,`开票日期不能为空`);
    }
  
    if(!params.merchant_name){
      return system.getResult(null,`购买方名称不能为空`);
    }
    if(!params.merchant_credit_code){
      return system.getResult(null,`购买方社会统一信用代码不能为空`);
    }
    if(!params.merchant_addr){
      return system.getResult(null,`购买方地址不能为空`);
    }
    if(!params.merchant_mobile){
      return system.getResult(null,`购买方电话不能为空`);
    }
    if(!params.merchant_bank){
      return system.getResult(null,`购买方开户行不能为空`);
    }
    if(!params.merchant_account){
      return system.getResult(null,`购买方对公账户不能为空`);
    }
    

    if(!params.businessmen_name){
      return system.getResult(null,`销售方名称不能为空`);
    }
    if(!params.businessmen_credit_code){
      return system.getResult(null,`销售方社会统一信用代码不能为空`);
    }
    if(!params.businessmen_addr){
      return system.getResult(null,`销售方地址不能为空`);
    }
    if(!params.businessmen_mobile){
      return system.getResult(null,`销售方电话不能为空`);
    }
    if(!params.businessmen_bank){
      return system.getResult(null,`销售方开户行不能为空`);
    }
    if(!params.businessmen_account){
      return system.getResult(null,`销售方对公账户不能为空`);
    }
    let _invoice= params._invoice;
    let _iinvoicesummaryinfoBean = await this.iinvoicesummaryinfoDao.findById(_invoice.id);
    if(!_iinvoicesummaryinfoBean){
      return system.getResult(null, `系统错误 ，当前摘要信息不存在`);
    }
    let _iinvoicesummaryinfoProperty = {};
    _iinvoicesummaryinfoProperty.province = this.trim(params.province);
    _iinvoicesummaryinfoProperty.invoice_type = this.trim(params.invoice_type);
    _iinvoicesummaryinfoProperty.invoice_join = this.trim(params.invoice_join);
    _iinvoicesummaryinfoProperty.invoice_no = this.trim(params.invoice_no);
    _iinvoicesummaryinfoProperty.invoice_number = this.trim(params.invoice_number);
    _iinvoicesummaryinfoProperty.invoice_time = this.trim(params.invoice_time);

    
    _iinvoicesummaryinfoProperty.merchant_name = this.trim(params.merchant_name);
    _iinvoicesummaryinfoProperty.merchant_credit_code = this.trim(params.merchant_credit_code);
    _iinvoicesummaryinfoProperty.merchant_addr = this.trim(params.merchant_addr);
    _iinvoicesummaryinfoProperty.merchant_mobile = this.trim(params.merchant_mobile);
    _iinvoicesummaryinfoProperty.merchant_bank = this.trim(params.merchant_bank);
    _iinvoicesummaryinfoProperty.merchant_account = this.trim(params.merchant_account);

    
    _iinvoicesummaryinfoProperty.businessmen_credit_code = this.trim(params.businessmen_credit_code);
    _iinvoicesummaryinfoProperty.businessmen_name = this.trim(params.businessmen_name);
    _iinvoicesummaryinfoProperty.businessmen_addr = this.trim(params.businessmen_addr);
    _iinvoicesummaryinfoProperty.businessmen_mobile = this.trim(params.businessmen_mobile);
    _iinvoicesummaryinfoProperty.businessmen_bank = this.trim(params.businessmen_bank);
    _iinvoicesummaryinfoProperty.businessmen_account = this.trim(params.businessmen_account);

    _iinvoicesummaryinfoProperty.summary = JSON.stringify(params.summary) ;
    
    _iinvoicesummaryinfoProperty.id = _invoice.id;

    let _invoiceProperty={};
    _invoiceProperty.status = this.trim(params.status);
    _invoiceProperty.id = _invoice.id; 
    try {
      await this.db.transaction(async t=>{
        await this.dao.update(_invoiceProperty,t);
        await this.iinvoicesummaryinfoDao.update(_iinvoicesummaryinfoProperty,t);
      });
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }


  /**
   * 客户交付
   * @param {*} params 
   */
  async deliveryCustomer(params) {
    if (!params.deliver_mail_no) {
      return system.getResult(null, `参数错误 客户快递单号不能为空`);
    }

    let iivoiceInforegProperty = {};
    iivoiceInforegProperty.id = this.trim(params.invoice_id);
    iivoiceInforegProperty.deliver_mail_no = this.trim(params.deliver_mail_no);
    let iinvoiceProperty = {};
    iinvoiceProperty.status = this.trim(params.status);
    iinvoiceProperty.id = params._invoice.id;
    try {
      await this.db.transaction(async t => {
        await this.iinvoiceinforegDao.update(iivoiceInforegProperty, t);
        await this.dao.update(iinvoiceProperty, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 订单完成
   * @param {*} params 
   */
  async completed(params) {
    let _invoice = params._invoice;
    _invoice.status = this.trim(params.status);
    try {
      _invoice.save();
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }





  /**********************************以下是交付商订单业务处理******************************************************** */

  /**
   * 分配业务员(交付商)
   * @param {*} params
   * @id     String  订单ID
   * @operator_id  String  业务员ID
   * @status String 下一个状态码
   */
  async deliverAssignSalesman(params) {
    if (!params.operator_id) {
      return system.getResult(null, `参数错误 业务员ID不能为空`);
    }
    try {
      let _iinvoicedeliver = await this.iinvoicedeliverDao.model.findOne({
        where: {
          invoice_id: this.trim(params._invoice.id)
        }
      });
      if (!_iinvoicedeliver) {
        return system.getResult(null, `参数错误 订单交付信息不存在`);
      }
      let invoicedeliverProperty = {};
      invoicedeliverProperty.operator_id = this.trim(params.operator_id);
      invoicedeliverProperty.id = _iinvoicedeliver.id;

      let invoiceProperty = {};
      invoiceProperty.status = this.trim(params.status);
      invoiceProperty.id = this.trim(params._invoice.id);
      await this.db.transaction(async t => {
        await this.iinvoicedeliverDao.update(invoicedeliverProperty, t);
        await this.dao.update(invoiceProperty, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 已经开具发票
   * @param {*} params 
   * @invoice
   */
  async invoiced(params){
    let _invoice = params._invoice;
    if(!params.invoice_no){
      return system.getResult(null,`发票代码不能为空`);
    }
    if(!params.invoice_img){
      return system.getResult(null,`发票图片不能为空`);
    }
    if(!params.invoice_time){
      return system.getResult(null,`发票时间不能为空`);
    }
    if(!params.invoice_number){
      return system.getResult(null,`发票号码不能为空`);
    }
    _invoice.invoice_no = this.trim(params.invoice_no);
    _invoice.invoice_img = this.trim(params.invoice_img);
    _invoice.invoice_time = this.trim(params.invoice_time);
    _invoice.invoice_number = this.trim(params.invoice_number);
    _invoice.status = this.trim(params.status);
    try {
      await _invoice.save();
      return system.getResultSuccess();
    } catch (error) {
      console.log( error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 交付商提交审核
   * @param {*} params 
   * @id  订单ID 
   * @status String 下一个订单状态
   */
  async submitAudit(params) {
    let _invoice = params._invoice;
    _invoice.status = this.trim(params.status);
    try {
      await _invoice.save();
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 交付商交付
   * @param {*} params
   * @invoice_id     String 订单ID
   * @status String 订单状态
   */
  async delivered(params) {

    if (!params.deliver_mail_no) {
      return system.getResult(null, `参数错误 交付商交付快递单号不能为空`);
    }
    if (!params.deliver_img) {
      return system.getResult(null, `参数错误 交接单图片不能为空`);
    }
    let iinvoiceDeliverProperty = {};
    iinvoiceDeliverProperty.deliver_mail_no = this.trim(params.deliver_mail_no);
    iinvoiceDeliverProperty.deliver_img = this.trim(params.deliver_img);

    let _invoice = params._invoice;
    iinvoiceDeliverProperty.id = _invoice.deliver_id;

    let invoiceProperty = {};
    invoiceProperty.status = this.trim(params.status);
    invoiceProperty.id = _invoice.id;

    try {
      await this.db.transaction(async t => {
        await this.iinvoicedeliverDao.update(iinvoiceDeliverProperty, t);
        await this.dao.update(invoiceProperty, t);
      });
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息${error}`);
    }
  }

  /**
   * 平台审核失败
   * @param {*} params 
   */
  async deliverReject(params) {
    try {
      await this.invoiced(params);
      return system.getResultSuccess();
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息${error}`);
    }
  }

  async businessCompletion(params) {
    try {
      let _invoice = params._invoice;
      _invoice.status = this.trim(params.status);
      await _invoice.save();
      return system.getResult(_invoice);
    } catch (error) {
      console.log(error);
      return system.getResult(null,`系统错误 错误信息${error}`);
    }
  }
}

module.exports = IinvoicestatusService;