<?php
/** 自助购新加控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <xiaoq@570035208.com>
 */

namespace Wxsmall\Controller;
class SelfgoController extends BaseController {
	public function _initialize(){
        	parent::_initialize ();
    }
    /**
	 * 获取附近门店列表页
	 */
	public function index(){
		$param = I('param.');
		$user_info=$this->checkuserauth();
		$param['uid']=$user_info['id'];
		$param['shop_id']=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店

       
        //$data=D('Mobile/Takeout')->get_cate_list();
		$result = D('Selfgo')->index($param);
		$result['HCshop'] = $user_info['HCshop'];//当前会员匹配的门店存储到客户端
        $cart_info=D('Selfgo')->get_cart_total_info($user_info['id']);
        $result['cart_info']=$cart_info;

        $result['data']['self_num'] = C('WEB_SELFGO_NUM');
		$this->ajaxReturn($result);
	}
	/**
     * 获取商品价格
     */
    public function get_goods_price(){
        $return=array('status'=>1);
        $param=I('post.');
        $goods_ids=explode(',',$param['goods_ids']);
        $goods_price_info=array();
        if($goods_ids){
            foreach($goods_ids as $key=>$val){
                $price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$val);
                $goods_price_info[$key]['shop_price']=$price_info['goods_price'];
                $goods_price_info[$key]['id']=$val;
                $goods_price_info[$key]['sprice']=format_price($price_info['goods_price']);
            }
        }
        $return['data']=$goods_price_info;
        $data_takout=D('Common/Takeout')->get_goods_list();
        $return['data']['takout_info'] = $data_takout;
        $this->ajaxReturn($return);
    }
    //加入购物车
     public function add_carts(){
        $param=I('param.');
        if($param['goods_attr']){
           $goods_attr= json_decode(htmlspecialchars_decode($param['goods_attr']),true);
        }
        if($goods_attr){
            $param['spec']=$goods_attr['key'];
            $param['name']=$goods_attr['name'];
        }
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $param['shop_id']=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $data=D("Common/Takeout")->add_cart_item($param);
        $cart_info=D("Selfgo")->get_cart_total_info($user_info['id']);
        $data['cart_info']=$cart_info;
        $this->ajaxReturn($data);
    }

    //页面加减加入购物车
    public function add_cart(){
        $param=I("post.");
        $map=array();
        $map['id']=$param['cart_id'];
        $spc=M("Cart")->where($map)->getField('goods_attr');
        if($spc){
            $goods_attr=unserialize($spc);
            $param['spec']=$goods_attr['key'];
            $param['name']=$goods_attr['name'];
        }
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $param['shop_id']=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $param['is_wxsmall']=1;
        $result=D("Common/Takeout")->add_cart_item($param);
        $this->ajaxReturn($result);
    }
    //end

    //订单详情页面加载
    public function buy_order(){
        $return=array('status'=>1);
        $param=I('param.param');
        $params = json_decode(htmlspecialchars_decode($param),true);
        $goods_arr=array();
        $total_num = 0;
        $total_money=0;
        $shop_id=1;
        $user_info=$this->checkuserauth();

        foreach($params as $kk=>$vv){
            if(str_exists($kk,'-')){
                $goods_ids = explode('-',$kk);
                $goods_id = $goods_ids[0];
                $info = idtoname($goods_id,'Goods','goods_sn,goods_name,img','id',false);
                $info['goods_num'] = $vv['num'];
                $info['price'] = format_decimal($vv['price']/$vv['num']); //这个价格目前是调的缓存里面的，后期可能需要调用get_min_price函数里面的
                $info['id']=$goods_id;
                if($vv['goods_attr']){
                    $params_h = json_decode(htmlspecialchars_decode($vv['goods_attr']),true);
                    $info['attr_key']=$params_h['key'];
                    $info['attr_name']=$params_h['name'];
                    $price_info=D('Pad/Cashier')->get_min_price($shop_id,$goods_id,$user_info,$params_h);
                    $info['price_type'] = $price_info['price_type'];
                }else{
                    $price_info=D("Common/Takeout")->get_min_price($shop_id,$goods_id);//获取商品最终价格
                    $info['price_type'] = $price_info['price_type'];
                }
                $goods_arr['goods_list'][]= $info;
                
            }
            $total_num+=$vv['num'];
            $total_money+=$vv['price'];

        }
        //1025
        $params['total_money'] = format_decimal($total_money);
        $params['uid'] = $user_info['id'];
        $result = D('Selfgo')->index($params);


        //end

        
        $return['data'] = $goods_arr;
        $return['data']['total_num'] = $total_num;
        $return['data']['selfgo_num'] = C('WEB_SELFGO_NUM');
        $return['data']['total_money'] = $total_money;
        $return['data']['user_info'] = $user_info;
        $return['data']['coupons'] = $result['data']['coupons'];
        $this->ajaxReturn($return);
    }

    /**
     * 计算价格
     */
    public function count_total(){
        $return=array('status'=>1);
        $cparam=I('param.cart_list');
        $total_price = 0;
        $cart_list = json_decode(htmlspecialchars_decode($cparam),true); //商品信息
        foreach($cart_list as $kl=>$vl){
            $total_price += $vl['price'];
        }
        $param = I('param.param');
        $params = json_decode(htmlspecialchars_decode($param),true);

        $use_account=intval($params['use_account']);
        $user_info=$this->checkuserauth();


        //网银支付
        if($payment_id>0 && $payment_id!=1){    //获取手续费
            $payment_info=idtoname($payment_id,'Payment','*');
            $counter_fee=$payment_info['fee'];
        }

        $pay_price = $total_price;
        if($pay_price>0 && $use_account==1 ){   //余额支付
            if($user_info['money']>0 && $user_info['money']>$pay_price){
                $account_money=$pay_price;
            }else{
                $account_money=$user_info['money'];
            }
            $pay_price=$pay_price-$account_money;
        }
        //拿着open_id去member表里查一下，要是有，就按照会员的走，没有就不走
        // $param['bonu']['id']=$param['bonus_id'];
        // $param['bonu']['money']=$param['bonus_money'];
        $param['uid']=$user_info['id'];
        $return['total_info']=array(
            'total_price'=>format_decimal($total_price),//商品总价
            'pay_price'=>format_decimal($pay_price),//线上支付价格
            // 'use_score'=>format_decimal($use_score),//使用的积分的钱
            // 'score'=>$pay_score,//使用的积分
            // 'use_score_money'=>format_decimal($use_score_money),//积分抵扣的价格
            // 'bonu_money'=>format_decimal($bonu_money),//红包/优惠抵扣的价格
            // 'active_money'=>format_decimal($active_money),//活动优惠
            'account_money'=>format_decimal($account_money),//使用余额
            'payment_info'=>$payment_info,//使网银支付信息
        );
        // $info=D('Common/OrderInfo')->count_total($param);
        $this->ajaxReturn($return);
    }
    //提交订单
    public function submit_order(){

        // $asd = 'a:2:{s:3:"key";s:2:"13";s:4:"name";s:33:"唇釉色彩:#378粉红火烈鸟 ";}';

        // $cv = unserialize($asd);
        // var_dump($cv); die;
        $user_info=$this->checkuserauth();
        $return=array('status'=>1);
        $shop_id=1;
        $type = 25;
        $param=I('param.cart_list');
        $goods_list = json_decode(htmlspecialchars_decode($param),true); //商品信息

        //其他参数
        $params = I('param.param');
        $params = json_decode(htmlspecialchars_decode($params),true);

        $use_account=intval($params['use_account']);
        $payment_id=$params['payment_id']?$params['payment_id']:0;//支付方式
        $source=3;//来源：0电脑，1手机2app

        $pay_pwd=$params['pay_pwd'];//交易密码

        //1019
        if($use_account==1){
            $m['id']=$user_info['id'];
            $userinfo=M("Member")->where($m)->field('paypassword,salt')->find();
            if($userinfo['paypassword'] == ''){
                $return['status'] = 3;
                $return['msg']="请到微商城设置会员支付密码";
                $this->ajaxReturn($return);exit();
            }
            if($pay_pwd=='' || creatpwd($pay_pwd,'HANCHAO'.$userinfo['salt']) != $userinfo['paypassword']){
                $return['status'] = 3;
                $return['msg']='支付密码错误';
                $this->ajaxReturn($return);exit();
            }
        }
        

        
        $order_info=D('Selfgo')->add_order($goods_list,$payment_id,$source,$type,$user_info);
        if($order_info['status']==1){
            $order_ids=$order_info['order_id'];
        }else{
            $return['msg']=$order_info['msg'];
            $this->ajaxReturn($return);
        }
        $total_money = 0;
        foreach($goods_list as $key=>$val){
            $total_money+=$val['price'];
        }
        $payment_info=array();
        $payment_info['order_id']=$order_ids;
        $payment_info['user_id']= $user_info['id'];
        $payment_info['type']=$type;
        $payment_info['order_sn']= createOrderNo();


        
        $payment_info['use_money']=$params['total_price'];//余额

        $payment_info['need_pay']=($params['total_info']['pay_price']<0?0:$params['total_info']['pay_price']);

        // $payment_info['need_pay']=($data['total_info']['pay_price']<0?0:$data['total_info']['pay_price']);

        // $payment_info['need_pay']=($params['total_price']<0?0:$params['total_price']);
        //还需支付的金额
        $payment_info['use_score']=$data['total_info']['score']>0?$data['total_info']['score']:0;//积分
        // $payment_info['use_score_money']=$data['total_info']['use_score_money'];//积分所抵的钱
        // $payment_info['order_total_price']=$data['total_info']['pay_total_price'];//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
        $payment_info['order_total_price']=$params['total_price'];
        $payment_info['payment_id']=$payment_id;//支付方式
        // $payment_info['payment_fee']=$data['total_info']['pay_fee'];//支付手续费
        $payment_info['pay_amount']=0;//
        $payment_info['pay_code']=idtoname($payment_id,"Payment",'code');//支付code
        $payment_info['is_paid']=0;
        $payment_info['create_time']=NOW_TIME;
        // $payment_info['wxsmall_formid_cache']=empty($param['formId'])?'':$param['formId'];
        $payment_info['shop_id']=$shop_id;
        //生成支付单
        $pay_log_id=M('PayLog')->add($payment_info);
        if($pay_log_id){
            if($use_account==1){
                if($params['total_price']>0){
                    account_change($user_info['id'],-$params['total_price'],1,4,'自助购购买商品支付，订单'.$order_info['order_sn']);
                }
            }else{
                //线上支付价格
                $payment_info = idtoname($payment_id,'Payment','*');
                if($params['total_price']>0 && $payment_info){
                    $return['pay']=$pay_log_id;
                    $return['status']=1;
                    $this->ajaxReturn($return);exit();
                }
            }
            
            //处理订单
            $pay_info=array();
            $pay_info['out_trade_no']=$payment_info['order_sn'];
            $pay_info['type']=$payment_info['type'];
            $res=D('Selfgo')->endorder($pay_info);
            if($res['status']==1){
                $return['status']=1;
                $return['data']=$order_ids;
                $this->ajaxReturn($return);
            }else{
                $return['msg']=$res['msg'];
                $this->ajaxReturn($return);
            }
            //end
            
        }else{
            $return['msg']="支付单生成失败";$this->ajaxReturn($return);
        }
        $this->ajaxReturn($return);
    }

    //查看订单
    public function get_orderinfo(){
        $param=I('param.');
        $order_id = $param['order_id'];
        $res = D('Selfgo')->get_orderinfo($order_id);
        $this->ajaxReturn($res);


    }

    //查看订单码
    public function get_ordercode(){
        $param=I('param.');
        $order_id = $param['order_id'];
        $res = D('Selfgo')->get_orderinfo($order_id,1);
        $this->ajaxReturn($res);
    }

    //查看自己的订单
    public function get_myorders(){
        $param=I('param.');
        $return=array('status'=>1);
        $user_info=$this->checkuserauth();
        $map=array();
        if($user_info){
            $map['uid'] = $user_info['id'];
        }else{
            //1.获取微信open_id
            $opne_id = 'o2Bwc5IBB8-iF6yLhadVr5o8cHRI';
            //2.查询
            $map['open_id'] = $opne_id;
        }
        $map['type'] =25;
        $info = M('OrderInfo')->where($map)->field(true)->select();
        if($info){
            foreach($info as $key=>$val){
                $info[$key]['shop_name'] = idtoname($val['shop_id'],'Shops','name','id',false);
                $info[$key]['pay_name'] = idtoname($val['payment_id'],'Payment','name','id',false);
                $info[$key]['pay_time'] = time_format($val['pay_time']);
            }
            $return['data']['list'] = $info;
        } 
        $this->ajaxReturn($return);

    }

    //点击确定改变订单状态
    public function complete_order(){
        $param=I('param.');
        $return=array('status'=>1);
        $order_id = $param['order_id'];
        if(empty($order_id)){
            $return['status'] = 3;
            $return['msg'] = '参数错误';
            $this->ajaxReturn($return);exit();
        }
        $save=$map=$where=$osave=array();
        $map['id'] = $order_id;
        $map['type'] = 25;
        $map['shipping_status'] = 4;
        $map['status'] = 3;

        $is_true = M('OrderInfo')->where($map)->count();
        if($is_true==0){
            $save['shipping_status'] = 4;
            $save['status'] = 3;
            $maps['id'] = $order_id;
            $save_id = M('OrderInfo')->where($maps)->save($save);

            if($save_id){
                $where['order_id'] = $order_id;
                $osave['status'] = 2;
                $ogoods = M('OrderGoods')->where($where)->save($osave);
                if($ogoods) $return['msg']='订单已确认完成';
            }
        }
        $return['is_true'] = $is_true; 
        $this->ajaxReturn($return);


    }
    //end

    //首页加载时判断缓存
    public function getcatchs(){

        // $asd = '{"72-":{"num":3,"price":75,"overtime":"2018-10-19"},"73-35":{"num":2,"price":60,"overtime":"2018-10-19"},"73-36":{"num":2,"price":120,"overtime":"2018-10-19"}}';
        //$user_info=$this->checkuserauth();
        $return=array('status'=>1);
        $param=I('param.param');
        $params = json_decode(htmlspecialchars_decode($param),true);    
        //判断失效时间
        $new_arr=array();
        $nums=0;
        $prices = 0.00;
        foreach($params as $kk=>$vv){
            if(strtotime($vv['overtime'])>NOW_TIME){
                $new_arr[$kk] = $vv;
            }
        }

        if(count($new_arr)>0) $return['data'] = $new_arr;
        // if(count($new_arr)>0){
        //     // foreach($new_arr as $k=>$v){
        //     //     $nums += $v['num'];
        //     //     $prices +=$v['price'];
        //     // }
        //     $return['data']['list'] = $new_arr;
        // }
        // $return['data']['nums'] = $nums;
        // $return['data']['prices'] = format_decimal($prices);
        
        
        $this->ajaxReturn($return);

    }

    /**
     * 获取扫码的商品
     */
    public function scan_get_goods(){
        $return=array('status'=>3);
        $code=I('code');
        $postdata=array();
        $postdata['sn']=$code;
        $postdata['is_cashier']=1;
        $postdata['is_shop']=1;
        $data=D("Common/InvoicingOrder")->search_by_sn($postdata);
        if($data['status']==0){
            $return['msg']=$data['msg'];
        }else{
            if($data['data']['list']['attr_key']){
                $attr=array();
                $attr['key']=$data['data']['list']['attr_key'];
                $attr['name']=$data['data']['list']['name'];
                $data['data']['list']['goods_attr']=json_encode($attr);
            }
            $return['data']=$data['data'];
            $return['msg']=$data['msg'];
            $return['status']=1;
        }
        $this->ajaxReturn($return);
    }
}
?>