<?php
include_once(CORE_DIR.'/api/ome/func.php');

class api_delivery extends shop_api_object {
    
    // 创建发货单、退货单
    function create($data){
        $status = strtolower($data['status']);
        if ( 'ready' != strtolower($status) ) {
            $this->api_response('fail','data fail',null,'订单状态应是Ready');
        }
        
        $order_id = $data['order_id'];
        
        $order = $this->db->selectrow('SELECT status,ship_status FROM sdb_orders WHERE order_id='.$this->db->quote($order_id));
        if ( !$order || 'active' != $order['status'] ) {
            $this->api_response('fail','data fail',null,'订单不存在或不再活动');
        }
        if (  SHIPMENT_SHIPOUT === +$order['ship_status'] ) {
            $this->api_response('fail','data fail',null,'订单已全部发货');
        }
        if (  SHIPMENT_RETURN === +$order['ship_status'] ) {
            $this->api_response('fail','data fail',null,'订单已退货');
        }
        
        if ( !$delivery_id = $data['delivery_id'] ) {
            $this->api_response('fail','data fail',null,'缺少发货单号');
        }
        $delivery_ = $this->db->selectrow('SELECT delivery_id FROM sdb_delivery WHERE delivery_id='.$delivery_id);
        if ( $delivery_ ) {
            $this->api_response('fail','data fail',null,'发货单已存在');
        }
        
        if ( !$member=$this->db->selectrow('SELECT member_id,uname FROM sdb_members WHERE uname='.$this->db->quote($data['member_id'])) ) {
            $this->api_response('fail','data fail',null,'会员不存在');
        }
        if ( $member['uname'] != $data['member_id'] ) {
            $this->api_response('fail','data fail',null,'订单不属于会员');
        }
        
        if ( !$items = json_decode($data['delivery_item'],true) ) {
            $this->api_response('fail','data fail',null,'没有发货商品');
        } unset($data['delivery_item']);
        
        // 检查商品 及其 库存
        $products_ = $this->db->select('SELECT bn,product_id,nums,sendnum FROM sdb_order_items WHERE order_id='.$this->db->quote($order_id));
        foreach( $products_ as $v ) {
            $products[$v['bn']] = $v;
        } unset($products_);
        
        foreach( $items as $item ) {
            $bn = $item['product_bn'];
            if ( !array_key_exists($item['product_bn'],$products) ) {
                $this->api_response('fail','data fail',null,'商品不存在:'.$bn);
            }
            if ( (+$products[$bn]['nums'] - $products[$bn]['sendnum']) < +$item['number'] ) {
                $this->api_response('fail','data fail',null,'发货数量大于下单数量:'.$bn);
            }
            
            // 生成发货记录 sdb_delivery_item
            $log = array(
                'delivery_id'=>$delivery_id,'item_type'=>$item['item_type'],
                'product_id'=>+$products[$bn]['product_id'],'product_bn'=>$item['product_bn'],
                'product_name'=>$item['product_name'],'number'=>$item['number'],
            );
            $this->db->insert('sdb_delivery_item', $log);
        }
        
        $ship_address = "mainland:{$data['ship_state']}/{$data['ship_city']}";
        // 生成发货单
        $delivery = array(
            'delivery_id'=>$delivery_id,
            'order_id'=>$order_id,
            'member_id'=>$member['member_id'],
            'status'=>$status,
            'logi_no'=>$data['logi_no'],
            'logi_id'=>$data['logi_id'],
            'logi_name'=>$data['logi_name'],
            
            'ship_name'=>$data['ship_name'],
            'ship_name'=>$data['ship_mobile'],
            'ship_tel'=>$data['ship_tel'],
            'ship_zip'=>$data['ship_zip'],
            'delivery'=>$data['delivery'],
            'ship_area'=>$ship_address,
            //'ship_name'=>$data['ship'],
        );
        $this->db->insert('sdb_delivery',$delivery);
        
        $this->api_response('true',null,'发货单创建成功');
    }
    
    // 仅修改发货单：物流公司,物流单号,发货状态
    function update($data) {
        if ( !$delivery_id = $data['delivery_id'] ) {
            $this->api_response('fail','data fail',null,'缺少发货单号');
        }
        $delivery_ = $this->db->selectrow("SELECT order_id,type,status FROM sdb_delivery WHERE disabled='false' AND delivery_id=".$this->db->quote($delivery_id));
        if ( !$delivery_ ) {
            $this->api_response('fail','data fail',null,'发货单不存在');
        }
        
        if( !$status = strtolower($data['ship_status']) ) { // 只修改物流单号
            $logi_id = $this->db->quote($data['logi_id']);
            $logi_no = $this->db->quote($data['logi_no']);
            $logi_name = $this->db->quote($data['logi_name']);
            $this->db->query("UPDATE sdb_delivery SET logi_id=$logi_id,logi_no=$logi_no,logi_name=$logi_name WHERE delivery_id=".$this->db->quote($delivery_id));
            $this->api_response('true',null,'修改物流信息成功');
        }
        
        if ( !in_array($status, array('succ','cancel','progress')) ) {
            $this->api_response('fail','data fail',null,'发货状态必须是:succ,cancel,progress');
        }
        
        $order_id = $delivery_['order_id'];
        
        if ( 'cancel' == $status ) {
            if ( 'succ' == $delivery_['status'] ) {
                $this->api_response('fail','data fail',null,'发货单已发货');
            }
            if ( 'cancel' == $delivery_['status'] ) {
                $this->api_response('fail','data fail',null,'发货单已取消');
            }
            $this->db->query('UPDATE sdb_delivery SET status="cancel" WHERE delivery_id='.$this->db->quote($delivery_id));
            $this->api_response('true',null,'发货单取消成功');
        }
        
        // 修改 sdb_order_items
        $items = $this->db->select('SELECT product_id,number FROM sdb_delivery_item WHERE delivery_id='.$this->db->quote($delivery_id));
        if ( !$items ) {
            $this->api_response('fail','system error',null,'发货单数据丢失');
        }
        foreach( $items as $item ) {
            $sendnum_ = +$item['number'];
            $product_id = +$item['product_id'];
            $this->db->query("UPDATE sdb_order_items SET sendnum=sendnum+$sendnum_ WHERE product_id=$product_id AND order_id=".$this->db->quote($order_id));
        }
        
        // 检查是否部分发货 如果订单cancel则要保证跟新 sdb_order_items
        $products_ = $this->db->select('SELECT 1 FROM sdb_order_items WHERE nums-sendnum>0 AND order_id='.$this->db->quote($order_id));
        if ( $products_ ) {
            $ship_status = SHIPMENT_SHIPOUT_PART;
        } else {
            $ship_status = SHIPMENT_SHIPOUT;
        }
        
        // 更新订单发货状态
        $now = NOW;
        $this->db->query("UPDATE sdb_orders SET ship_status='$ship_status',last_change_time=$now WHERE order_id=".$this->db->quote($order_id));
        
        $orderMdl = $this->system->loadModel('trading/order');
        // 订单日志
        $orderMdl->_info['order_id'] = $order_id;
        $orderMdl->addLog('发货',null,null,'订单发货');
        
        $this->system->loadModel('trading/order')->fireEvent('editorder',array('order_id'=>$order_id));
        
        $this->api_response('true',null,'发货成功');
    }

    /**
     * 发货时添上订单操作记录
     * add by hujianxin
     *
     * @param bigint $dealer_order_id
     * @param int $delivery_id，
     * @return boolean
     */
    function _add_order_log($dealer_order_id,$delivery_id){
        if(!$delivery_id){
            $this->api_response('true','data true',$result,'发货单不存在');
        }
        $message_part1 = "";
        $message = "";
        $behavior = "";
        $order_info = $this->db->selectrow("SELECT ship_status FROM sdb_orders WHERE order_id=".$this->db->quote($dealer_order_id));
        $ship_status = $order_info['ship_status'];        
        $delivery_info = $this->db->selectrow("SELECT logi_name,logi_no FROM sdb_delivery WHERE delivery_id=".$this->db->quote($delivery_id));
        
        if( $ship_status == SHIPMENT_SHIPOUT ){   //全部发货
            $message_part1 = "发货完成";
            $behavior = "发货";
        }else if( $ship_status == SHIPMENT_SHIPOUT_PART ){    //部分发货
            $message_part1 = "已发货";
            $behavior = "发货";
        }else if( $ship_status == SHIPMENT_RETURN_PART ){  //部分退货
            $message_part1 = "已退货";
            $behavior = "退货";
        }else if( $ship_status == SHIPMENT_RETURN ){   //全部退货
            $message_part1 = "退货完成";
            $behavior = "退货";
        }
  
        if(empty($behavior)) return false;
        $message = "订单<!--order_id=".$dealer_order_id."&delivery_id=".$delivery_id."&ship_status=".$ship_status."-->".$message_part1;
        if(!empty($delivery_info['logi_name'])){
            $message .= "，物流公司：".$delivery_info['logi_name'];
        }
        if(!empty($delivery_info['logi_no'])){
            $message .= "，物流单号：".$delivery_info['logi_no'];
        }
        $log_text = array(
            'message' => $message,
            'logi_no' => $delivery_info['logi_no'],
            'logi_name' => $delivery_info['logi_name']
        );
        $$this->orderMdl->_info['order_id'] = $dealer_order_id;
        return $this->orderMdl->addLog(serialize($log_text),null,null,$behavior);        
    }
}
