<?php
namespace Admin\Controller;
use Org\Sms;
use Think\Model;
/**
 * 订单控制器
 */
class OrderController extends AdminController {


    /**
     * 列表页
     */
    public function index(){
        $p = I('p',1);
        $demo = 1;

    	$keywords = I('keywords','');
    	$mac_id = I('mac_id',0);
    	$mch_id = I('mch_id',0);
    	$order_status = I('order_status','');
    	$start_date = I('start_date');
    	$end_date = I('end_date');
    	if(!empty($start_date)&&!empty($end_date)){
    		$start_date = strtotime($start_date);
    		$end_date = strtotime($end_date)+3600*24;
    		$map['createtime']    =   array(array('EGT',$start_date),array('ELT',$end_date),'and');
    	}

    	if(!empty($keywords)){
    		$map['out_trade_no|mobile'] = array('like', '%'.(string)$keywords.'%');
    	}
    	if(!empty($mch_id)){
    	    $map['mid'] = $mch_id;
    	}
    	if(!empty($mac_id)){
    	    $map['mac_id'] = $mac_id;
    	}
    	if(!empty($order_status)){
    	    switch ($order_status){
    	        case 'yuyue':
    	            $map['status'] = 1;
    	            $map['yuyue'] = 1;
    	            $map['pay_status'] = 1;
    	            break;
    	        case 'wait_admin_fetch':
    	            $map['status'] = 1;
    	            $map['yuyue'] = 0;
    	            $map['pay_status'] = 1;
    	            break;
    	        case 'no_pay':
    	            $map['status'] = 1;
    	            $map['pay_status'] = 0;
    	            break;
    	        case 'has_pay':
    	            $map['pay_status'] = 1;
    	            break;
    	        case 'admin_has_fetch':
    	            $map['status'] = 2;
    	            break;
    	        case 'wait_customer_fetch':
    	            $map['status'] = 3;
    	            break;
    	        case 'finish':
    	            $map['status'] = 10;
    	            break;
    	        case 'timeout':
    	            $map['status'] = array('neq',10);
    	            $map['pay_status'] = 1;
    	            $map['createtime'] = array('lt',time()-3600*24*3);
    	            break;
    	        default:
    	            break;
    	    }
    	}
    	if(UID!=26){
    	    $map['is_fault'] = 0;
    	    $demo = 0;
    	}
    	
        $list   = $this->lists(CONTROLLER_NAME, $map, 'createtime desc',true,500);

        $macList = $this->getAllRows('Machine',true,array('status'=>1));
        $mchList = $this->getAllRows('Merchant',true,array('status'=>1));
        
        //是否有超时订单
        $filter = array(
            'status'=> array('neq',10),
            'pay_status' => 1,
            'createtime' => array('lt',time()-3600*24*3)
        );
        $timeoutNum = M('Order')->where($filter)->count();
        
        $total_fee = M('Order')->where($map)->sum('total_fee');


        $this->assign('keywords', $keywords);
        $this->assign('mac_id', $mac_id);
        $this->assign('mch_id', $mch_id);
        $this->assign('order_status', $order_status);
        $this->assign('_list', $list);
        $this->assign('macList', $macList);
        $this->assign('mchList', $mchList);
        $this->assign('orderStatus', C('OrderStatus'));
        $this->assign('timeoutNum', $timeoutNum);
        $this->assign('total_fee', $total_fee);
        $this->assign('p', $p);
        $this->assign('demo', $demo); //是为演示数据
        $this->meta_title = 'Order list';
        $this->display();
    }



    /**
     * 浏览页面
     */
    public function view(){
    	$info = $this->getInfo('Order');
    	$goods = json_decode($info['body'],true);

    	$log = $this->getAllRows('OrderLog',true,array('out_trade_no'=>$info['out_trade_no']));

        $this->assign('info',$info);
        $this->assign('goods',$goods);
        $this->assign('log',$log);
        $this->meta_title = 'Order detial' ;
        $this->display();
    }


    /**
     * 编辑页面
     */
    public function edit(){
    	if(IS_POST){
    		$this->save(CONTROLLER_NAME,'',false);
    	}else {
    		$this->display();
    	}
    }


    /**
     * 完成订单，释放格子
     */
    public function finish($id=0){
        $info = $this->getInfo('Order');


        $res = M('Order')->where(array('out_trade_no'=>$info['out_trade_no']))->save(array('status'=>10,'box'=>'','yuyue'=>0,'updatetime'=>time()));
        if($res){
            M('OrderCode')->where(array('order_sn'=>$info['out_trade_no']))->save(array('status'=>1));
            $where['mac_id'] = $info['mac_id'];
            $where['num'] = array('in',$info['box']);
            M('MachineBox')->where($where)->save(array('is_used'=>0));
            $this->success('Operation succeeded');

        }else{
            $this->error('Operation failure');
        }

    }


    //打开箱门
    Public function openBox($id=0){

    	$orderInfo = $this->getInfo('Order');
    	if(!$orderInfo ){
    		$this->error('Failed to obtain order information');
    	}
    	if($orderInfo['status']==10 || $orderInfo['pay_status']==0 ){
    		$this->error('Order status is incorrect');
    	}
    	if(!$orderInfo['box']){
    		$this->error('parameter error');
    	}
    	$macInfo = M('Machine')->find($orderInfo['mac_id']);
    	if(!$macInfo || $macInfo['status']!=1){
    	    $this->error('parameter error 02');
    	}

    	$flag = false;
    	{
    		$map['mac_id'] = $macInfo['id'];
    		$map['num'] = array('in',$orderInfo['box']);
    		$map['status'] = 1;
    		$boxes = M('MachineBox')->field('addr,door')->where($map)->select();
    		require VENDOR_PATH.'JPush/JPush.php';
    		$JPush = new \JPush();
    		$res = $JPush->openDoor($macInfo['serial_no'], $boxes);
			//$this->error(json_encode($res));
    		if($res){
    			$flag = true;
    		}
    	}
    	if($flag){
    		$this->success('Operation succeeded');
    	}else{
    	    $this->error('Operation failure');
    	}
    }


    //打印条码
    Public function printBarcode($id=0){
    	$orderInfo = $this->getInfo('Order');

    	if(!$orderInfo ){
    		$this->error('Failed to obtain order information');
    	}
    	if($orderInfo['status']==10 || $orderInfo['pay_status']==0 ){
    		$this->error('Order status is incorrect');
    	}
    	$macInfo = M('Machine')->find($orderInfo['mac_id']);
    	if(!$macInfo || $macInfo['status']!=1){
    		$this->error('parameter error');
    	}

    	$flag = false;

    	$flag = false;
    	{

    		require VENDOR_PATH.'JPush/JPush.php';
    		$JPush = new \JPush();
    		$res = $JPush->printBarcode($macInfo['serial_no'], $orderInfo['out_trade_no']);
    		if($res){
    			$flag = true;
    		}
    	}
    	if($flag){
    		$this->success('Print success');
    	}else{
    		$this->error('Print failure');
    	}
    }


    //发送取件码
    Public function sendSms($id=0){
        $orderInfo = $this->getInfo('Order');

        if(!$orderInfo ){
            $this->error('Failed to obtain order information');
        }
        if($orderInfo['status']!=3 ){
            $this->error('Order status is incorrect');
        }
        $info = M('OrderCode')->where(array('order_sn'=>$orderInfo['out_trade_no']))->find();
        $code = $info['code'];

        $macInfo = M('Machine')->find($orderInfo['mac_id']);

        //发送短信，通知用户取件
        $params['code'] = $code;
        $params['address'] = $macInfo['address'];
        $obj_sms = new Sms();
        $status = $obj_sms->send($orderInfo['mobile'], 'finish_notify', $params);

        if($status){
            $this->success('SMS sent successfully');
        }else{
            $this->error('SMS sent failed');
        }
    }


    
    /**
     * 洗衣明细
     */
    public function goods(){
    	$fac_id = I('fac_id',0);
    	$start_date = I('start_date');
    	$end_date = I('end_date');
    	
    	$sql = "SELECT g.goods_name,count(g.goods_id) num,g.goods_price,g.goods_cate FROM ot_order_goods g LEFT JOIN ot_order o on g.out_trade_no=o.out_trade_no where o.`status`=10 ";
    	if(!empty($start_date)&&!empty($end_date)){
    		$start_date = strtotime($start_date);
    		$end_date = strtotime($end_date)+3600*24;
    		$sql .=" and o.updatetime>=$start_date and o.updatetime<=$end_date ";
    	}

    	if(!empty($fac_id)){
    	    $sql .=" and g.fac_id=".$fac_id;
    	}
    	$sql .=" GROUP BY goods_id";
    	
    	$model = new Model();
    	$list = $model->query($sql);
    	
        $facList = $this->getAllRows('Factory',true,array('status'=>1));

        $this->assign('fac_id', $fac_id);
        $this->assign('_list', $list);
        $this->assign('facList', $facList);
        $this->meta_title = 'Order details';
        $this->display();
    }
    
    
    /**
     * 洗衣明细-导出
     */
    public function goods_export(){
        $fac_id = I('fac_id',0);
        $start_date = I('start_date');
        $end_date = I('end_date');
         
        $sql = "SELECT g.goods_name, g.goods_cate, g.goods_price, count(g.goods_id) num FROM ot_order_goods g LEFT JOIN ot_order o on g.out_trade_no=o.out_trade_no where o.`status`=10 ";
        if(!empty($start_date)&&!empty($end_date)){
            $start_date = strtotime($start_date);
            $end_date = strtotime($end_date)+3600*24;
            $sql .=" and o.updatetime>=$start_date and o.updatetime<=$end_date ";
        }
    
        if(!empty($fac_id)){
            $sql .=" and g.fac_id=".$fac_id;
        }
        $sql .=" GROUP BY goods_id";
         
        $model = new Model();
        $list = $model->query($sql);
        
        foreach ($list as $k=>$v){
            $list[$k]['goods_cate'] = get_category_title($v['goods_cate']);
        }
        
        $fileName = "Order details_".time();
        //导出的字段
        $headArr = array('title','category','price','quantity');
        $this->exportExcel($fileName,$headArr,$list);

	}
	

	public function txt_export(){
		$vo_id = intval(I('id'));
		
		$sql = "SELECT `ot_order`.*  
		FROM `ot_order` 
		WHERE `ot_order`.`id` = '$vo_id'
		";
         
        $model = new Model();
		$list = $model->query($sql)[0];
		$detail = json_decode($list['body'],true);

		$sql = "SELECT * FROM `ot_category`";
		$model = new Model();
		$cate = $model->query($sql);
		foreach($cate as $k=>$c){
			$cates[$c['id']] = $c['title'];
		}

		$sql = "SELECT * FROM `ot_machine`";
		$model = new Model();
		$mach = $model->query($sql);
		foreach($mach as $k=>$m){
			$machs[$m['id']] = $m['title'];
		}

		header('Content-Disposition: attachment; filename='.$vo_id.'.txt');
		header('Content-type: application/txt');
		header('Content-Transfer-Encoding: binary');
		header('Content-Description: File Transfer');
		header('Cache-Control: must-revalidate');
		ob_clean();
		flush();

		$head = array(	
			'Machine_ID',
			'Service_Date',
			'Service_Time',
			'Service_No',
			'PackageCode',
			'Customer_Tag',
			'Cloth_Item',
			'Cloth_Tag',
			'Cloth_Name',
			'Service_Type',
			'Service_Qty',
			'Service_Price',
			'Service_Amount',
			'Payment_Flag',
		);
		
		$txt = implode ('|',$head);
		$txt .= "\r\n";
		echo( iconv('utf8', 'tis620',$txt) );

		$i = 0;
		foreach($detail as $d){
			$i++;
			$echo = array(	
				$machs[$list['mac_id']],	//machine_id
				date('Ymd',$list['createtime']),		//Service_date
				date('H:i:s',$list['createtime']),		//Service_time
				$list['out_trade_no'],					//Service_No
				1,								//PackageCode
				$list['mobile'],					//Customer_Tag
				$i,									//Cloth_Item
				$d['id'],						//Cloth_Tag
				$d['title'],						//Cloth_Name
				$d['cate'],							//Service_Type
				$d['num'],							//Service_Qty
				number_format($d['price'],2),		//Service_Price
				number_format($d['price']*$d['num'],2),		//Service_Amount
				'001',				//Payment_Flag

			);
			
			$txt = implode ('|',$echo);
			$txt .= "\r\n";
			echo( iconv('utf8', 'tis620',$txt) );
		}
	}
	
	public function txt_export_selected(){


		$sql = "SELECT * FROM `ot_category`";
		$model = new Model();
		$cate = $model->query($sql);
		foreach($cate as $k=>$c){
			$cates[$c['id']] = $c['title'];
		}

		$sql = "SELECT * FROM `ot_machine`";
		$model = new Model();
		$mach = $model->query($sql);
		foreach($mach as $k=>$m){
			$machs[$m['id']] = $m['title'];
		}

		$ids = explode(',',I('ids'));
		header('Content-Disposition: attachment; filename='.'ew'.date('Ymd_His').'.txt');
		header('Content-type: application/txt');
		header('Content-Transfer-Encoding: binary');
		header('Content-Description: File Transfer');
		header('Cache-Control: must-revalidate');
		ob_clean();
		flush();

		$head = array(	
			'Machine_ID',
			'Service_Date',
			'Service_Time',
			'Service_No',
			'PackageCode',
			'Customer_Tag',
			'Cloth_Item',
			'Cloth_Tag',
			'Cloth_Name',
			'Service_Type',
			'Service_Qty',
			'Service_Price',
			'Service_Amount',
			'Payment_Flag',
		);
		
		$txt = implode ('|',$head);
		$txt .= "\r\n";
		echo( iconv('utf8', 'tis620',$txt) );

		
		foreach($ids as $id){
			$vo_id = intval($id);
			if(empty($vo_id)){
				continue;
			}
			$sql = "SELECT `ot_order`.*  
			FROM `ot_order` 
			WHERE `ot_order`.`id` = '$vo_id'
			";
			$model = new Model();
			$list = $model->query($sql)[0];
			$detail = json_decode($list['body'],true);

			$i = 0;
			foreach($detail as $d){
				$i++;
				$echo = array(	
					$machs[$list['mac_id']],	//machine_id
					date('Ymd',$list['createtime']),		//Service_date
					date('H:i:s',$list['createtime']),		//Service_time
					$list['out_trade_no'],					//Service_No
					1,									//PackageCode
					$list['mobile'],					//Customer_Tag
					$i,									//Cloth_Item
					$d['id'],						//Cloth_Tag
					$d['title'],						//Cloth_Name
					$d['cate'],							//Service_Type
					$d['num'],							//Service_Qty
					number_format($d['price'],2),		//Service_Price
					number_format($d['price']*$d['num'],2),		//Service_Amount
					'001',								//Payment_Flag

				);
				
				$txt = implode ('|',$echo);
				$txt .= "\r\n";
				echo( iconv('utf8', 'tis620',$txt) );
			}
		}


    }


}