<?php
/**
 * Copy Right IJH.CC
 * Each engineer has a duty to keep the code elegant
 * $Id$
 */
if(!defined('__CORE_DIR')){
    exit("Access Denied");
}
class Ctl_Order extends Ctl
{

    public function index($params)
    {
        $this->items($params);
    }

    public function items($params)
    {
        $this->check_login();
        $filter = array();
        $filter['uid'] = $this->uid;
        $filter['order_status'] = array(-1,0,1,2,8);  // -1:已取消, 0：未处理，1：已接单，2：补差价，4：完成
        $page = max((int) $params['page'], 1);
        $pager['limit'] = $limit = 10;
        if (!$items = K::M('order/order')->items($filter, array('order_id'=>'desc'), $page, $limit, $count)) {
            $items= array();
        }else{
            $staff_ids = $order_ids = array();
            foreach ($items as $k=>$val){
                $staff_ids[$val['staff_id']] = $val['staff_id'];
                $order_ids[$val['order_id']] = $val['order_id'];
            }
            if($staff_ids){
               $staffs = K::M('staff/staff')->items_by_ids($staff_ids);
            }

            $cates = K::M('cate/cate')->fetch_all();
            $jifen = $this->system->config->get('jifen');
            foreach($items as $k=>$val){
                if(!$val['staff_id']){
                    $items[$k]['staffs'] = array('staff_id'=>0);
                }else{
                    $items[$k]['staffs'] = $this->filter_fields('staff_id,mobile,orders,face,name,lat,lng,year_num,comments,score',$staffs[$val['staff_id']]);
                }
                $items[$k]['photo'] = $cates[$val['cate_id']]['photo'];
                $items[$k]['title'] = $cates[$val['cate_id']]['title'];
                $items[$k]['jifen'] = $jifen['jifen_ratio']*($val['amount']- $val['hongbao']);
            }
            foreach ($items as $k=>$val){
                $items[$k] = $this->filter_fields('order_id,cate_id,title,photo,jifen,comment_status,staffs,order_status,pay_status,order_status_label,order_action,addr,house,deposit,dateline', $val);
            }
            
        }
        $this->msgbox->add('success');
        $this->msgbox->set_data('data', array('items'=>array_values($items)));
    }

    public function detail($params)
    {
        $this->check_login();

        if(!$order_id = (int)$params['order_id']){
            $this->msgbox->add('错误的订单ID',211);
        }else if(!$order = K::M('order/order')->detail($order_id)){
            $this->msgbox->add('不存在的订单',212);
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('非法订单',213);
        }else{
            $order = $this->filter_fields('order_id,cate_id,photo,amount,hongbao,hongbao_id,service_time,note,staff_id,deposit,order_status,pay_status,staff_name,staff_mobile,order_status_label,order_action,next,contact,mobile,addr,house,comment_status,dateline', $order);
            if(!$staff = K::M('staff/staff')->detail($order['staff_id'])){
               $order['staffs'] = array('staff_id'=>0);
            }else{
                $staff = $this->filter_fields('staff_id,mobile,face,name,lat,lng,orders,year_num,comments,score',$staff);
                $order['staffs'] = $staff;
            }
            if(!$photos = K::M('order/pics')->items(array('order_id'=>$order_id))){
                $order['pics'] = array();
            }else{
                $order['pics'] = array_values($photos);
            }
            $cates = K::M('cate/cate')->fetch_all();
            $jifen = $this->system->config->get('jifen');
            $order['jifen'] = $jifen['jifen_ratio']*($order['amount']-$order['hongbao']);
            $order['title'] = $cates[$order['cate_id']]['title'];
            $this->msgbox->add('success');
            $this->msgbox->set_data('data', array('items'=>$order));
        }
    }
    
    

    public function create($params)
    {
        $this->check_login();
        if(!$this->uid){
            $this->msgbox->add('您还没有登录!',201);
        }else if(!$cate_id = (int) $params['cate_id']){
            $this->msgbox->add('请正确服务类型!',202);
        }else if(!$addr_id = (int)$params['addr_id']){
            $this->msgbox->add('请选择服务地址',203);
        }else if(!$addr_detail = K::M('member/addr')->detail($addr_id)){
            $this->msgbox->add('服务地址不存在',204);
        }else if(!$params['service_time']){
            $this->msgbox->add('服务时间不能为空!',205);
        }else{
            $cate = K::M('cate/cate')->detail($cate_id);
            $need_deposit = $cate['deposit'];
            if($need_deposit > $params['deposit']){
                $this->msgbox->add('定金金额不正确!',206)->response();
            }
            $staff_id = (int)$params['staff_id'];
            if($staff_id){
                $staff_attr = K::M('staff/attr')->items(array('staff_id'=>$staff_id));
                $attrs = array();
                foreach($staff_attr as $k=>$val){
                    $attrs[] = $val['cate_id'];
                }
                if(!in_array($cate_id, $attrs)){
                    $this->msgbox->add('请选择正确的师傅!',207)->response();
                }
                //$params['order_status'] = 1;
            }
            if(strtotime($params['service_time']) < __TIME){
                $this->msgbox->add('服务时间不正确!',208)->response();
            }
            $params['uid'] = $this->uid;
            $params['contact'] = $addr_detail['contact'];
            $params['mobile'] = $addr_detail['mobile'];
            $params['addr'] = $addr_detail['addr'];    
            $params['house'] = $addr_detail['house'];
            $params['lat'] = $addr_detail['lat'];
            $params['lng'] = $addr_detail['lng'];
            if($order_id = K::M('order/order')->create($params)){
                if($attachs = $_FILES){
                    $upload = K::M('magic/upload');
                    foreach($attachs as $k=>$attach){
                        if($attach['error'] == UPLOAD_ERR_OK){
                            if($a = $upload->upload($attach, 'photo')){
                                K::M('order/pics')->create(array('order_id' => $order_id,'photo' => $a['photo']));
                            }
                        }
                    }
                }
                K::M('order/log')->create(array('order_id'=>$order_id,'from'=>'member','log'=>'订单已提交','type'=>1));
                if($staff_id){
                    K::M('staff/msg')->create(array('staff_id'=>$staff_id,'title'=>'您有新的预约订单','content'=>'您有新的预约订单','is_read'=>0,'order_id'=>$order_id));
                }
                if($staff_id){
                    K::M('staff/staff')->update_count($staff_id, 'orders', 1);
                }
                K::M('member/member')->update_count($this->uid, 'orders', 1);
                $this->msgbox->add('订单提交成功');
                $this->msgbox->set_data('order_id',$order_id);
            }else{
                $this->msgbox->add('订单提交失败!',209);
            }
        }
    }



    public function cancel($params)
    {
        $this->check_login();
        if(!$order_id = (int)$params['order_id']){
            $this->msgbox->add('错误的订单ID',211);
        }else if(!$order = K::M('order/order')->detail($order_id)){
            $this->msgbox->add('不存在的订单',212);
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('你没有权限操作',213);
        }else if($order['order_status'] < 0){
            $this->msgbox->add('订单已经取消，无需重复取消',214);
        }else if($order['order_status'] != 0){
            $this->msgbox->add('当前订单是不可取消的状态',215);
        }else if(K::M('order/order')->cancel($order_id, $order, 'member')){
            $this->msgbox->add('success');
        }else{
            $this->msgbox->add('取消订单失败', 216);            
        }
    }
    
    
    public function setprice($params){ // 用户根据与师傅协商结果填写总订单金额
        $this->check_login();
        if(!$order_id =$params['order_id']){
            $this->msgbox->add('没有订单ID',211);
        }else if(!$order =K::M('order/order')->detail($order_id)){
            $this->msgbox->add('不存在的订单',212);
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('非法订单',213);
        }else if($order['pay_status'] ==1){
           $this->msgbox->add('该订单已支付!',213);
        }else if($order['order_status'] != 2){
           $this->msgbox->add('该订单不能支付!',215);  
        }else if(!$amount = $params['amount']){
            $this->msgbox->add('没有设置订单总价',214);
        }else if(!$amount = (int)$amount){
            $this->msgbox->add('非法的订单总价',215);
        }else {
            if(K::M('order/order')->update($order['order_id'],array('amount'=>$amount, 'order_status'=>2, 'pay_status'=>0))) {
                    if(!$log_id = K::M('order/log')->find(array('order_id'=>$order_id,'type'=>2))){
                        K::M('order/log')->create(array('order_id'=>$order['order_id'], 'log'=>"订单需要补价", 'from'=>'member', 'type'=>2));
                    }else{
                        K::M('order/log')->update($log_id,array('dateline'=>__TIME));
                    }
                    if($order['hongbao_id']){
                        K::M('hongbao/hongbao')->update($order['hongbao_id'],array('order_id'=>0,'used_ip'=>'','used_time'=>0));
                        K::M('order/order')->update($order['order_id'],array('hongbao'=>0, 'hongbao_id'=>0));
                    }
                    $this->msgbox->add('success');
                    $this->msgbox->set_data('data',array('order_status'=>2));
                }
        }
    }
    
    
     public function set_hongbao($params){
        $this->check_login();
        $hongbao_id = (int)$params['hongbao_id'];
        $order_id = (int)$params['order_id'];
        $detail = K::M('hongbao/hongbao')->detail($hongbao_id);
        if(!$order_id){
           $this->msgbox->add('订单不存在!',211);
       }else if(!$order = K::M('order/order')->detail($order_id)){
           $this->msgbox->add('订单不存在!',212);
       }else if($order['uid'] != $this->uid){
           $this->msgbox->add('你没有权限操作该订单!',222);
       }else if($order['pay_status'] ==1){
           $this->msgbox->add('该订单已支付!',213);
       }else if($order['order_status'] != 2){
           $this->msgbox->add('该订单不能支付!',215);  
       }else if($hongbao_id && empty($detail)){
           $this->msgbox->add('红包不存在',216);  
       }else if($hongbao_id && $detail['min_amount'] > $order['amount']){
           $this->msgbox->add('该红包不能使用',217);  
       }else{
           if($order['hongbao_id']){
                K::M('hongbao/hongbao')->update($order['hongbao_id'],array('order_id'=>0,'used_ip'=>'','used_time'=>0));
           }
           if($res = K::M('order/order')->update($order_id, array('hongbao_id'=>$hongbao_id,'hongbao'=>$detail['amount']))){ 
               K::M('hongbao/hongbao')->update($hongbao_id,array('order_id'=>$order_id,'used_time'=>__TIME,'used_ip'=>__IP));
               $this->msgbox->add('操作成功');
           }
       }
    }
    
    public function complete($params){
        $this->check_login();
        $hongbao_id = $params['hongbao_id'];
        $order_id = $params['order_id'];
        $detail = K::M('hongbao/hongbao')->detail($hongbao_id);
        if(!$order_id){
           $this->msgbox->add('订单不存在!',211);
       }else if(!$order = K::M('order/order')->detail($order_id)){
           $this->msgbox->add('订单不存在!',212);
       }else if($order['uid'] != $this->uid){
           $this->msgbox->add('你没有权限操作该订单!',222);
       }else if($order['order_status'] != 2){
           $this->msgbox->add('该订单不能完成!',215);  
       }else if($hongbao_id && empty($detail)){
           $this->msgbox->add('红包不存在',216);  
       }else if($hongbao_id && $detail['min_amount'] > $order['amount']){
           $this->msgbox->add('该红包不能使用',217);  
       }else{
           $chajia = $order['amount'] - $detail['amount'] - $order['deposit'];
           if($chajia <=0){ //判断不需要支付尾款
              if($res = K::M('order/order')->update($order_id, array('hongbao_id'=>$hongbao_id,'hongbao'=>$detail['amount'],'order_status'=>8,'pay_status'=>1))){ 
                  if($hongbao_id){
                    K::M('hongbao/hongbao')->update($hongbao_id, array('order_id'=>$order_id,'used_time'=>__TIME,'used_ip'=>__IP));
                  }
                    if($chajia <0){
                        K::M('member/member')->update_money($this->uid,abs($chajia),'订单(ID:'.$order_id.')服务完成，退还金额');
                    }
              }
               $this->msgbox->add('操作成功');
           }
       }
    }
    
    
    public function comment($params)
    {
        $this->check_login();
        if(!$order_id = (int)$params['order_id']){
            $this->msgbox->add('错误的订单id',211);
        }else if(!$order = K::M('order/order')->detail($order_id)){
            $this->msgbox->add('订单不存在或已经删除',212);
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('您没有权限评价该订单',213);
        }else if($order['status'] < 0){
            $this->msgbox->add('订单已取消不可评价',214);
        }else if($order['order_status'] != 8){
            $this->msgbox->add('订单未完成不可评价',215);
        }else if($order['comment_status']){
            $this->msgbox->add('该订单已经评价过了',216);
        }else if(!$params['score'] || $params['score'] < 1 || $params['score'] > 5){
            $this->msgbox->add('请正确选择评分!',217);
        }else if(!$params['content']){
            $this->msgbox->add('没有填写评价内容!',218);
        }else{
                $data = array(
                'uid'=>$this->uid,
                'staff_id'=>$order['staff_id'],
                'order_id'=>$order_id,
                'content'=>$params['content'],
                'score'=> $params['score'],
            );
            if($file = $_FILES){
                $data['have_photo'] = 1;
            }
                if($comment_id = K::M('staff/comment')->create($data)){
                    if($file){
                        //插入评价
                        foreach($file as $k => $v){ 
                            if($a = K::M('magic/upload')->upload($v,'photo')){
                                $photo_data = array(
                                    'comment_id' => $comment_id,
                                    'photo' => $a['photo']
                                );
                                $photo_id = K::M('staff/photo')->create($photo_data);
                            }
                        }
                    }
                    if($data['score']>3){
                        $update_data = array('comments'=>'`comments`+1','praise_num'=>'`praise_num`+1','score'=>'`score`+'.$data['score']);
                    }else{
                       $update_data = array('comments'=>'`comments`+1','score'=>'`score`+'.$datas['score']); 
                    }
                    K::M('staff/staff')->update($order['staff_id'],$update_data,true);
                    K::M('order/order')->update($data['order_id'],array('comment_status'=>1));
                    $jifen = $this->system->config->get('jifen');
                    $jifen_total = (int)(($order['amount'] - $order['hongbao'])*$jifen['jifen_ratio']);
                    K::M('member/member')->update_jifen($this->uid,$jifen_total,'订单'.$data['order_id'].'评价完成，获得积分');
                    K::M('staff/msg')->create(array('staff_id'=>$order['staff_id'],'title'=>'订单已评价','content'=>'用户('.$order['contact'].')已评价订单(ID:'.$order['order_id'].')','is_read'=>0,'type'=>2,'order_id'=>$order['order_id']));
                    $this->msgbox->add('评价成功!');
                }else{
                    $this->msgbox->add('评价失败!',220);
                }  
        }
    }
    
    
     public function delete($params)
    {
        $this->check_login();
        if(!$order_id = (int)$params['order_id']){
            $this->msgbox->add('错误的订单ID',211);
        }else if(!$order = K::M('order/order')->detail($order_id)){
            $this->msgbox->add('不存在的订单',212);
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('你没有权限操作',213);
        }else if($order['order_status'] != (-1) || $order['order_status'] != 8){
            $this->msgbox->add('订单为不可删除状态',214);
        }else if(K::M('order/order')->delete($order_id)){
            $this->msgbox->add('success');
        }else{
            $this->msgbox->add('取消订单失败', 216);            
        }
    }
    
    

    //用户申请退单，需要商家/管理员同意后才能取消订单
    public function tuidan($params)
    {

    }

    public function confirm($params)
    {
        $this->check_login();
        if(!$order_id = (int)$params['order_id']){
            $this->msgbox->add('错误的订单ID',211);
        }else if(!$order = K::M('order/order')->detail($order_id)){
            $this->msgbox->add('不存在的订单',212);
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('你没有权限操作',213);
        }else if($order['order_status'] == 8){
            $this->msgbox->add('订单已经确认,无需重复确认',214);
        }else if(!in_array($order['order_status'], array(3, 4))){
            $this->msgbox->add('商家还未配送完成不可确认',215);
        }else if(K::M('order/order')->confirm($order_id, $order, 'member')){
            $this->msgbox->add('success');
        }else{
            $this->msgbox->add('订单确认完成失败',216);
        }
    }

    public function complaint($params)
    {
        $this->check_login();
        if(!$order_id = (int)$params['order_id']){
            $this->msgbox->add('订单不存在',211);
        }else if(!$order_detail = K::M('order/order')->detail($order_id)){
            $this->msgbox->add('订单不存在',212);
        }else if($order_detail['uid'] !=$this->uid){
            $this->msgbox->add('订单不正确',213);
        }else if(!$title = $params['title']){
            $this->msgbox->add('投诉类型不能为空',214);
        }else if(!$content = $params['content']){
            $this->msgbox->add('投诉内容不能为空',214);
        }else{
            $data = array(
                'order_id' => $order_id,
                'uid'      => $this->uid,
                'shop_id'  => $order_detail['shop_id'],
                'staff_id' => $order_detail['staff_id'],
                'title'    => $title,
                'content'  => $content
            );
            if($complaint_id = K::M('order/complaint')->create($data)){
                $this->msgbox->add('success');
                $this->msgbox->set_data('data', array('complaint_id'=>$complaint_id));
            }
        }
    }

}
