<?php
//发货,订单编辑

class api_order extends shop_api_object {
    function __construct() {
        parent::__construct();
        $this->orderMdl = $this->system->loadModel('trading/order');
    }

    function update_aftersale($aftersale){
        if ( !$this->system->getConf('site.is_open_return_product') ) {
            $this->api_response('fail','data fail',null,'售后申请未开启');
        }
        
        if( !$return_id = (int)$aftersale['return_id'] ) {
            $this->api_response('fail','data fail',null,'缺主键');
        }
        
        $status = +$aftersale['status'];
        if( !in_array($status, array(6,7,8,9)) ) {
            $data['status'] = $status;
        }
        
        $ome_status = array(
            0 => '默认',
            1 => '退货',
            2 => '换货',
            3 => '拒绝',
        );
        $comments_ = (array)json_decode($aftersale['comment'],1);
        foreach($comments_ as $k=>$v){
            $comments[] = array(
                'time'=>NOW,
                'content' => '需'.$ome_status[$status].'商品名:'.$v['name'].',货号:'.$v['bn'].'.需要支付的金额:'.$v['need_money'].',折旧(其他费用)为:'.$v['other_money'].'.<br>',
            );
        }

        $data['comment'] = serialize($comments);
        
        $rs = $this->db->exec("SELECT * FROM sdb_return_product WHERE return_id=$return_id LIMIT 1");
        if ( $sql = $this->db->getUpdateSql($rs,$data,true) ) {
            if ( !$this->db->exec($sql) ) {
                $this->api_response('fail','data fail',$result,'售后申请失败');
            }
        }
        
        $this->api_response('true','data true',$result,'售后申请成功');
    }

    // 拉取订单列表 store.trades.sold.get
    function fetch_order_list($filter){
        // 时间范围过滤
        $dtline = json_decode($filter['dtline'],1);
        if ( isset($dtline[0]) ) {
            $dtline_s =  strtotime($dtline[0]);
            $dtline_e = isset($dtline[1]) ? strtotime($dtline[1]) : NOW+1;
            $sql[] = "((createtime >= $dtline_s AND createtime<=$dtline_e) OR (last_change_time >= $dtline_s AND last_change_time<=$dtline_e))";
        }
        
        // 订单号过滤
        $orders = json_decode($filter['orders'],1);
        if ( $orders ) {
            $orders = array_unique($orders);
            array_splice($orders,100);
            $sql[] = 'order_id IN ("'.implode('","',$orders).'")';
        }
        
        // 订单状态过滤
        $status = json_decode($filter['status'],1);
        if ( $status ) {
            $sql[] = 'status IN ("'.implode('","',$status).'")';
        }
        
        if ( !$sql ) {
            $this->api_response('true','',array());
        }
        
        // 总数统计
        $count = $this->db->select('SELECT COUNT(*) c FROM sdb_orders WHERE '.implode(' AND ', $sql));
        if ( !$count || 0 >= ($count = (int)$count[0]['c']) ) {
            $this->api_response('true','',array());
        }
        
        // 订单列表
        $_offset_ = (int)$filter['_offset_'];
        $_pagesize_ = isset($filter['_pagesize_']) ? (int)$filter['_pagesize_'] : 100;
        
        $matrixMdl = $this->system->loadModel('system/matrix');
        $sql_limit_ = " LIMIT $_offset_,$_pagesize_";
        $sql_limit = " LIMIT ".$_pagesize_*$_offset_.",$_pagesize_";
        
        $sql = 'SELECT order_id,status,pay_status,ship_status,createtime,last_change_time FROM sdb_orders WHERE '.implode(' AND ', $sql).$sql_limit;
        
        foreach( $this->db->select($sql) as $v ) {
            $data[] = array(
                'order_id' => $v['order_id'],
                'status' => $matrixMdl->format_matrix_status_order($v['status']),
                'pay_status' => $matrixMdl->format_matrix_status_payment($v['pay_status']),
                'ship_status' => $matrixMdl->format_matrix_status_shipment($v['ship_status']),
                'modified' => date('Y-m-d H:i:s',max((int)$v['last_change_time'], (int)$v['createtime'])),
            );
        }
        
        $data = array(
            'total_results'=>$count,
            'trades'=>$data,
        );
        
        $this->api_response('true','',$data);
    }
    
    // 拉取订单详细 store.trade.fullinfo.get
    function fetch_order_detail($filter){
        if ( !$order_id = $filter['order_id'] ) {
            $this->api_response('fail','data fail',null,'缺少订单号');
        }
        
        $order = $this->db->selectrow('SELECT order_id FROM sdb_orders WHERE order_id='.$this->db->quote($order_id));
        if ( !$order ) {
            $this->api_response('true','',array());
        }
        
        $matrixMdl = $this->system->loadModel('system/matrix');
        $data['trade'] = $matrixMdl->format_matrix_trade($order_id);
        $this->api_response('true','',$data);
    }
    
    function fetch_order_url($order){
        $order_ = $this->db->selectrow('SELECT order_id FROM sdb_orders WHERE order_id='.$this->db->quote($order['tid']));
        if ( !$order_ ) {
            $this->api_response('fail','data fail',null,'订单不存在');
        }
        
        $_auth_secret = md5(md5(STORE_KEY));
        $url = $this->system->base_url();
        $ome_url = $order['notify_url'];
        $url .= SHOPADMIN_PATH."/index.php?ctl=order/order&act=showEdit&p[0]={$order['tid']}&ome_notify_url=$ome_url&_auth_secret={$_auth_secret}";
        
        $this->api_response('true','',array('url'=>$url));
    }
    
    function set_order_status($data) {
        $order_id = $data['order_id'];
        $order = $this->orderMdl->instance($order_id,'status');
        if ( !$order ) {
            $this->api_response('fail','data fail',null,'订单不存在');
        }
        if ( 'active' != $order['status'] ) {
            $this->api_response('fail','data fail',null,'订单不在active状态');
        }
        
        if ( !$this->orderMdl->toCancel($order_id) ) {
            $this->api_response('fail','system error',null,'系统错误');
        }
        
        $this->api_response('true',null,'取消订单成功');
    }
}
