<?php
/**
 * 订单管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <1070309178@qq.com>
 */

namespace Mobile\Controller;
use Think\Controller;
class OrderController extends BaseController {
    public function _initialize(){
        parent::_initialize ();
        if(!MID){
             $this->redirect('Mobile/Login/index');
        }
        if($this->m_info['is_tmp']==1&&!$this->m_info['mobile']){
             session('format_url',U('Mobile/Cart/index'));
             $this->redirect('Mobile/Login/perfect');
        }elseif($this->m_info['is_tmp']==1&&$this->m_info['mobile']){
             $this->error('您已经领取过会员卡了！');exit;
        }
        $this->assign('tplseo_title','确认订单'.'_'.C('WEB_SITE_TITLE'));
        $this->assign('page_title','确认订单');
    }
    public function index(){
		session('goods_attr',null);session('pid',null);session('spec_attr',null);
        $map['id']=$this->member_info['id'];
        $user_info=M("Member")->where($map)->field(true)->find();
        //立即购买信息
        $goods_id=I('goods_id');
        $invoice_title=I('invoice_type');
        $this->assign('invoice_title',$invoice_title);
        if($goods_id){
            session('goods_id',$goods_id);
            session('ids',null);
        }else{
            $goods_id=session('goods_id');
        }
        $number=I('number');
        if($number){
            session('number',$number);
        }else{
            $number=session('number');
        }
        $goods_attr=I('goods_attr');
        if($goods_attr){
            session('goods_attr',$goods_attr);
        }else{
            $goods_attr=session('goods_attr');
        }
        // 服务属性
        $spec_attr=urldecode(I('spec_attr'));
        session('spec_attr',$spec_attr);

        if($goods_attr){
            $goods_attr = explode('_',$goods_attr);
            $arr = array();
            foreach($goods_attr as $v){
                $arr[] = intval($v);
            }
            sort($arr);
            $goods_attr = implode('_',$arr);
        }
        $act=I('act');
        if($act){
            session('act',$act);
        }else{
            $act=session('act');
        }
        $type=I('type');
        if($type){
            session('type',$type);
        }else{
            $type=session('type');
        }
        if($type==3){
            $integral=I('integra');
            if($integral){
                session('integra',$integral);
            }else{
                $integral=session('integra');
            }
        }
        $ids=I('ids');
        if($ids){
            session('ids',$ids);
            session('goods_id',null);
            $goods_id='';
        }else{
            $ids=session('ids');
        }
		$pid=I('pid');
        if($pid){
            session('pid',$pid);
        }else{
            $pid=session('pid');
        }
		if($type == 6){
			$pid = $pid;
		}else{
			$pid = 0;
		}
        session('jump',2);
        session('jump_paypass',2);
        $data = array();
        $data['goods_id']=$goods_id;
        $data['number']=$number;
        $data['goods_attr']=$goods_attr;
        $data['spec_attr']=$spec_attr;
        $data['act']=$act;
        $data['type']=$type;
        $data['ids']=$ids;
        $data['pid']=$pid;
        $data['integra']=$integral;

		
        session('getdata',$data);
        $goods_id=$data['goods_id'];
        $type=$data['type'];
        $ids = $data['ids'];
		
        // print_r($data);exit;
        $addres_id=I('address_id');
        if($addres_id)$this->assign('addres_id',$addres_id);

        $this->assign('order_datas',json_encode($data));
        $this->assign("o_param",$data);
        $shop_id = get_wxsmall_shop_id();
        if($type==6){
            if(!empty($goods_id) && empty($ids)){
                $is_num = D("Common/Cart")->shopgoodsstock($goods_id,$shop_id,$goods_attr);
                if($is_num['goods_number'] <= 0){
                    $this->error('库存不足！');
                }
            }
            $buy_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where('e.style_ext_id='.$goods_id)->order('e.id desc')->getField('buy_limit');
            if($data['number'] > $buy_limit && $buy_limit != 0){
                if($type == 6){
                    $this->error('按拼团价格买每人限购'.$buy_limit.'件，不得超过数量限制');
                }else{
                    $this->error('每人限购'.$buy_limit.'件，不得超过数量限制');
                }
                // $this->error('按拼团价格买每人限购'.$buy_limit.'件，不得超过数量限制');
            }
            $now_time = NOW_TIME;
            //是否成团
            $pid_order = I('get.pid');
            if(!empty($pid_order)){
                $map_tea['id']=$pid_order;
                $tid = M('OrderInfo')->where($map_tea)->getField('uid');
                if($tid==MID){
                    $this->error('你是该团的团长，不可参团购买',U('FightGroup/group_join',array('order_id'=>$pid_order,'eid'=>MID)));
                }
                $map_son['pid'] = $pid_order;
                $map_son['pay_status'] = 3;
                $son_uid = M('OrderInfo')->where($map_son)->field('uid')->select();
                if(!empty($son_uid)){
                    foreach($son_uid as $k=>$v){
                        $arr[] = $v['uid'];
                    }
                    if(in_array(MID, $arr)){
                        $this->error('你已参加该团，不可再次购买');
                    }
                }
                $p_order_status = M('OrderInfo')->where('id='.$pid_order)->getField('shipping_status');
                if($p_order_status == 1){
                    $this->error('该团已成团，不可参团');
                }
                $group_time_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where('e.style_ext_id='.$goods_id)->order('e.id desc')->getField('group_time_limit');
                $p_time = M('OrderInfo')->where('id='.$pid_order)->getField('confirm_time');
                $p_end = $p_time + ($group_time_limit * 3600);
                if($p_end<$now_time){
                    //已过期未成团的，返还余额
                    $status = M('OrderInfo')->where('id='.$pid_order)->getField('status');
                    if($status != 10 && $status != 4){
                        $postdata['order_id']=$pid_order;
                        $postdata['admin_id']=MID;//操作日志用
                        $postdata['type']='Member';//操作日志用
                        $return=D('Common/OrderInfo')->cancel_order($postdata);
                        if($return['status'] == 1){
                            $save['status'] = 10;
                            $map = array();
                            $map['id'] = $pid_order;
                            $update = M('OrderInfo')->where($map)->save($save);
                        }
                        $map = array();
                        $map['pid'] = $pid_order;
                        $son_orders = M('OrderInfo')->where($map)->field('id')->select();
                        if(!empty($son_orders)){
                            $map_order['admin_id']=MID;//操作日志用
                            $map_order['type']='Member';//操作日志用
                            foreach ($son_orders as $key => $value) {
                                $map_order['order_id']=$value['id'];
                                $updates = D('Common/OrderInfo')->cancel_order($map_order);
                                if($updates['status'] == 1){
                                    $maps = array();
                                    $maps['id'] = $value['id'];
                                    $saves['status'] = 10;
                                    $updates = M('OrderInfo')->where($maps)->save($saves);
                                }
                            }
                        }
                    }
                    $this->error('该团已过期，不可参团');
                }
            }
            //是否过期
            $map = array();
            $map['e.style_ext_id'] = $goods_id;
            $end_time = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where($map)->order('e.id desc')->getField('end_time');
            if($end_time<$now_time){
                // $this->error('该团已过期，不能购买此商品');
                if($type == 6){
                    $this->error('该团已过期，不能购买此商品');
                }else{
                    $this->error('活动已过期，不能购买此商品');
                }
            }
        }
        $result = D('Common/OrderInfo')->order_list($ids,$goods_id,$type,$addres_id);
        if($result['service_time']['to_time']){
            $add_time = NOW_TIME + ($result['service_time']['to_time']*60);
        }else{
            $add_time = NOW_TIME;
        }
        $liji_time = NOW_TIME + ($result['service_time']['to_time']*60);
        $this->assign('liji_time',$liji_time);
        $this->assign('now_time',$add_time);
        $this->assign('now_time_date',NOW_TIME);
        $this->assign('now_week',date('w'));
        //获取订单信息
        if($result['data']['status']==0){
            if(empty($result['data']['msg']))$result['data']['msg']='获取订单信息错误';
            $this->error($result['data']['msg'],get_forward());
        }
		
        //判断是否有支付密码
        if(empty($user_info['paypassword'])){
            $this->assign('userpaypass',1);
        }
        //收货地址
        $address=array();
        foreach($result['address_list'] as $key=>$val){
            if($addres_id){
                if($val['id']==$addres_id){
                    $address=$val;
                }
            }else{
                if($val['id']==$result['addr_check_id']){
                    $address=$val;
                }
            }
        }
        if($type == 11){
            $html = '';
            $gmap['id'] = $goods_id;
            $goodsinfo = M('Goods')->where($gmap)->field(true)->find();
            if($goodsinfo['shop_ids'] != 0 && $goodsinfo['shop_ids'] != $shop_id){
                $this->error('该服务已下架');
            }
            if($goodsinfo['service_tostore'] == 1 && $goodsinfo['service_tohome'] == 1){
                $service_type = 3;
            }else if($goodsinfo['service_tostore'] == 1 && empty($goodsinfo['service_tohome'])){
                $service_type = 1;
            }else if(empty($goodsinfo['service_tostore']) && $goodsinfo['service_tohome'] == 1){
                $service_type = 2;
            }
            $mindate = time_format(NOW_TIME,'Y-m-d h:i:s');
            $this->assign('s_id',$shop_id);
            $this->assign('mindate',$mindate);
            $this->assign('service_type',$service_type);
        }
//        print_r($result['data']['list']);
        $this->assign($result);
        $yingshou_coupon=$result['data']['list'][$shop_id]['shop_info']['shop_total_price']-$result['data']['list'][$shop_id]['shop_info']['giftprice'];
        $coupons = get_online_bonus($yingshou_coupon,$user_info['id'],$ids,$goods_id);
        $this->assign('coupons',$coupons);
        $this->assign('yingshou_coupon',$yingshou_coupon);
        $this->assign('type',$type);

        $this->assign('dis',$result['addr_info']);
        $this->assign('address_info',$result['addr_info']['address_info']);
        $this->assign('member_info',$user_info);
        $this->assign('ids',$ids);
        if($type==14 || $type==6 || $type==11 || $type==3){
            if(!empty($goods_id) && empty($ids) && $type!=11){
                $shop_id = get_wxsmall_shop_id();
                $is_num = D("Common/Cart")->shopgoodsstock($goods_id,$shop_id,$goods_attr);
                if($is_num['goods_number'] <= 0){
                    $this->error('库存不足！');
                }
            }
            $this->assign('is_addcart',$type);
            $this->assign('shop_info',$result['data']['list'][$shop_id]['shop_info']);
            $this->assign('s_id',$shop_id);
        }
        $this->display();
    }

    /**
     * 发票
     */
    public function order_invoice(){
        $this->assign('page_title','发票信息');
        $user_info=idtoname($this->member_info['id'],'Member','*');
        $ids = I('ids'); $this->assign('cids',$ids);
        $data=I('get.');
        $goods_id=I("goods_id");
        $type=I("type");
        $result = D('Common/OrderInfo')->order_list($ids,$goods_id,$type,'');//获取订单信息
        $shop_goods=$result['data']['shopgoods'];
        foreach($shop_goods as $key=>$val) {
            if ($key > 0) {
                foreach ($val['goods_ids'] as $kk => $v) {
                    $map['id'] = $v;
                    $goods_info = M("Goods")->where($map)->field('goods_name,img')->find();
                    $goods[$kk]['goods_id'] = $v;
                    $goods[$kk]['goods_name'] = $goods_info['goods_name'];
                    $goods[$kk]['goods_img'] = $goods_info['img'];
                }
                $shop_goodsinfo[$key] = $goods;
            }
        }
        $invoce_map['uid']=$user_info['id'];
        $invoce_info=M("MemberInvoice")->where($invoce_map)->field(true)->find();
        $invoice_info=unserialize($invoce_info['invoice_info']);
        $this->assign('invoice_info',$invoice_info);
    $this->assign('shop_goods',$shop_goodsinfo);

    $this->assign('type',$type);
        $this->assign("order_param",json_encode($data));
        $this->display();
    }
    public function sub_vat(){
        $root=array('status'=>0,'msg'=>'');
        $post=I("post.");
        $user_info=idtoname($this->member_info['id'],'Member','*');
        $invoce_map['uid']=$user_info['id'];
        $data['invoice_info']=serialize($post);
        $data['type']=$post['invoice_type'];
        $invoce_info=M("MemberInvoice")->where($invoce_map)->field(true)->find();
        if($post['email']){
            $regular=new \Common\Vendor\Regular;
            if(!$regular->isEmail($post['email'])){
                $root['msg']="电子邮箱格式错误";
                $this->ajaxReturn($root);
            }
        }
        if($invoce_info){
            $invoce_map['id']=$invoce_info['id'];$data['update_time']=NOW_TIME;
            $info=M("MemberInvoice")->where($invoce_map)->save($data);
        }else{
            $data['uid']=$user_info['id'];
            $info=M("MemberInvoice")->add($data);
        }
        if($info){
            $root['status']=1;
            $root['msg']="保存成功";
        }else{
            $root['msg']="保存失败";
        }
        $this->ajaxReturn($root);
    }
   //计算总价
    public function count_total(){
        $return=array();
        $param = array();
        $cart_ids=I('ids')?I('ids'):0;
        $payment_id=I('payment_id');
        $delivery_id=I('addr_id');
        $score=I('score')?1:0;
        $bonus=I('bouns');
        $shop_id=I('shop_id');
        $use_account=I('use_account')?1:0;
        $account_money=I('account_money');
        $send_type=I('send_type')>0?I('send_type'):0;
        $type=I('type');
        $data=I('order_info');
        $param['cart_ids']=$cart_ids;
        $param['data']=$data;
        $param['type']=$type;
        $param['bonu']=$bonus;
        $param['score']=$score;
        $param['use_account']=$use_account;
        $param['account_money']=$account_money;
        $param['payment_id']=$payment_id;
        $param['delivery_id']=$delivery_id;
        $param['send_type']=$send_type;
        $result = D('Common/OrderInfo')->count_total($param);
       
        $this->assign($result['total_info']);
        $html=$this->fetch('cart_total');
        $return['html']=$html;
        $return['total_info']=$result['total_info'];
        //print_r($result);
        $this->ajaxReturn($return);
    }
    /**
     * 提交订单
     */
    public function sub_order(){
        if(empty($this->m_info['mobile'])){
            $data['status'] = 0;
            $data['msg'] = '请完善信息';
            $data['url'] = U('Mobile/Login/perfect');
            $this->ajaxReturn($data);
        }
        $cart_ids=I('ids');
        $param = I('post.');

        $param['data']=I("order_info");//print_r($param);exit;
        $bonus=I('bouns');
        // if($param['type'] == 11){$param['best_time'] = strtotime($param['best_time']);}
        $param['boun']=$bonus;
		
		if($param['type'] == 14 || $param['type'] == 11 || $param['type']==3){
			if($param['best_time_day'] || $param['best_time_hour']){
				$bast_day = date('Y-m-d',$param['best_time_day']);
				$bast_hour = date('H:i',$param['best_time_hour']);
				
				$param['best_time'] = strtotime($bast_day.' '.$bast_hour);
				unset($param['best_time_day'],$param['best_time_hour']);
				
				$now = NOW_TIME;
				if($param['best_time'] < $now){
					$param['best_time'] = $now+50*60;
				}
			}
		}
		// echo "<pre>";print_r($param);exit;
        $result= D("Common/OrderInfo")->sub_order($param);
        $this->ajaxReturn($result);
    }

    /**
     *支付成功
     */
    public function order_success(){
        $order_id=I("order_ids");
        $order_id_true=array_filter(explode(',',$order_id));
        $pay_id=I("id");
            $o_where=array();
        if($order_id){
            $this->assign('page_title','支付结果');
            $o_where['is_delete'] = 0;
            $o_where['_string'] ="order_id='".$order_id."' or order_id like '%,".$order_id.",%'";
            $payinfo=M('PayLog')->where($o_where)->field('type,id')->find();
            $type =$payinfo['type'];
            $this->assign('type',$type);
            if($type==3){
                $g_order_id=array_filter(explode(',',$order_id));
                $g_map['order_id']=$g_order_id[1];
                /*$gift_info=M("WinGift")->where($g_map)->field('sn_number,user_id')->find();
                //echo M("WinGift")->getLastSql();exit;
                $this->assign($gift_info);*/
            }
            if($type==20){
                //微信分享相关配置
                $wx = new \Common\Vendor\Jssdk();
                $signPackage = $wx->getSignPackage();
                $this->assign('signPackage',$signPackage);
                $map=array();
                $g_order_id=array_filter(explode(',',$order_id));
                $map['order_id']=$g_order_id[1];
                $order_goods=M("OrderGoods")->where($map)->getField('goods_id');
                $this->assign('order_goods',$order_goods);
                $this->assign('type',$type);
                $this->assign('order_id',$g_order_id[1]);
            }
			
            $count = 0;
            // 是否绑定微信
            $wx = new \Common\Vendor\Weixinopen;
            $res = $wx->wxconfig(C('appid'));
            if(!$res){$count = 0;}
            else{
                // 小票抽奖
				$xiaop_img = '';
                $title_msg = '微信二维码';
				$message_msg = '长按识别二维码关注公众号';
                $g_map=array();$g_map['status'] = 1;$g_map['class'] = 0;
                $g_map['start_time'] = array('elt',NOW_TIME);
                $g_map['end_time'] = array('egt',NOW_TIME);
                $count = M('ReceiptDraw')->where($g_map)->count();
                if($count && $type == 14){
					$title_msg = '抽奖二维码';
					$message_msg = '长按识别二维码进行抽奖';
                    $cj = 'cj'.$order_id_true[1];
                    $xiaop_img = U('Home/Qrcode/wxqrcode',array('id'=>$cj,'sp'=>1),true,true);
                }else{
                    if(C('WEIXIN_PUBLIC_NUMBER_URL')){
                        $xiaop_img=C('WEIXIN_PUBLIC_NUMBER_URL');
                    }else{
                        $wx = new \Common\Vendor\Weixinopen;
                        $result=$wx->get_authorizer_info();
                        if(!empty($result['authorizer_info']['user_name'])){
                            $qrcode=$wx->get_wxqrcode($result['authorizer_info']['user_name']);
                            if(!empty($qrcode) && str_exists($qrcode,'weixin.qq.com'))$xiaop_img=$qrcode;
                            if(C('WEIXIN_PUBLIC_NUMBER_URL') != $xiaop_img && strlen($xiaop_img)<=80){
                                $map = $save = array();
                                $map['name'] = 'WEIXIN_PUBLIC_NUMBER_URL';
                                $save['value'] = $xiaop_img;
                                M('Config')->where($map)->save($save);
                            }
                        }
                    }
                    if($xiaop_img){
                        $count = 1;
                        $xiaop_img = U('Home/Qrcode/index',array('data'=>urlencode($xiaop_img)),true,true);
                    }
                }
                $this->assign('title_msg',$title_msg);
                $this->assign('xiaop_img',$xiaop_img);
                $this->assign('message_msg',$message_msg);
            }
            if($type==3){$count=0;}
                $this->assign('is_code',$count);
            if($type!=3) {
                $add_points = look_give_double_points($order_id_true[1]);
                $this->assign('give_points', $add_points);
            }
        }
        if($pay_id){
            $this->assign('page_title','立即支付');
            $o_where['id']=$pay_id;
            $this->assign('pay_id',$pay_id);
        }
        $pay_info = M("PayLog")->where($o_where)->field(true)->find();        
        if($pay_info){
            $p_map['id']=$pay_info['payment_id'];
            $payment_info=M("Payment")->where($p_map)->find();
            $this->assign('payment_info',$payment_info);
        }else{
            $this->error("支付信息错误");
        }
        $this->assign('pay_info',$pay_info);
        if($type==20){
            $this->display('coupon_success');
        }else{
            $this->display();
        }

    }
    /**
     * 继续付款
     */
    public function continu_pay(){
        $order_id=I("order_id");
        $res=D("Common/OrderInfo")->continu_pay($order_id);
        $this->ajaxReturn($res);
    }
    /**
     * 继续付款页面加载
     */
    public function continue_payhtml(){
        $map=array();
        $map['id']=$this->member_info['id'];
        $user_info=M("Member")->where($map)->field('paypassword')->find();
        $order_id=I("order_id");if(empty($order_id))$order_id=session('jumporder_id');
        $result=D("Common/OrderInfo")->get_continue($order_id);
        if($result['status']==0){
            $this->error("参数错误",$result['url']);
        }
        session('jumporder_id',$order_id);
        $order_info=$result['data'];
        $this->assign('order_info',$order_info);
        $this->assign('order_id',$order_id);
        $this->assign('is_addcart',$result['is_addcart']);
        //判断是否有支付密码
        if(empty($user_info['paypassword'])){
        session('jump',3);
        session('jump_paypass',3);
            $this->assign('userpaypass',1);
        }
        $this->display("continue_pay");
    }

    /**
     * 继续付款计算总价
     */
    public function count_order_total(){
        $order_id=I("ids");
        $payment_id=I('payment_id');
        $use_account=I('use_account')?1:0;
        $score=I('score')?1:0;
        $type=I('type');
        $account_money=I('account_money');
        $result = D('Common/OrderInfo')->count_order_total($order_id,$type,$score,$use_account,$account_money,$payment_id);
        $this->assign($result['total_info']);
        $html=$this->fetch('cart_total');
        $return['html']=$html;
        $return['total_info']=$result['total_info'];
        //print_r($result);
        $this->ajaxReturn($return);
    }
    //继续付款提交
    public function sub_continue_order(){
        $param=I("post.");
        $result= D("Common/OrderInfo")->sub_continue_order($param);
        $this->ajaxReturn($result);
    }
}
?>