<?php
/**
 * Rocky Zhang 2012.5.28
*/
define('OME_NO_QUEUE', 1);

class ome_order_listener {
    function __construct() {
        $this->system =& $GLOBALS['system'];
        $this->matrixMdl = $this->system->loadModel('system/matrix');
        $this->queueMdl = $this->system->loadModel('plugins/ome/ome_queue');
        
        include_once dirname(__FILE__).'/ome_mdl_matrix.php';
        $this->matrix_ = new ome_mdl_matrix();
    }

    // 订单操作：下单、支付、退款、编辑都同步所有订单数据
    function order_to_ome($event,$order,$async=true) {
        if( !$order || !($order_id=$order['order_id']) ) {
            return;
        }
        if ( $order['ome_sync_flag']&&$event !='addmemo' ) {
            return;
        }
        // 订单数据
        $data = $this->matrixMdl->format_matrix_trade($order_id);
        
        // 数据日志
        $queue_id = $this->queueMdl->add($data,$order_id,'order','store.trade.add');
        if ( $async ) {
            $resp = $this->matrix_->push_async($queue_id,$data,'store.trade.add');
        } else {
            $resp = $this->matrix_->push_sync($queue_id,$data,'store.trade.add');
        }
        $this->queueMdl->update($queue_id,$resp);
        return $resp;
    }
    
    function aftersale_to_ome($event,$aftersale){
        if ( !$return_id = $aftersale['return_id'] ) {
            return;
        }
        
        if ( !$data = $this->matrixMdl->format_matrix_aftersale($return_id) ) {
            return;
        }
        
        // 数据日志
        $queue_id = $this->queueMdl->add($data,$return_id,'aftersale','store.trade.aftersale.add');
        
        $resp = $this->matrix_->push_async($queue_id,$data,'store.trade.aftersale.add');
        $this->queueMdl->update($queue_id,$resp);
    }
    
    function refund_to_ome($event,$refund){
        if ( !$data = $this->system->loadModel('system/matrix')->format_matrix_refund($refund['refund_id']) ) {
            return;
        }
        
        $data['memo'] = "#{$refund['ome_refund_id']}#".$data['memo'];
        // 数据日志
        $queue_id = $this->queueMdl->add($data,$refund['refund_id'],'refund','store.trade.refund.add');
        
        $resp = $this->matrix_->push_async($queue_id,$data,'store.trade.refund.add');
        $this->queueMdl->update($queue_id,$resp);
    }
}
