<?php



class OOrder {

    
    
    
    
    public static function getItemList($order_number){
        global $INI;
        global $login_user_id;
        $condition['order_number'] = $order_number;
        $item = DB::LimitQuery("order_item",array(
            'condition' => $condition,
        ));
        $html = "";
        foreach($item as $one){
            
            $html .= $one['item_number'] . "[" . $one['size'] . "](" . $one['quantity'] . ")<br />\n";
        }
        return $html;
    }
    public static function createFromCart($express) {
        global $INI;
        global $login_user_id;
        global $login_user;

        
        $order = array(); 

        
        $sql = "select a.*,b.cost_discount
                from cart as a,category as b
                where a.user_id='".$login_user_id."' and a.category_id=b.id";
        $cart = DB::GetQueryResult($sql, FALSE);
        
        $tb1 = new Table($INI['db']['profix'] . "order_item");
        foreach ($cart as $one) {
            
            
            if (!isset($order[$one['provider_id']])) {
                $order[$one['provider_id']]['order_number'] = self::genOrderNumber();
                $order[$one['provider_id']]['weight'] = 0;
                $order[$one['provider_id']]['sum'] = 0;

            }

            $tb1->order_number = $order[$one['provider_id']]['order_number'];
            $tb1->provider_id = $one['provider_id'];
            $tb1->category_id = $one['category_id'];
            $tb1->item_id = $one['item_id'];
            $tb1->item_number = $one['item_number'];
            $tb1->quantity = $one['quantity'];
            $tb1->origin = $one['origin'];
            $tb1->size = $one['size'];
            $tb1->weight = $one['weight'];
            $tb1->discount = $one['discount'];
            
            $tb1->cost = $one['cost_discount'];
            $tb1->Insert('order_number','category_id','provider_id', 'item_id','item_number','quantity','origin','size','weight','discount','cost');

            $order[$one['provider_id']]['weight'] += $one['weight'] * $one['quantity'];
            
            $order[$one['provider_id']]['sum'] += mceil($one['origin'] * $one['discount'])* $one['quantity'];
        }
        

        
        $tb = new Table($INI['db']['profix'] . "order_info");
        $on = count($order);
        if($on>1) Session::Set('success',"根据不同供货商，订单被拆分为 ".count($order)." 笔创建，"); 
        foreach ($order as $k => $v) {
            $provider = Table::Fetch('provider', $k);
            $tb->order_number = $v['order_number'];
            $tb->user_id = $login_user_id;
            $tb->state = "unpay";
            $tb->provider_id = $k;
            $tb->realname = $express['real_name'];
            $tb->express_id = $express['express'][$k];
            $tb->mobile = $express['mobile'];
            $tb->phone = $express['phone'];
            $tb->zipcode = $express['zipcode'];
            $tb->province = $express['province'];
            $tb->address = $express['address'];
            $tb->remark = $express['remark'];
            $tb->weight = $v['weight'];
            $tb->fare = OOrder::getFare($express['express'][$k], $provider['province'], $express['province'], $v['weight']);
            $tb->create_time = time();
            $tb->sum = $v['sum'] + $tb->fare;
            $order[$k]['order_id'] = $tb->Insert('order_number', 'user_id', 'state', 'provider_id', 'realname', 'express_id', 'mobile','phone','zipcode', 'province', 'address', 'weight', 'fare', 'remark', 'create_time','sum');
        }
        
    }
    
    public static function genOrderNumber() {
        $order_number = "";

        DB::Query('LOCK TABLES `sys` WRITE');
        $order_number = Table::Fetch('sys', 1);
        $order_number = $order_number['order_number'];
        if (substr($order_number, 0, 8) == date('Ymd')) {
            $order_number = $order_number + 1;
        } else {
            $order_number = date('Ymd') . '001';
        }
        Table::UpdateCache('sys', 1, array('order_number' => $order_number));
        DB::Query('UNLOCK TABLES');
        return $order_number;
    }

    public static function createFromCsv($textCSV) {
        
        
        global $INI;
        global $login_user_id;
        global $login_user;
        $csv = explode("\r\n", $textCSV);
        if(!empty($csv[count($csv)-1])) $csv[count($csv)-1] = ""; 
        $tb = new Table($INI['db']['profix'] . "order_info");
        $tb1 = new Table($INI['db']['profix'] . "order_item");
        $order = array();

        foreach ($csv as $one) {
            if(!empty($one)){
                $one = explode(",", $one);
                $item = OOrder::getItem($one[8], $one[9]);
                $provider = Table::Fetch('provider', $item['provider_id']);
            }
            if (!empty($one[1]) || empty($one)) { 

                
                if(isset($order[$item['provider_id']])){
                    
                    foreach($order as $k => $v) {
                        $provider = Table::Fetch('provider', $k);
                        $tb->order_number = $v['order_number'];
                        $tb->user_id = $login_user_id;
                        $tb->state = "unpay";
                        $tb->provider_id = $k;
                        $tb->realname = $express['real_name'];
                        $tb->express_id = $express['express_id'];
                        $tb->mobile = $express['mobile'];
                        $tb->zipcode = $express['zipcode'];
                        $tb->province = $express['province'];
                        $tb->address = $express['address'];
                        $tb->remark = $express['remark'];
                        $tb->weight = $v['weight'];
                        
                        $tb->fare = OOrder::getFare($express['express_id'], $provider['province'], $express['province'], $v['weight']);
                        $tb->create_time = time();
                        $tb->sum = $v['sum']+$tb->fare;
                        $order[$k]['order_id'] = $tb->Insert('order_number', 'user_id', 'state', 'provider_id', 'realname', 'express_id', 'mobile', 'zipcode', 'province', 'address', 'weight', 'fare', 'remark', 'create_time','sum');
                    }
                    $order = array(); 
                }

                
                if(!empty($one)){
                    $express['express_id'] = $one[7];
                    $express['real_name'] = $one[1];
                    $express['mobile'] = $one[2];
                    $express['zipcode'] = $one[5];
                    $express['province'] = $one[3];
                    $express['address'] = $one[4];
                    $express['remark'] = $one[6];
                }
            }
            
            if(!empty($one)){
                if (!isset($order[$item['provider_id']])) {
                    $order[$item['provider_id']]['order_number'] = self::genOrderNumber();
                    $order[$item['provider_id']]['weight'] = 0;
                    $order[$item['provider_id']]['sum'] = 0;
                }
                
                $tb1->order_number = $order[$item['provider_id']]['order_number'];
                $tb1->item_id = $item['id'];
                $tb1->weight = $item['weight'];
                $tb1->origin = $item['origin'];
                $tb1->quantity = $one[10];

                $season = strtolower(substr($item['season'],-2));
                if(substr($season,0,1)<>'q') $season = 'q1';
                
                $tb1->discount = $provider[$season]+$INI['sys']['level'][$login_user['level']]/100;
                $tb1->Insert('order_number', 'item_id', 'quantity','origin','weight','discount');
                
                $order[$item['provider_id']]['weight'] += $item['weight'] * $one[10];
                $order[$item['provider_id']]['sum'] += $item['origin'] * $one[10] * $tb1->discount;
            }
        }
    }
    public static function getItem($item_number,$size){
        $row = DB::LimitQuery('item',array(
            'condition' => array(
                'item_number'   => $item_number,
                'size'          => $size
            ),
            'size'      => 1
        ));
        return $row[0];
    }
    
    
    
    public static function getFare($express_id, $src, $dest, $weight) {
        
        $condition = "source='".$src."' and destination like '%".$dest."%' and id='".$express_id."'";
        $fare = DB::LimitQuery('fare', array(
                    'condition' => $condition,
                    'size' => 1,
                ));
        if(count($fare)==0){
            $condition = "source='".$src."' and destination like '%一般%' and id='".$express_id."'";
            $fare = DB::LimitQuery('fare', array(
                        'condition' => $condition,
                        'size' => 1,
                    ));
        }
        return $fare[0]['base'] + $fare[0]['add'] * mceil(($weight - 1000) / 1000);
    }
    
    public static function pay($order_number){
        global $login_user;
        global $login_user_id;
        $order_info = Table::Fetch('order_info',$order_number,'order_number');
        if( ($order_info['user_id']!=$login_user_id) && !is_manager() ) exit; 
        $user = OUser::GetUser($order_info['user_id']);
        ($user['id']!=$login_user_id)? $admin_id = $login_user_id : $admin_id=1;
        if($order_info['sum']>$user['money']){
            Session::Set('error','你的余额不足！');
            
            return false;
        }elseif($order_info['state']!="unpay"){
            Session::Set('error','此订单无需再次支付！');
            return false;
        }else{
            $user['money'] = $user['money']-$order_info['sum'];
            DB::Query('LOCK TABLES `user` WRITE,`order_info` WRITE,`flow` WRITE');
            Table::UpdateCache('user', $user['id'], array(
                'money' => $user['money']
            ));
            Table::UpdateCache('order_info', $order_info['id'], array(
                'state' => 'pay',
                'pay_time' => time()
            ));

            OFlow::Create(array(
                'direction'     => 'expense',
                'action'        => 'order',
                'money'         => $order_info['sum'],
                'create_time'   => time(),
                'user_id'       => $user['id'],
                'admin_id'      => $admin_id,
                'detail_id'     => $order_info['order_number'],
                'detail'        => "下单付款"
            ));
            DB::Query('UNLOCK TABLES');
            return true;
        }
    }
    
    public static function update($order_number){
        global $login_user_id;
        
        
        
        
        $order_info = Table::Fetch('order_info',$order_number,'order_number');
        $provider = OProvider::getProvider($order_info['provider_id']);
        
        
        if($order_info['state']=='unpay'){
            
            (mceil(1.2)==2)?$ceil="ceil":$ceil="";
            $sql = "select sum(weight*quantity) as sum_weight,sum(".$ceil."(discount*origin)*quantity) as sum_money from order_item
                    where order_number='".$order_number."'";
            $sum = DB::GetQueryResult($sql);
            $update['weight'] = $sum['sum_weight'];
            $update['fare'] = self::getFare($order_info['express_id'],$provider['province'],$order_info['province'],$sum['sum_weight']);
            $update['sum'] = $sum['sum_money'] + $update['fare'];
            Table::UpdateCache('order_info', $order_info['id'], $update);
        }
        
        
        
        if($order_info['state']=='pay'){
            
            (mceil(1.2)==2)?$ceil="ceil":$ceil="";
            $sql = "select sum(weight*quantity) as sum_weight,sum(".$ceil."(discount*origin)*quantity) as sum_money
                    from order_item
                    where order_number='".$order_number."' and isnull(state)"; 
            $sum = DB::GetQueryResult($sql);
            if(!isset($sum['sum_weight']) || $sum['sum_weight']==0) {
                $update['weight'] =0;
                $update['fare'] =0;
                $update['sum'] =0;
                $update['state'] = "refund";
                Session::Set('success','订单已经全部退款！');
            }else{
                $update['weight'] = $sum['sum_weight'];
                $update['fare'] = self::getFare($order_info['express_id'],$provider['province'],$order_info['province'],$sum['sum_weight']);
                $update['sum'] = $sum['sum_money'] + $update['fare'];
                Session::Set('success','订单更新成功！部分订单已退款！');
            }
            Table::UpdateCache('order_info', $order_info['id'], $update);

            
            $sql = "update order_item set state='refund' where order_number='".$order_number."' and state='refunding'";
            DB::Query($sql);
            $refund = $order_info['sum'] - $update['sum'];
            $sql = "update user set money = money+".$refund." where id=".$order_info['user_id'];
            DB::Query($sql);
            
            OFlow::Create(array(
                'direction'     => 'income',
                'action'        => 'refund',
                'money'         => $refund,
                'create_time'   => time(),
                'user_id'       => $order_info['user_id'],
                'detail_id'     => $order_info['order_number'],
                'detail'        => "订单退款",
                'admin_id'      => $login_user_id   
            ));
        }
        if($order_info['state']=='send'){
            
            (mceil(1.2)==2)?$ceil="ceil":$ceil="";
            $sql = "select sum(weight*quantity) as sum_weight,sum(".$ceil."(discount*origin)*quantity) as sum_money
                    from order_item
                    where order_number='".$order_number."' and state=\"send\""; 
            $sum = DB::GetQueryResult($sql);
            if(!isset($sum['sum_weight']) || $sum['sum_weight']==0) {
                $update['weight'] =0;
                
                $update['sum'] = $order_info['fare'];
                $update['state'] = "refund";
                Session::Set('success','订单已经全部退款！未退运费！');
            }else{
                $update['weight'] = $sum['sum_weight'];
                
                $update['sum'] = $sum['sum_money'] + $order_info['fare'];
                Session::Set('success','订单更新成功！部分订单已退款！未退运费！');
            }
            Table::UpdateCache('order_info', $order_info['id'], $update);

            
            $sql = "update order_item set state='refund' where order_number='".$order_number."' and state='refunding'";
            DB::Query($sql);
            $refund = $order_info['sum'] - $update['sum'];
            $sql = "update user set money = money+".$refund." where id=".$order_info['user_id'];
            DB::Query($sql);
            
            OFlow::Create(array(
                'direction'     => 'income',
                'action'        => 'refund',
                'money'         => $refund,
                'create_time'   => time(),
                'user_id'       => $order_info['user_id'],
                'detail_id'     => $order_info['order_number'],
                'detail'        => "售后退款，不退运费！",
                'admin_id'      => $login_user_id   
            ));
        }

    }
    
    public static function send($order_number,$express_no){
        if(!isset($order_number) || !isset($express_no)) return;
        
        $sql = "update order_info set state='send',express_no='".$express_no."'
                where order_number='".$order_number."'";
        $re = DB::query($sql);
        
        $sql1 = "update order_item set state='send'
                where isnull(state) and  order_number='".$order_number."'";
        $re1 = DB::query($sql1);
        
        $sql2 = "update item as a,order_item as b
                set a.quantity=a.quantity-b.quantity
                where a.id=b.item_id and b.order_number='".$order_number."'";
        $re2 = DB::query($sql2);

        $re = $re & $re1 & $re2;
        
        if($re==false) return false;
        return true;

    }

}


function order_ut1() {
    global $INI;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");
    echo OOrder::getFare(1, '河北', 'DDDD', '2800');
}


function order_ut2() {
    global $INI;
    global $login_user_id;
    $login_user_id = 1;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");

    
    $express['express_id'] = '1';
    $express['real_name'] = '吕建军';
    $express['mobile'] = '15081880198';
    $express['zipcode'] = '050021';
    $express['province'] = '北京';
    $express['address'] = '东风路218号';
    $express['remark'] = '备注';
    OOrder::createFromCart($express);
}


function order_ut3() {
    global $INI;
    global $login_user_id;
    $login_user_id = 1;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");
    echo OOrder::genOrderNumber();
}

function order_ut4(){
    global $INI;
    global $login_user_id;
    $login_user_id = 1;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");
    $item = OOrder::getItem('K2101AK038-518', 'XL');
    echo $item['provider_id'];
}

function order_ut5(){
    global $INI;
    global $login_user_id;
    $login_user_id = 1;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");
    $csvfile = IMG_ROOT . "/porder.csv";
    $csv = file_get_contents($csvfile);
    OOrder::createFromCsv($csv);
}

?>
