<?php
namespace Api\Controller;
use Org\Check;
use Org\Vcode;
use Org\Sms;
use Common\Model\MemberModel;
use Api\Model\OrderModel;
use Admin\Model\MachineBoxModel;

class MachineController extends PublicController {
    private $action;


    public function rest(){
        $result = array('status'=>0, 'info'=>'fail');

    	$msg = "\n[".date('Y-m-d H:i:s').']'."\n";
    	$msg .= json_encode($_GET)."\n";
    	$msg .= json_encode($_POST)."\n";
    	file_put_contents('logs/machine/'.date('Y-m-d').'.log', $msg,FILE_APPEND);

    	$action = I('action','');

    	if(!$action || !method_exists($this,$action) ){
    	    $result['info'] = L('illegal_request'); //不存在的请求方法
    	    $this->ajaxReturn($result);
    	}
    	$this->action = $action;

    	$this->$action();

    }


    //初始化
    protected function init(){
        $result = array('status'=>0, 'info'=>'fail');
        $machine_id = I('machine_id','');
        if(!$machine_id){
            $result['info'] = L('param_error'); //参数错误
            $this->ajaxReturn($result);
        }
        S('machine_id',$machine_id);

        $map['status'] = 1;
        $map['machine_id'] = $machine_id;
        $macInfo = M('Machine')->where($map)->find();
        if(!$macInfo || !$macInfo['serial_no']){
            $result['info'] = L('unauthorized_equipment'); //未授权的设备
            $this->ajaxReturn($result);
        }

        $data['serial_no'] = $macInfo['serial_no'];

        $result['status'] = 1;
        $result['info'] = 'succ';
        $result['data'] = $data;
        $this->ajaxReturn($result);

    }

    //配置信息
    protected function config(){
    	$result = array('status'=>1, 'info'=>'succ');
    	$map['status'] = 1;
    	$map['mac_id'] = $this->mac_id;
    	$map['is_used'] = 0;

    	$data['min_amount'] = C('min_amount');
    	$data['phone'] = C('phone');
    	$data['ratio'] = C('jifen_ratio');
    	$macInfo = $this->getInfo(Machine,$this->mac_id);
    	$data['address'] = $macInfo['address'];

    	$map['type'] = array('in','1,2');
    	$data['box1'] = $this->getCount('Machine_box',$map);

    	$map['type'] = 3;
    	$data['box2'] = $this->getCount('Machine_box',$map);



    	$result['data'] = $data;
    	$this->ajaxReturn($result);

    }


    //广告
    protected function ad(){
    	$result = array('status'=>1, 'info'=>'succ');
    	$map['status'] = 1;
//     	$map['mac_id'] = $this->mac_id;

    	$data = $this->lists('Ad', $map, 'sort desc', 'id,icon_path img');

    	$result['data'] = $data;
    	$this->ajaxReturn($result);

    }


    //衣物分类
    protected function cate(){
    	$result = array('status'=>1, 'info'=>'succ');
    	$map['status'] = 1;
    	$map['mid'] = $this->mid;

    	$data = $this->lists('category', $map, 'sort desc', 'id,title,icon_path img,icon2_path img_selected');

    	$result['data'] = $data;
    	$this->ajaxReturn($result);

    }


    //衣物列表
    protected function goods(){
    	$result = array('status'=>0, 'info'=>'succ');
    	$cate = I('cate',0);
    	if(!$cate){
    	    $result['info'] = L('get_cate_fail'); //获取分类id失败
    	    $this->ajaxReturn($result);
    	}
    	$map['status'] = 1;
    	$map['cate'] = $cate;

    	$data = $this->lists('Goods', $map, 'sort desc', 'id,title,price',100);

    	$result['status'] = 1;
    	$result['data'] = $data;
    	$this->ajaxReturn($result);

    }


    /**
     * 发送短信验证码
     *
     * @param string $mobile
     * @return json
     */
    /*
    protected function sendVcode()
    {
        $result = array('status'=>0, 'info'=>'succ');


    	$mobile = I('mobile','');
    	$check = Check::isMobile($mobile);
    	if(!$check){
    	    $result['info'] = 'The phone number is incorrect'; //手机号码填写有误
    	    $this->ajaxReturn($result);
    	}

    	$obj_vcode = new Vcode();
    	$vcode = $obj_vcode->set_vcode($mobile);
    	if($vcode==false)
    	{
    	    $result['info'] = $obj_vcode->error;
    	    $this->ajaxReturn($result);
    	}

    	$params['code'] = $vcode;
//     	$this->success($vcode,'',true);
    	$obj_sms = new Sms();
    	$status = $obj_sms->send($mobile, 'verify_code', $params);
    	if (!$status) {
    		//     		$this->error('SMS sent failed','',true);
    		$result['info'] = 'SMS sent failed';
    		$this->ajaxReturn($result);
    	}else{
    	    $result['status'] = 1;
    	    $result['info'] = 'SMS sent successfully';
    	    $this->ajaxReturn($result);
    	}
    }
    */

    /**
     * 验证用户手机
     *
     * @param string $mobile
     * @param string $vcode
     * @return json
     */
    /*
    protected function checkUser(){
    	$result = array('status'=>0, 'info'=>'succ');

    	$mobile = I('mobile','');
    	$vcode = I('vcode','');
    	//短信验证todo
    	$obj_vcode = new Vcode();
    	$res = $obj_vcode->check_vcode($mobile,$vcode);
    	if (!$res) {
    	    $result['info'] = $obj_vcode->error;
    	    $this->ajaxReturn($result);
    	}

    	$m_member = new MemberModel();
    	$userInfo = $m_member->getInfoByMobile($mobile);
    	if($userInfo){
    		$data['credits'] = $userInfo['credits'];
    		$data['userid'] = $userInfo['id'];
    		$result['data'] = $data;
    	}else{
    		if($res = $m_member->regByMobile($mobile)){
    			$data['credits'] = 0;
    			$data['userid'] = $res;
    			$result['data'] = $data;
    		}else{
    			$result['info'] = 'Operation failed, please try again'; //操作失败，请重试
    			$this->ajaxReturn($result);
    		}
    	}

    	$result['status'] = 1;
    	$this->ajaxReturn($result);

    }
    */




    //创建订单
    /*
    protected function createOrder(){


    	$result = array('status'=>0, 'info'=>'succ');

    	$data['mac_id'] = $this->mac_id;
    	$data['fac_id'] = $this->fac_id;
    	$data['agent_id'] = $this->agent_id;
    	$data['mid'] = $this->mid;

    	$obj_order = D('Order');
    	$res = $obj_order->createOrder($data);
    	if(!$res){
    	    $result['info'] = $obj_order->getError();
    	    $this->ajaxReturn($result);
    	}else {
    	    $result['status'] = 1;
    		$result['data'] = $res;
    		$this->ajaxReturn($result);
    	}

    }
    */


    //创建订单--新版，登录、支付合并一步
    protected function createOrder_new(){


    	$result = array('status'=>0, 'info'=>'succ');

    	$data['mac_id'] = $this->mac_id;
    	$data['fac_id'] = $this->fac_id;
    	$data['agent_id'] = $this->agent_id;
    	$data['mid'] = $this->mid;

    	$obj_order = D('Order');
    	$res = $obj_order->createOrder_new($data);
    	if(!$res){
    		$result['info'] = $obj_order->getError();
    		$this->ajaxReturn($result);
    	}else {

    		$result['status'] = 1;
    		$result['data']['out_trade_no'] = $res;
    		$result['data']['qrcode_url'] = C('ROOT_DOMAIN')."/index.php?s=/Home/Index/confirm/out_trade_no/".$res;
    		$this->ajaxReturn($result);
    	}

    }


    //管理员输入密码
    protected function admin(){
    	$result = array('status'=>0, 'info'=>'succ');

    	$pwd = I('pwd','');
    	$macInfo = $this->getInfo('Machine',$this->mac_id);
    	if($pwd!=$macInfo['pwd']){
    	    $result['info'] = L('verify_fail'); //验证失败
    	    $this->ajaxReturn($result);
    	}

    	$obj_order = new OrderModel();
    	$order = $obj_order->macOrder($this->mac_id);
    	if(empty($order)){
    	    $result['info'] = L('no_order'); //暂无订单
    	    $this->ajaxReturn($result);
    	}

    	$result['status'] = 1;
    	$result['data']['order'] = $order;
    	$result['data']['address'] = $macInfo['address'];

    	$this->ajaxReturn($result);
    }


    protected function setPrintStatus(){
        $result = array('status'=>0, 'info'=>'succ');

        $out_trade_no = I('out_trade_no','');
        $succ = I('succ',0);

        $obj_order = new OrderModel();
        $res = $obj_order->setPrintStatus($out_trade_no,$succ);
        if($res ){
            $result['status'] = 1;
            $this->ajaxReturn($result);
        }else{
            $result['info'] = L('update_print_status_fail'); //更新打印状态失败
            $this->ajaxReturn($result);
        }

    }


    /**
     * 管理员取走衣物,关闭箱门
     *
     * @return json
     */
    protected function fetchOrder(){
        $result = array('status'=>0, 'info'=>'succ');

    	$out_trade_no = I('out_trade_no','');

    	$obj_order = new OrderModel();
    	$orderInfo = $obj_order->getInfo('out_trade_no', $out_trade_no);
    	if(!$orderInfo ){
    	    $result['info'] = L('obtain_order_info_fail'); //获取订单信息失败
    	    $this->ajaxReturn($result);
    	}

    	$obj_order->fetchOrder($out_trade_no);

    	//发短信

    	$result['status'] = 1;
    	$this->ajaxReturn($result);
    }


    //根据柜子编号，获取电子锁插线编号
    protected function getBoxAddr(){
    	$result = array('status'=>0, 'info'=>'succ');

    	$box = I('box',0);
    	$map['mac_id'] = $this->mac_id;
    	$map['num'] = $box;
    	$info = M('MachineBox')->where($map)->field('addr,door')->find();
    	if(empty($info)){
    	    $result['info'] = L('get_lock_num_fail'); //获取插线信息失败
    	    $this->ajaxReturn($result);
    	}

    	$result['status'] = 1;
    	$result['data'] = $info;
    	$this->ajaxReturn($result);

    }

    //获取微信支付二维码
    protected function payQrcode(){
    	$result = array('status'=>0, 'info'=>'succ');

    	$out_trade_no = I('out_trade_no','');
    	$type = I('type','wxpay');
    	if(!$out_trade_no){
    	    $result['info'] = L('obtain_order_info_fail'); //获取订单信息失败
    	    $this->ajaxReturn($result);
    	}

    	$obj_order = new OrderModel();
    	if(substr($out_trade_no, 0,1)=='f'){
    		$map['out_trade_no'] = $out_trade_no;
    		$orderInfo = M('OrderCode')->where($map)->find();
    	}else{
    		$orderInfo = $obj_order->getInfo('out_trade_no', $out_trade_no);
    	}
    	if(!$orderInfo ){
    	    $result['info'] = L('obtain_order_info_fail'); //获取订单信息失败
    	    $this->ajaxReturn($result);
    	}

    	if($type=='alipay')
    		$data = $obj_order->alipayQrcode($orderInfo);
    	else
    		$data = $obj_order->wxpayQrcode($orderInfo);

    	if(!$data){
    	    $result['info'] = L('qrcode_generation_failure'); //生成二维码失败
    	    $this->ajaxReturn($result);
    	}else{
    	    $result['status'] = 1;
    	    $result['data'] = $data;
    		$this->ajaxReturn($result);
    	}


//     	echo '<img alt="模式二扫码支付" src="'.$data.'" style="width:150px;height:150px;"/>';
    }


    //查询订单支付状态
    protected function queryOrderPayStatus(){
    	$result = array('status'=>0, 'info'=>'succ');

    	$out_trade_no = I('out_trade_no','');
    	$map['out_trade_no'] = $out_trade_no;

    	$type = substr($out_trade_no, 0,1);
    	if($type=='f'){
    		$obj_order = M('OrderCode');
    	}else{
    		$obj_order = new OrderModel();
    	}

    	$orderInfo = $obj_order->where($map)->find();

    	if(!$orderInfo || !$orderInfo['box']){
    		$result['status'] = 1;
    		$result['data'] = array(
    				'out_trade_no'=> $out_trade_no,
    				'pay_status'=>0,
    				'box'=>''
    		);
    		$this->ajaxReturn($result);

    	}

    	$result['status'] = 1;
    	$result['data'] = array(
    			'out_trade_no'=> $type=='f'? $orderInfo['order_sn']:$orderInfo['out_trade_no'],
    			'pay_status'=>$orderInfo['pay_status'],
    			'box'=>$orderInfo['box']
    	);
    	$this->ajaxReturn($result);

    }


    //扫码条码，获取订单信息
    protected function scanBarcode(){

        $result = array('status'=>0, 'info'=>'fail');
        $result['params'] = (object)array();

        $barcode = I('barcode','');

        if(!$barcode){
            $result['info'] = L('param_error'); //参数错误
            $this->ajaxReturn($result);

        }
        $barcode = str_replace('\ufffd', '', $barcode); //扫码时，返回订单号乱码替换
        $out_trade_no = 'sn_'.$barcode;
        $obj_order = new OrderModel();

        $map['out_trade_no'] = $out_trade_no;
        $map['status'] = 2;
        $map['mac_id'] = $this->mac_id;
        $orderInfo = M('Order')->where($map)->find();
        if(!$orderInfo ){
            $result['info'] = L('obtain_order_info_fail'); //查询订单信息失败
            $this->ajaxReturn($result);
        }
        $box = getAvlBox($out_trade_no);
        if($box==''){
            $result['info'] = L('no_available_box'); //没有可用的格子
            $this->ajaxReturn($result);
        }

        if(!$obj_order->deposit($out_trade_no,$box)){
            $result['info'] = $obj_order->getError();
            $this->ajaxReturn($result);

        }else{
        	$obj_box = new MachineBoxModel();
        	$box_arr = $obj_box->getBoxInfo($this->mac_id, $box);

            $result = array('status'=>1, 'info'=>'succ', 'data'=>$box_arr);
            $this->ajaxReturn($result);

        }

    }


    //配送员存件完成
    protected function deposit(){
        $result = array('status'=>0, 'info'=>'succ');

    	$barcode = I('barcode','');
    	$out_trade_no = 'sn_'.$barcode;

    	$obj_order = new OrderModel();
    	if(!$obj_order->deposit($out_trade_no)){
    	    $result['info'] = $obj_order->getError();
    	    $this->ajaxReturn($result);
    	}

    	$result['status'] = 1;
    	$this->ajaxReturn($result);

    }



    //输入取件码，。。。。。
    protected function checkFetchCode(){

    	$result = array('status'=>0, 'info'=>'succ');
    	$code = I('code','');
    	if(!$code ){
    	    $result['info'] = L('fetch_code_error'); //取件码有误
    	    $this->ajaxReturn($result);
    	}

    	$obj_order = new OrderModel();

    	$res = $obj_order->checkOrderIsOverdue($this->mac_id,$code);

    	//file_put_contents('logs/machine/'.date('Y-m-d').'.log', json_encode($res),FILE_APPEND);

    	if($res==false){
    	    $result['info'] = $obj_order->getError();
    	    $this->ajaxReturn($result);
    	}else{
    	    $result['status'] = 1;
    	    $result['info'] = L('operate_succ'); //操作成功
    		$result['data'] = $res;
    		if($res['pay_fee']>0)
    			$result['qrcode_url'] = C('ROOT_DOMAIN')."/index.php?s=/Home/Index/pay_machine/out_trade_no/".$res['out_trade_no'];
    		else
    			$result['qrcode_url'] = '';
    		$this->ajaxReturn($result);
    	}
    }



    //用户取件完成
    /*
    protected function finish(){
        $result = array('status'=>0, 'info'=>'succ');
    	$code = I('code','');
    	if(!$code ){
    	    $result['info'] = '取件码有误';
    	    $this->ajaxReturn($result);
    	}
    	$obj_order = new OrderModel();
    	$res = $obj_order->finish($this->mac_id,$code);
    	if($res==false){
    	    $result['info'] = $obj_order->getError();
    	    $this->ajaxReturn($result);
    	}else{
    	    $result['status'] = 1;
    	    $result['info'] = 'Operation succeeded';
    	    $this->ajaxReturn($result);

    	}
    }
    */



    //打开箱门
    protected function openBox(){
        $result = array('status'=>0, 'info'=>'succ');

    	$box = I('box','');
    	$out_trade_no = I('out_trade_no','');
    	$step = I('step',0); //第几次开门

    	$obj_order = new OrderModel();
    	$orderInfo = $obj_order->getInfo('out_trade_no', $out_trade_no);
    	if(!$orderInfo ){
    	    $result['info'] = L('obtain_order_info_fail'); //获取订单信息失败
    	    $this->ajaxReturn($result);
    	}
    	if($orderInfo['status']==10 || $orderInfo['pay_status']==0 ){
    	    $result['info'] = L('order_status_incorrect'); //订单状态有误
    	    $this->ajaxReturn($result);
    	}

    	if(!$box || !$step){
    		$result['info'] = L('param_error'); //参数错误
    		$this->ajaxReturn($result);
    	}

    	/*
    	$box_arr = explode(',', $box);

    	$mac = new Mac();

    	foreach ($box_arr as $b){
    		$res = $mac->openDoor($this->uuid, $this->mac_id,$b,$out_trade_no);
    		$res = json_decode($res,true);
    		//file_put_contents('logs/machine/'.date('Y-m-d').'.log', json_encode($res)."\n",FILE_APPEND);
    		sleep(2);
    	}
    	*/
    	$obj_box = new MachineBoxModel();
    	$box_arr = $obj_box->getBoxInfo($this->mac_id, $box);
    	$result['data'] = $box_arr;
    	$result['params'] = (object)array();

    	if(1){

    		if($step==1){//下单支付完成，打开柜门
    			if(!$obj_order->succOrder($orderInfo)){
    				$result['info'] = $obj_order->getError();
    				$this->ajaxReturn($result);
    			}
    			$result['status'] = 1;
    			$result['info'] = L('operate_succ'); //操作成功
    			$this->ajaxReturn($result);

    		}elseif($step==2){//管理员开箱取件
    			if(!$obj_order->fetchOrder($out_trade_no,false)){
    			    $result['info'] = $obj_order->getError();
    			    $this->ajaxReturn($result);
    			}
    			$result['params'] = $obj_order->barcodeInfo($orderInfo);
    			$result['status'] = 1;
    			$result['info'] = L('operate_succ'); //操作成功
    			$this->ajaxReturn($result);

    		}elseif($step==4){//输入取件码，开箱

    			$res = $obj_order->finish($out_trade_no);
    			if($res==false){
    			    $result['info'] = $obj_order->getError();
    			    $this->ajaxReturn($result);
    			}
    			$result['status'] = 1;
    			$result['info'] = L('operate_succ'); //操作成功
    			$this->ajaxReturn($result);

    		}elseif($step==5){//输入预约码，开箱
    			$data['yuyue'] = 0;
    			$res = M('order')->where(array('out_trade_no'=>$out_trade_no))->save($data);

    			if(!$res){
    			    $result['info'] = L('operate_fail');//操作失败
    			    $this->ajaxReturn($result);
    			}

    			if(!$obj_order->succOrder($orderInfo)){
    			    $result['info'] = $obj_order->getError();
    			    $this->ajaxReturn($result);
    			}
    			$result['status'] = 1;
    			$result['info'] = L('operate_succ'); //操作成功
    			$this->ajaxReturn($result);
    		}
    	}else{
    		$result['info'] = L('operate_fail');//操作失败
    		$this->ajaxReturn($result);
    	}

    }


    //获取要打印的条码信息
    public function getBarcodeInfo(){
    	$result = array('status'=>0, 'info'=>'succ');

    	$out_trade_no = I('out_trade_no','');

    	$obj_order = new OrderModel();
    	$orderInfo = $obj_order->getInfo('out_trade_no', $out_trade_no);
    	if(!$orderInfo ){
    		$result['info'] = L('obtain_order_info_fail'); //获取订单信息失败
    		$this->ajaxReturn($result);
    	}

    	$result['data'] = $obj_order->barcodeInfo($orderInfo);
    	$result['status'] = 1;
    	$result['info'] = L('operate_succ'); //操作成功
    	$this->ajaxReturn($result);
    }


    //打印条形码
    /*
    protected function printBarcode(){
    	$out_trade_no = I('out_trade_no','');


    }
    */



    //获取扫码数据
    /*
    protected function getBarcode(){
    	$result = array('status'=>1, 'info'=>'succ');

    	$s_barcode = S($this->uuid.'_barcode');
    	if($s_barcode){
    		$s_barcode = array_shift($s_barcode);
    		S($this->uuid.'_barcode',$s_barcode);
    		$result['data'] = $s_barcode;
    	}
    	else
    		$result['data'] = '';

    	$this->ajaxReturn($result);

    }
    */

    //获取箱门开关状态
    protected function getBoxStatus(){
    	$result = array('status'=>0, 'info'=>'succ');

    	$box = I('box',0);
    	$map['mac_id'] = $this->mac_id;
    	$map['num'] = $box;
    	$boxInfo = M('machine_box')->where($map)->find();
    	if(!$boxInfo){
    	    $result['info'] = L('fetch_code_error'); //取件码有误
    	    $this->ajaxReturn($result);
    	}
    	$result['status'] = 1;
    	$result['data'] = $boxInfo['openflag'];
    	$this->ajaxReturn($result);

    }


    //输入预约码
    protected function checkYuyueCode(){


    	$result = array('status'=>0, 'info'=>'succ');

    	$code = I('code','');

    	if(!$code ){
    	    $result['info'] = L('fetch_code_error'); //取件码有误
    	    $this->ajaxReturn($result);
    	}

    	$obj_order = new OrderModel();

    	$res = $obj_order->checkYuyueCode($this->mac_id,$code);

    	if($res==false){
    		$result['info'] = $obj_order->getError();
    		$this->ajaxReturn($result);
    	}else{
    	    $result['status'] = 1;
    	    $result['data'] = $res;
    		$this->ajaxReturn($result);

    	}

    }


    //根据uuid检查用户是否确登录
    protected function getScanQrcode(){
        $type = I('type','login');
        $type = I('type','login');

        $result = array('status'=>1, 'info'=>'succ');

        $ukey = 'scan_'.$this->mac_id.time().rand(10000, 99999);
        if($type=='fetch'){
            $token = md5('scanFetch'.AUTH_KEY.date('Ymd'));
            $url = C('ROOT_DOMAIN')."/index.php?s=/Home/Index/scanFetch/ukey/$ukey/mac_id/$this->mac_id/token/$token";
        }else{
            $token = md5('scanLogin'.AUTH_KEY.date('Ymd'));
            $url = C('ROOT_DOMAIN')."/index.php?s=/Home/Index/scanLogin/ukey/$ukey/mac_id/$this->mac_id/token/$token";
        }

        $data['qrcode_url'] = $url;
        $data['ukey'] = $ukey;

        $result['data'] = $data;
        $this->ajaxReturn($result);

    }

    //根据uuid检查用户是否确登录
    protected function getScanLogin(){

        $result = array('status'=>0, 'info'=>'succ');
        $ukey = I('ukey','');
        if(!$ukey ){
            $result['info'] = L('param_error'); //参数错误
            $this->ajaxReturn($result);
        }

        $data = array();
        $memInfo = getScanLogin($ukey);
        if($memInfo){
            $data['credits'] = $memInfo['credits'];
            $data['userid'] = $memInfo['id'];
            $data['mobile'] = $memInfo['mobile'];
        }
        $result['status'] = 1;
        $result['data'] = $data;
        $this->ajaxReturn($result);

    }



    //根据uuid检查用户的取件码
    protected function getScanFetch(){

        $result = array('status'=>0, 'info'=>'succ');
        $ukey = I('ukey','');
        if(!$ukey ){
            $result['info'] = L('param_error'); //参数错误
            $this->ajaxReturn($result);
        }

        $data = array();
        $data = getScanFetch($ukey);

        $result['status'] = 1;
        $result['data'] = $data;
        $this->ajaxReturn($result);

    }


    //心跳
    protected function heart(){
    	$result = array('status'=>1, 'info'=>'succ');

    	$key = $this->uuid.'_active_time';
    	S($key,time());

    	$this->ajaxReturn($result);
    }


    protected function ajaxReturn($data) {
        $msg = '['.date('Y-m-d H:i:s').']'."\n";
        $msg .=$this->action.'_return'.json_encode($data)."\n";

        file_put_contents('logs/machine/'.date('Y-m-d').'.log', $msg,FILE_APPEND);
//         print_pre($data);

        // 返回JSON数据格式到客户端 包含状态信息
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($data));

    }





}