<?php
/**
 * Copy Right IJH.CC
 * Each engineer has a duty to keep the code elegant
 * $Id: index.ctl.php 14351 2015-07-22 01:25:14Z wanglei $
 */
if(!defined('__CORE_DIR')){
    exit("Access Denied");
}

class Ctl_Order extends Ctl
{
    // 待处理订单列表
    public function index(){
        $this->check_login();
        $this->tmpl = 'order/items.html';  
    }

    public function items()
    {
        $this->check_login();
        $filter = array();
        $filter['uid'] = $this->uid;
        $filter['order_status'] = array(-1,0,1,2,8);  // -1:已取消, 0：未处理，1：已接单，2：补差价，8：完成
        $page = max((int) $this->GP('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();
            foreach($items as $k=>$val){
                $items[$k]['staff_name'] = $staffs[$val['staff_id']]['name'];
                $items[$k]['staff_mobile'] = $staffs[$val['staff_id']]['mobile'];
                $items[$k]['photo'] = $cates[$val['cate_id']]['photo'];
                $items[$k]['title'] = $cates[$val['cate_id']]['title'];
            }
        }
        //print_r($items);die;
        $this->msgbox->set_data('data', array('items' => array_values($items)));
    }

    public function order($cate_id)
    {   
        $this->check_login();
        $cate_id = (int)$cate_id;
        if(!$cate_id){
            $this->msgbox->add('服务分类不能为空',221);
        }
        $today = date("Y-m-d",time());
        $today_y = date("m-d",time());
        $today_w = date("w",time());
        $week = array();
        $week[0]['d'] = $today;
        $week[0]['y'] = $today_y;
        $week[0]['w'] = $today_w;
        for($i=1;$i<=6;$i++){
                $d = date('Y-m-d',86400*$i+time());
                $y = date('m-d',86400*$i+time());
                $w = date('w',86400*$i+time());
                $week[$i]['d'] = $d;
                $week[$i]['y'] = $y;
                $week[$i]['w'] = $w;
        }
        foreach($week as $k => $v){
            switch ($week[$k]['w']){
            case 0:
              $week[$k]['w'] = "周日";
              break;
            case 1:
              $week[$k]['w'] = "周一";
              break;
            case 2:
              $week[$k]['w'] = "周二";
              break;
           case 3:
              $week[$k]['w'] = "周三";
              break;
           case 4:
              $week[$k]['w'] = "周四";
              break;
           case 5:
              $week[$k]['w'] = "周五";
              break;
           case 6:
              $week[$k]['w'] = "周六";
              break;
            }
        }
        $this->pagedata['week'] = $week;
        $this->pagedata['cates'] = K::M('cate/cate')->fetch_all();
        $this->pagedata['addrs'] = K::M('member/addr')->items(array('uid'=>$this->uid));
        $this->pagedata['maddr'] = K::M('member/addr')->find(array('uid'=>$this->uid,'is_default'=>1));
        $this->pagedata['cate_id'] = $cate_id;
        $this->tmpl = 'order/order.html';  
    }
    
    public function create(){
        $this->check_login();
        $data = $_POST;
        $file = $_FILES;
        if(!$this->uid){
            $this->msgbox->add('您还没有登录!',201);
        }else if(!$cate_id = (int) $data['cate_id']){
            $this->msgbox->add('请正确服务类型!',202);
        }else if(!$addr_id = (int)$data['addr_id']){
            $this->msgbox->add('请选择服务地址',203);
        }else if(!$addr_detail = K::M('member/addr')->detail($addr_id)){
            $this->msgbox->add('服务地址不存在',204);
        }else if(!$data['service_time']){
            $this->msgbox->add('服务时间不能为空!',205);
        }else{
            $cate = K::M('cate/cate')->detail($cate_id);
            $need_deposit = $cate['deposit'];
            if($need_deposit > $data['deposit']){
                $this->msgbox->add('定金金额不正确!',206)->response();
            }
            $staff_id = (int)$data['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();
                }
                //$data['order_status'] = 1;
            }
            if(strtotime($data['service_time']) < __TIME){
                $this->msgbox->add('服务时间不正确!',208)->response();
            }
            $data['uid'] = $this->uid;
            $data['contact'] = $addr_detail['contact'];
            $data['mobile'] = $addr_detail['mobile'];
            $data['addr'] = $addr_detail['addr'];    
            $data['house'] = $addr_detail['house'];
            $data['lat'] = $addr_detail['lat'];
            $data['lng'] = $addr_detail['lng'];
            if($order_id = K::M('order/order')->create($data)){
                if($file){ //订单图片
                    foreach($file as $k => $val){
                        if($a = K::M('magic/upload')->upload($val,'photo')){
                            $photo_data = array(
                                'order_id' => $order_id,
                                'photo' => $a['photo']
                            );
                            $pic_id = K::M('order/pics')->create($photo_data);
                        }
                    }
                }
                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 ($this->MEMBER['wx_openid']) {
                    //获取模版消息配置 --订单已提交
                    $wx_config = $this->system->config->get('wx_config');
                    $config = $this->system->config->get('site');
                    $a = array('title'=>'您的订单已提交！', 'items' => array('OrderSn' => $order_id, 'OrderStatus' => '您的订单已提交'), 'remark' =>'您的订单于 '.date('Y-m-d H:i:s',__TIME).' 提交成功');
                    $url = K::M('helper/link')->mklink('order:detail', array('args'=>$order_id), array(), 'www');
                    K::M('weixin/wechat')->wechat_client($config)->sendTempMsg($this->MEMBER['wx_openid'], $wx_config['order_id'], $url, $a);    
                }
                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 pay($order_id)
    {
       $this->check_login();
       $order_id = (int)$order_id;
       if(!$order_id){
           $this->msgbox->add('订单不存在!',211);
       }else if(!$detail = K::M('order/order')->detail($order_id)){
           $this->msgbox->add('订单不存在!',212);
       }else if($detail['pay_status'] ==1){
           $this->msgbox->add('该订单已支付!',213);
       }else if((!$detail['staff_id']&&$detail['order_status'] >0)||($detail['staff_id']&&$detail['order_status'] >1)){
           $this->msgbox->add('该订单不能支付!',215);
       }
       
       if(defined('IN_WEIXIN')){
           $this->pagedata['weixin'] = 1;
       }
       
        $this->pagedata['detail'] = $detail;
        $this->tmpl = 'order/pay.html';  
    }

    public function pay_all($order_id){
        $this->check_login();
        $amount = $_POST['amount'];
        $order_id = (int)$order_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($amount <=0){
           $this->msgbox->add('订单总额不正确!',216);  
       }else{
           if($res = K::M('order/order')->update($order_id, array('amount'=>$amount,'hongbao_id'=>0,'hongbao'=>0))){ 
               if($order['hongbao_id']){
                    K::M('member/hongbao')->update($order['hongbao_id'],array('order_id'=>0,'used_ip'=>'','used_time'=>0));
                }
               $this->msgbox->add('确认订单金额，下面进行支付');
           }
       }
    }

    
    public function set_hongbao($order_id){
        $this->check_login();
        $hongbao = $_POST['hongbao'];
        $hongbao_id = (int)$_POST['hongbao_id'];
        $order_id = (int)$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($res = K::M('order/order')->update($order_id, array('hongbao_id'=>$hongbao_id,'hongbao'=>$hongbao))){ 
               K::M('hongbao/hongbao')->update($hongbao_id,array('order_id'=>$order_id,'used_time'=>__TIME,'used_ip'=>__IP));
               $this->msgbox->add('操作成功');
           }
       }
    }
    
    public function complete($order_id){
        $this->check_login();
        $hongbao = $_POST['hongbao'];
        $hongbao_id = (int)$_POST['hongbao_id'];
        $order_id = (int)$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'] - $hongbao - $order['deposit'];
           if($chajia <=0){ //判断不需要支付尾款
              if($res = K::M('order/order')->update($order_id, array('hongbao_id'=>$hongbao_id,'hongbao'=>$hongbao,'order_status'=>8,'pay_status'=>1))){ 
                    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 pay2($order_id)
    {
       $this->check_login();
       $order_id = (int)$order_id;
       if(!$order_id){
           $this->msgbox->add('订单不存在!',211);
       }else if(!$detail = K::M('order/order')->detail($order_id)){
           $this->msgbox->add('订单不存在!',212);
       }else if($detail['pay_status'] ==1){
           $this->msgbox->add('该订单已支付!',213);
       }else if($detail['order_status'] !=2){
           $this->msgbox->add('该订单不能支付!',215);
       }
       
       if(defined('IN_WEIXIN')){
           $this->pagedata['weixin'] = 1;
       }
       
        $this->pagedata['detail'] = $detail;
        $this->tmpl = 'order/pay2.html';  
    }

    

    
    
    public function comment($order_id)
    {

        $this->check_login();
        $order_id = (int)$order_id;
        if(!$order_id){
            $this->msgbox->add('订单不能为空!',211);
            $this->msgbox->response();
        }else if(!$order = K::M('order/order')->detail($order_id)){
            $this->msgbox->add('订单不存在!',221);
            $this->msgbox->response();
        }else if($order['order_status'] != 8){
            $this->msgbox->add('订单不可评价!',212);
            $this->msgbox->response();
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('非法操作!',213);
            $this->msgbox->response();
        }else if($order['comment_status'] != 0){
            $this->msgbox->add('订单已经评价过了!',214);
            $this->msgbox->response();
        }else{
            $staff = K::M('staff/staff')->detail($order['staff_id']);
        }
        if($staff['comments']){
            $score = $staff['score']/$staff['comments'];
        }else{
            $score = 3;
        }
        if(!$lng || !$lat){
            $lng = $this->request['UxLocation']['lng'];
            $lat = $this->request['UxLocation']['lat'];
        }
        $juli = K::M('helper/round')->getdistances($staff['lng'], $staff['lat'], $lng, $lat);  //距离
        $score = number_format($score, 1);
        $jifen = $this->system->config->get('jifen');
        $this->pagedata['jifen'] = $jifen['jifen_ratio']*($order['amount']- $order['hongbao']);
        $this->pagedata['juli'] = $juli;
        $this->pagedata['score'] = $score;
        $this->pagedata['staff'] = $staff;
        $this->pagedata['order'] = $order;
        $this->tmpl = 'order/comment.html';  
    }
    
    
    public function comment_handle()
    {
        $this->check_login();
        $data = $_POST['data'];
        $file = $_FILES;
        if(!$this->uid){
            $this->msgbox->add('您还没有登录!',101);
        }else if(!$data['score'] || $data['score'] < 1 || $data['score'] > 5){
            $this->msgbox->add('请正确选择评分!',214);
        }else if(!$data['content']){
            $this->msgbox->add('没有填写评价内容!',215);
        }else if(!$data['order_id']){
            $this->msgbox->add('错误的订单!',216);
        }else if(!$order = K::M('order/order')->detail($data['order_id'])){
            $this->msgbox->add('错误的订单!',216);
        }else if($order['uid'] != $this->uid){
            $this->msgbox->add('非法操作!',216);
        }else{
                $data['staff_id'] = $order['staff_id'];
                $data['uid'] = $this->uid;
                if($file){
                    $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{
                    //print_r($this->system->db->SQLLOG());die;
                    $this->msgbox->add('评价失败!',217);
                }  
        }
    }

    // 订单详情
    public function detail($order_id) 
    {
        $this->check_login();
        if(!$order_id = (int)$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{
            $time = time();
            if($order['dateline']+1800 < $time && $order['order_status'] == 0 && $order['pay_status'] == 0){
                if($order['order_status'] != (-1)){
                  $this->pagedata['reload'] = 1;
                    $this->chargeback($order['order_id']);  
                }
            }
            $this->pagedata['pics'] = K::M('order/pics')->items(array('order_id'=>$order_id)); 
            $this->pagedata['order'] = $order;
            $this->pagedata['jifen'] = $this->system->config->get('jifen');
            $this->pagedata['staff'] = K::M('staff/staff')->detail($order['staff_id']);
            $this->pagedata['cates'] = K::M('cate/cate')->fetch_all();
            $this->tmpl = 'order/detail.html';
        }
        
    } 

    // 申请退单
    public function chargeback($order_id) 
    {
        $this->check_login();
        if(!$order_id = (int)$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('当前订单是不可取消的状态',215);
        }else{
            if(K::M('order/order')->cancel($order_id, $order, 'member')) {
                $data = array(
                    'staff_id'=>$order['staff_id'],
                    'title'=>'订单已取消',
                    'content'=>'用户('.$order['contact'].')已取消订单(ID:'.$order_id.')',
                    'is_read'=>0,
                    'type'=>1,
                    'order_id'=>$order_id
                    );
                K::M('staff/msg')->create($data);
                $this->msgbox->add('退单成功');
            }else {
                $this->msgbox->add('退单失败',216);
            }
        }
    } 

    // 催单
    public function remind()
    {
        $this->check_login();
        $order_id = $this->GP('order_id');
        if(!$order_id = (int)$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((__TIME - $order['cui_time'])<600){
            $this->msgbox->add('已经催过，稍后再试',216);
        }else if(K::M('order/order')->update($order_id, array('cui_time'=>__TIME))) {
            $data = array(
                'shop_id'=>$order['shop_id'],
                'title'=>'用户正在催单',
                'content'=>'用户('.$order['contact'].')正在催促订单(ID:'.$order_id.')',
                'is_read'=>0,
                'type'=>1,
                'order_id'=>$order_id
                );
            K::M('shop/msg')->create($data);
            if($staff = $order['staff_id']) {
                $data2 = array(
                    'staff_id'  => $staff,
                    'title'    => '用户正在催单',
                    'content'  => '用户('.$order['contact'].')正在催促订单(ID:'.$order_id.')',
                    'is_read'  => 0,
                    );
                K::M('staff/msg')->create($data2);
            }
            $this->msgbox->add('催单成功');
        }else {
            $this->msgbox->add('催单失败',214);
        }
    }

    // 确认送达
    public function getwell() 
    {
        $this->check_login();
        $order_id = $this->GP('order_id');
        if(!$order_id = (int)$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(1,3,4))){
            $this->msgbox->add('商家还未配送完成不可确认',215);
        }else if(K::M('order/order')->confirm($order_id, null, 'member')){
            
            $this->msgbox->add('订单确认送达成功'); 
        }else {
            $this->msgbox->add('订单确认送达失败',222);
        }
    }


    // 删除订单
    public function delorder($order_id) {
        if($order_id = (int)$order_id){
            if(!$order = K::M('order/order')->detail($order_id)){
                $this->msgbox->add('你要删除的订单不存在或已经删除', 211);
            }else if($order['comment_status']==0 && $order['order_status']==8) {
                $this->msgbox->add('你要删除的订单还未评价',212);
            }else{
                if(K::M('order/order')->delete($order_id)){
                    $this->msgbox->add('删除订单成功');
                }
            }
        }
    }   
}