<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class MdController extends Controller
{
    protected $Url = 'https://sale.1vgy.com';
    //查询门店
    public function getMd(Request $req)
    {
        if(!in_array('',$req -> all())) {
            $lng1 = $req -> longitude;   //经度
            $lat1 = $req -> latitude;    //纬度
            $md = DB::table('md') -> where('status',1) -> get();
            $mdInfo = [];
            $markers = [];
            if(count($md)) {
                foreach($md as $key => $val) {
                    $map = explode(',',$val -> md_map);
                    $mdInfo[$key]['id'] = $val -> id;
                    $mdInfo[$key]['md_name'] = $val -> md_name;
                    $mdInfo[$key]['md_address'] = $val -> md_address;
                    $mdInfo[$key]['online_time'] = $val -> online_time;
                    $mdInfo[$key]['juli'] = round($this -> getdistance($lng1,$lat1,$map[0],$map[1]),1);

                    $markers[$key]['iconPath'] = '/images/makers.png';
                    $markers[$key]['id'] = $val -> id;
                    $markers[$key]['longitude'] = $map[0];
                    $markers[$key]['latitude'] = $map[1];
                    $markers[$key]['height'] = 28;
                    $markers[$key]['width'] = 24;
                    $callout['content'] = $val -> md_name;
                    $callout['display'] = 'ALWAYS';
                    $callout['textAlign'] = 'center';
                    $callout['padding'] = '7';
                    $callout['borderRadius'] = '10';
                    $callout['fontSize'] = '12';
                    $markers[$key]['callout'] = $callout;
                }
                
            }
            return ['code' => '1000','msg' => 'OK','markers' => $markers,'mdInfo' => $mdInfo];
        }
        return ['code' => '100','msg' => 'err','markers' => [],'mdInfo' => []];
    }
    //计算经纬度
    function getdistance($lng1, $lat1, $lng2, $lat2) {
        // 将角度转为狐度
        $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
        return $s;
    } 
    //获取现在的位置，再获取最近的门店
    public function getFirstMd(Request $req) 
    {
        // return $req -> all();
        if(!in_array('',$req -> all())) {
            $lng1 = $req -> longitude;   //经度
            $lat1 = $req -> latitude;    //纬度
            //查询首页ad图
            $ad = DB::table('index_ad') -> where('map',1) -> first();
            $index_ad = [];
            $index_ad['imgUrl'] = $this -> Url . '/' . $ad -> imgUrl;
            $index_ad['link'] = $ad -> link;
            if($req -> md == 0){   //正常第一次进入门店
                $md = DB::table('md') -> where('status',1) -> get();
                if($md) {
                    $m = explode(',',$md[0] -> md_map);
                    $md_id = $md[0] -> id;
                    $min = round($this -> getdistance($lng1,$lat1,$m[0],$m[1]),1);
                    foreach($md as $key => $val) {
                        $map = explode(',',$val -> md_map);
                        $juli = round($this -> getdistance($lng1,$lat1,$map[0],$map[1]),1);
                        if($min > $juli) {
                            $min = $juli;
                            $md_id = $val -> id;
                        }
                    }
                    $now_md = DB::table('md') -> where('id',$md_id) -> first();
                        $now_md_arr = [];
                        $now_md_arr['md_address'] = $now_md -> md_address;
                        $now_md_arr['md_name'] = $now_md -> md_name;
                        $now_md_arr['online_time'] = $now_md -> online_time;
                        $now_md_arr['md_phone'] = $now_md -> md_phone;
                        $now_md_arr['online_time'] = $now_md -> online_time;
                        $now_md_arr['up_price'] = $now_md -> up_price;
                        $now_md_arr['peisong_price'] = $now_md -> peisong_price;
                        $now_md_arr['peisong_fanwei'] = $now_md -> peisong_fanwei;
                        $now_md_arr['peisong_service'] = $now_md -> peisong_service;
                        $now_md_arr['id'] = $md_id;
                        $now_md_arr['juli'] = $min;
                        // $goodsHot = $this -> getGoodsHot($md_id);
                        //查询当前门店排名第一的商品分类   //3-31更改
                        $first_cate = DB::table('goods_cate') -> where('md_id',$md_id) -> orderBy('orders','asc') -> first();
                        $goodsOne = DB::table('goods') -> where('pid',$first_cate -> id) -> get();
                        $goodsHot = [];
                  		$new_goods = [];
                        if($goodsOne) {
                            foreach($goodsOne as $key => $val) {
                                $goodsHot[$key]['id'] = $val -> id;
                                $goodsHot[$key]['goods_name'] = $val -> goods_name;
                                $goodsHot[$key]['goods_images'] = $this -> Url . '/' . $val -> goods_images;
                                $goodsHot[$key]['price'] = $val -> price;
                                $goodsHot[$key]['goods_keywords'] = $val -> goods_keywords;
                                $goodsHot[$key]['peisong_type'] = $val -> peisong_type;
                                //查询对应商品的规格  4-1
                                $guige = DB::table('goods_guige') -> where('goods_id',$val -> id) -> get();
                                $goodsHot[$key]['guige'] = [];

                                if(count($guige)) {
                                    
                                    $new_goods['count'] = count($guige);   //规格数量
                                    $new_goods[$val -> id] = $guige;   //组装规格数组  键为商品id
                                    $goodsHot[$key]['price'] = $guige[0] -> guige_price;   //如果有规格，默认价格为第一个
                                    //$new_goods;
                                }
                            }
                        }
                        $goodsCate = $this -> getGoodsCate($md_id);
                    return ['code' => '1000','msg' => 'OK','result' => $now_md_arr,'goodsHot' => $goodsHot,'cate_name' => $first_cate -> cate_name,'goodsCate' => $goodsCate,'md_id'=>$md_id,'index_ad'=>$index_ad,'guige' => $new_goods];
                }
            }else{
                $now_md = DB::table('md') -> where('id',$req -> md) -> first();
                $now_md_arr = [];
                    $map = explode(',',$now_md -> md_map);
                    $now_md_arr['md_address'] = $now_md -> md_address;
                    $now_md_arr['md_name'] = $now_md -> md_name;
                    $now_md_arr['online_time'] = $now_md -> online_time;
                    $now_md_arr['md_phone'] = $now_md -> md_phone;
                    $now_md_arr['online_time'] = $now_md -> online_time;
                    $now_md_arr['up_price'] = $now_md -> up_price;
                    $now_md_arr['peisong_price'] = $now_md -> peisong_price;
                    $now_md_arr['peisong_fanwei'] = $now_md -> peisong_fanwei;
                    $now_md_arr['peisong_service'] = $now_md -> peisong_service;
                    $now_md_arr['id'] = $req -> md;
                    $now_md_arr['juli'] = round($this -> getdistance($lng1,$lat1,$map[0],$map[1]),1);
                    // $goodsHot = $this -> getGoodsHot($req -> md);
                    //查询当前门店排名第一的商品分类   //3-31更改
                    $first_cate = DB::table('goods_cate') -> where('md_id',$req -> md) -> orderBy('orders','asc') -> first();
                    $goodsOne = DB::table('goods') -> where('pid',$first_cate -> id) -> get();
                    $goodsHot = [];
                        if($goodsOne) {
                            foreach($goodsOne as $key => $val) {
                                $goodsHot[$key]['id'] = $val -> id;
                                $goodsHot[$key]['goods_name'] = $val -> goods_name;
                                $goodsHot[$key]['goods_images'] = $this -> Url . '/' . $val -> goods_images;
                                $goodsHot[$key]['price'] = $val -> price;
                                $goodsHot[$key]['goods_keywords'] = $val -> goods_keywords;
                                //查询对应商品的规格  4-1
                                $guige = DB::table('goods_guige') -> where('goods_id',$val -> id) -> get();
                                $goodsHot[$key]['guige'] = [];
                                if(count($guige)) {
                                    $new_goods = [];
                                    $new_goods['count'] = count($guige);   //规格数量
                                    $new_goods[$val -> id] = $guige;   //组装规格数组  键为商品id
                                    $goodsHot[$key]['price'] = $guige[0] -> guige_price;   //如果有规格，默认价格为第一个
                                    $new_goods;
                                }
                            }
                        }
                    $goodsCate = $this -> getGoodsCate($req -> md);
                return ['code' => '1000','msg' => 'OK','result' => $now_md_arr,'goodsHot' => $goodsHot,'cate_name' => $first_cate -> cate_name,'goodsCate' => $goodsCate,'md_id'=>$req->md,'index_ad'=>$index_ad,'guige' => $new_goods];

//                return ['code' => '1000','msg' => 'TWO OK','result' => $now_md_arr,'goodsHot' => $goodsHot,'cate_name' => $first_cate -> cate_name,'goodsCate' => $goodsCate,'md_id'=>$req -> md,'index_ad'=>$index_ad];
            }
        }
    }
    public function hotgoods()
    {
        $goodsHot = [];
        $goodsOne = DB::table('goods') -> where('is_recomd',1 ) -> get();
        $new_goods = [];
        foreach ($goodsOne as $key => $val)
        {
            $goodsHot[$key]['id'] = $val -> id;
            $goodsHot[$key]['goods_name'] = $val -> goods_name;
            $goodsHot[$key]['goods_images'] = $this -> Url . '/' . $val -> goods_images;
            $goodsHot[$key]['price'] = $val -> price;
            $goodsHot[$key]['goods_keywords'] = $val -> goods_keywords;
            //查询对应商品的规格  4-1
            $guige = DB::table('goods_guige') -> where('goods_id',$val -> id) -> get();
            $goodsHot[$key]['guige'] = [];
            if(count($guige)) {

                $new_goods['count'] = count($guige);   //规格数量
                $new_goods[$val -> id] = $guige;   //组装规格数组  键为商品id
                $goodsHot[$key]['price'] = $guige[0] -> guige_price;   //如果有规格，默认价格为第一个
                $new_goods;
            }
        }
        return ['code' => '1000','msg' => 'OK','goodsHot' => $goodsHot,'guige' => $new_goods];

    }
 
    //获取门店分类商品
    public function getGoodsCate($md_id)
    {
        $goodsCate = DB::table('goods_cate') -> where('md_id',$md_id) -> where('status',1) -> orderBy('orders','asc') -> get();
        return $goodsCate;
    }
    //获取现在的位置，再获取最近的门店
    public function getFirstMd1(Request $req)
    {
        // return $req -> all();
        if(!in_array('',$req -> all())) {
            $lng1 = $req -> longitude;   //经度
            $lat1 = $req -> latitude;    //纬度
            //查询首页ad图
            $ad = DB::table('index_ad') -> where('map',1) -> first();
            $index_ad = [];
            $index_ad['imgUrl'] = $this -> Url . '/' . $ad -> imgUrl;
            $index_ad['link'] = $ad -> link;
            if($req -> md == 0){   //正常第一次进入门店
                $md = DB::table('md') -> where('status',1) -> get();
                if($md) {
                    $m = explode(',',$md[0] -> md_map);
                    $md_id = $md[0] -> id;
                    $min = round($this -> getdistance($lng1,$lat1,$m[0],$m[1]),1);
                    foreach($md as $key => $val) {
                        $map = explode(',',$val -> md_map);
                        $juli = round($this -> getdistance($lng1,$lat1,$map[0],$map[1]),1);
                        if($min > $juli) {
                            $min = $juli;
                            $md_id = $val -> id;
                        }
                    }
                    $now_md = DB::table('md') -> where('id',$md_id) -> first();
                    $now_md_arr = [];
                    $now_md_arr['md_address'] = $now_md -> md_address;
                    $now_md_arr['md_name'] = $now_md -> md_name;
                    $now_md_arr['online_time'] = $now_md -> online_time;
                    $now_md_arr['md_phone'] = $now_md -> md_phone;
                    $now_md_arr['online_time'] = $now_md -> online_time;
                    $now_md_arr['up_price'] = $now_md -> up_price;
                    $now_md_arr['peisong_price'] = $now_md -> peisong_price;
                    $now_md_arr['peisong_fanwei'] = $now_md -> peisong_fanwei;
                    $now_md_arr['peisong_service'] = $now_md -> peisong_service;
                    $now_md_arr['id'] = $md_id;
                    $now_md_arr['juli'] = $min;
                    // $goodsHot = $this -> getGoodsHot($md_id);
                    //查询当前门店排名第一的商品分类   //3-31更改
                    $first_cate = DB::table('goods_cate') -> where('md_id',$md_id) -> orderBy('orders','asc') -> first();
                    $goodsOne = DB::table('goods') -> where('pid',$first_cate -> id) -> get();
                    $goodsHot = [];
                    $new_goods = [];
                    if($goodsOne) {
                        foreach($goodsOne as $key => $val) {
                            $goodsHot[$key]['id'] = $val -> id;
                            $goodsHot[$key]['goods_name'] = $val -> goods_name;
                            $goodsHot[$key]['goods_images'] = $this -> Url . '/' . $val -> goods_images;
                            $goodsHot[$key]['price'] = $val -> price;
                            $goodsHot[$key]['goods_keywords'] = $val -> goods_keywords;
                            $goodsHot[$key]['peisong_type'] = $val -> peisong_type;
                            //查询对应商品的规格  4-1
                            $guige = DB::table('goods_guige') -> where('goods_id',$val -> id) -> get();
                            $goodsHot[$key]['guige'] = [];

                            if(count($guige)) {

                                $new_goods['count'] = count($guige);   //规格数量
                                $new_goods[$val -> id] = $guige;   //组装规格数组  键为商品id
                                $goodsHot[$key]['price'] = $guige[0] -> guige_price;   //如果有规格，默认价格为第一个
                                //$new_goods;
                            }
                        }
                    }
                    $goodsCate = $this -> getGoodsCate($md_id);
                    return ['code' => '1000','msg' => 'OK','result' => $now_md_arr,'goodsHot' => $goodsHot,'cate_name' => $first_cate -> cate_name,'goodsCate' => $goodsCate,'md_id'=>$md_id,'index_ad'=>$index_ad,'guige' => $new_goods];
                }
            }else{
                $now_md = DB::table('md') -> where('id',$req -> md) -> first();
                $now_md_arr = [];
                $map = explode(',',$now_md -> md_map);
                $now_md_arr['md_address'] = $now_md -> md_address;
                $now_md_arr['md_name'] = $now_md -> md_name;
                $now_md_arr['online_time'] = $now_md -> online_time;
                $now_md_arr['md_phone'] = $now_md -> md_phone;
                $now_md_arr['online_time'] = $now_md -> online_time;
                $now_md_arr['up_price'] = $now_md -> up_price;
                $now_md_arr['peisong_price'] = $now_md -> peisong_price;
                $now_md_arr['peisong_fanwei'] = $now_md -> peisong_fanwei;
                $now_md_arr['peisong_service'] = $now_md -> peisong_service;
                $now_md_arr['id'] = $req -> md;
                $now_md_arr['juli'] = round($this -> getdistance($lng1,$lat1,$map[0],$map[1]),1);
                // $goodsHot = $this -> getGoodsHot($req -> md);
                //查询当前门店排名第一的商品分类   //3-31更改
                $first_cate = DB::table('goods_cate') -> where('md_id',$req -> md) -> orderBy('orders','asc') -> first();
                $goodsOne = DB::table('goods') -> where('pid',$first_cate -> id) -> get();
                $goodsHot = [];
                if($goodsOne) {
                    foreach($goodsOne as $key => $val) {
                        $goodsHot[$key]['id'] = $val -> id;
                        $goodsHot[$key]['goods_name'] = $val -> goods_name;
                        $goodsHot[$key]['goods_images'] = $this -> Url . '/' . $val -> goods_images;
                        $goodsHot[$key]['price'] = $val -> price;
                        $goodsHot[$key]['goods_keywords'] = $val -> goods_keywords;
                        //查询对应商品的规格  4-1
                        $guige = DB::table('goods_guige') -> where('goods_id',$val -> id) -> get();
                        $goodsHot[$key]['guige'] = [];
                        if(count($guige)) {
                            $new_goods = [];
                            $new_goods['count'] = count($guige);   //规格数量
                            $new_goods[$val -> id] = $guige;   //组装规格数组  键为商品id
                            $goodsHot[$key]['price'] = $guige[0] -> guige_price;   //如果有规格，默认价格为第一个
                            $new_goods;
                        }
                    }
                }
                $goodsCate = $this -> getGoodsCate($req -> md);
                return ['code' => '1000','msg' => 'TWO OK','result' => $now_md_arr,'goodsHot' => $goodsHot,'cate_name' => $first_cate -> cate_name,'goodsCate' => $goodsCate,'md_id'=>$req -> md,'index_ad'=>$index_ad];
            }
        }
    }

    //拿取分类下的商品
    public function getGoodsCateOne(Request $req)
    {
        if($req -> cate_id) {
            //获取分类名称
            $cate_name = DB::table('goods_cate')->where('id', $req->cate_id)->value('cate_name');
            //获取门店id
            $md_id = DB::table('goods_cate')->where('id', $req->cate_id)->value('md_id');
            //获取门店下的所有分类
            $goodsCate = DB::table('goods_cate')->where('md_id', $md_id)->where('status', 1)->orderBy('orders', 'asc')->get();
            $cateGoods = DB::table('goods')->where('pid', $req->cate_id)->where('status', 1)->orderBy('orders', 'asc')->get();
            $goods = [];
            $new_goods = [];
            if($cateGoods) {
                foreach ($cateGoods as $key => $val) {
                    $goods[$key]['id'] = $val->id;
                    $goods[$key]['goods_name'] = $val->goods_name;
                    $goods[$key]['goods_images'] = $this->Url . '/' . $val->goods_images;
                    $goods[$key]['price'] = $val->price;
                    $goods[$key]['goods_keywords'] = $val->goods_keywords;

                    //查询对应商品的规格  4-1
                    $guige = DB::table('goods_guige')->where('goods_id', $val->id)->get();
                    $goodsHot[$key]['guige'] = [];


                    $new_goods['count'] = count($guige);   //规格数量
                    $new_goods[$val->id] = $guige;   //组装规格数组  键为商品id
                    $goods[$key]['price'] = $guige[0]->guige_price;   //如果有规格，默认价格为第一个
                    $new_goods;

                }
            }

        }
            //        }else{
////            return ['code' => '1001','msg' => 'err','result' => $goods];
//        }
        return ['code' => '1000', 'msg' => $new_goods, 'result' => $goods, 'guige' => $new_goods, 'md_id' => $md_id, 'goodsCate' => $goodsCate, 'cate_id' => $req->cate_id, 'cate_name' => $cate_name];

    }
    //像是商品详情
    public function getGoodsDetail(Request $req)
    {
        $goodsDetail = DB::table('goods') -> where('id',$req -> goods_id) -> first();
        $goodsDetail2 = DB::table('goods_guige') -> where('goods_id',$req -> goods_id) -> first();
        $goods = [];
        if($goodsDetail) {
            $goods['id'] = $goodsDetail -> id;
            $goods['goods_name'] = $goodsDetail -> goods_name;
            $goods['goods_images'] = $this -> Url . '/' . $goodsDetail -> goods_images;
            $goods['price'] = $goodsDetail -> price;
            $goods['goods_keywords'] = $goodsDetail -> goods_keywords;
            $goods['goods_description'] = $goodsDetail -> goods_description;
        }
        //获取购买须知
        $xuzhi = '';
        if($req -> md_id) {
            $xuzhi = DB::table('goods_notes') -> where('md_id',$req -> md_id) -> value('content');
        }
        return ['code' => '1000','msg' => 'OK','result' => $goods,'xuzhi' => $xuzhi,'price'=>$goodsDetail2 -> guige_price,'guige_name'=>$goodsDetail2 -> guige_name];
    }
    //首页计算购物车总价和单价和 商品名
    public function numPrice(Request $req)
    {
        // return $req -> all();
        if($req -> shopCar) {
            $shopCar = json_decode($req -> shopCar,true);
            //计算总价格
            $new_shop = [];
            $allPrice = 0;
            $key = array_reverse(array_keys($shopCar));   //倒序数组 ，前台才能正插入
            $val = array_reverse(array_values($shopCar));
            
            for($i=0;$i<count($key);$i++) {
                $goods = explode('//',$key[$i]);   //拆分商品id，判断有没有规格id
                // return $goods;
                $goodsInfo = DB::table('goods') -> where('id',$goods[0]) -> first();
                $new_shop[$i]['guige_name'] = '默认';   //商品id
                $new_shop[$i]['guige_id'] = '';   //商品id
                $new_shop[$i]['type_price'] = $goodsInfo -> price * $val[$i];   //单价x数量
                if(count($goods) > 1) {   //有规格
                    $new_shop[$i]['guige_name'] = DB::table('goods_guige') -> where('goods_id',$goods[0]) -> where('id',$goods[1]) -> value('guige_name');   //商品id
                    $new_shop[$i]['guige_id'] = $goods[1];   //商品规格id
                    $new_shop[$i]['type_price'] = (int)DB::table('goods_guige') -> where('goods_id',$goods[0]) -> where('id',$goods[1]) -> value('guige_price') * $val[$i];   //单价x数量
                }
                $new_shop[$i]['goods_name'] = $goodsInfo -> goods_name;   //商品名称
                $new_shop[$i]['goods_num'] = $val[$i];   //商品数量
                $new_shop[$i]['goods_id'] = $key[$i];   //商品id
                
                $allPrice += $new_shop[$i]['type_price'];   //总价
            }
            
            return ['code' => '1000','msg' => 'OK','new_shop' => $new_shop,'allPrice' => $allPrice * 100];
        }
    }

 
    //定单确认页面
    public function getOrderPrev(Request $req)
    {
//        if(in_array('',$req -> all())) {
//            return ['code' => '1002','msg' => 'err','result' => ''];
//        }
        if($userInfo = DB::table('user') -> where('token',$req -> token) -> first()){
            //查询门店信息
            $md_id = $req -> md_id;
            $token = $req -> token;
            $key = $req -> key;
            $md = [];
            $md_info = DB::table('md') -> where('id',$md_id) -> first();
            $md['name'] = $md_info -> md_name;
            $md['peisong_price'] = $md_info -> peisong_price;
            //这里改为获取地址距离计算配送费   4-2
            //查找门店的是否设置了详细的距离和费用
            // $peisong_num = DB::table('peisong') -> where('md_id',$md_id) -> get();
            // if(count($peisong_num)){
            //     $userAddress = $userInfo -> address;
            //     $user_address_map = $this -> take_address_map($userAddress,$key);   //用户地址转换的坐标
            //     $results = json_decode($user_address_map,true);
            //     $lng = $results['result']['location']['lng'];
            //     $lat = $results['result']['location']['lat'];  //得到用户地址坐标
            //     if($lng && $lat) {
            //         //查询门店的坐标
            //         $map = explode(',',$md_info -> md_map);
            //         $juli = $this -> getdistance($lng,$lat,$map[0],$map[1]);   //用户地址和门店的距离
            //         $km = 0;
            //         foreach($peisong_num as $key => $val) {
            //             if($juli > $val -> juli) {
            //                 //用户距离大于配送距离   就进行下一档
            //             }else{
            //                 $km = $val -> id;
            //                 break;
            //             }
            //             if($km != 0){
            //                 $price = DB::table('peisong') -> where('id',$km) -> first();  //最合适的一档
            //             }else{
            //                 //等于0说明没有任何一档合适，用户的距离始终大于设置的配送距离  //就按最大的算
            //                 $price = DB::table('peisong') -> where('id',$peisong_num[count($peisong_num)-1] -> id) -> first();
            //             }
            //         }
            //         $md['peisong_price'] = $price -> price;
            //     }
            // }
            $md['id'] = $md_id;
            //查询用户地址和钱包信息
            $user['name'] = $userInfo -> name;
            $user['phone'] = $userInfo -> phone;
            $user['address'] = $userInfo -> address;
            $user['menpai'] = $userInfo -> menpai;
            $user['access_price'] = DB::table('access') -> where('user_id',$userInfo -> id) -> value('price');
            if($user['access_price'] == null) {
                $user['access_price'] = '未开通';
            }
            return ['code' => '1000','msg' => 'OK','md' => $md,'user' => $user];
        }else{
            return ['code' => '1003','msg' => 'err','result' => ''];
        }
    }
    public function cancelOrder(Request $req)//取消订单
    {
        if ($req->token) {

//            $orderuser = DB::table('user')->where('token', $req->token)->first();//token查找用户

            $delorder = DB::table('order')->where('order_id', $req -> order_feel)->delete();
            $delorder_goods = DB::table('order_goods')->where('order_id', $req -> order_feel)->delete();

            $id = DB::table('user') -> where('token',$req -> token) -> value('id');
            if(!$id) {
                return ['code' => '1001','msg' => 'err','result' => ''];
            }

                $order = DB::table('order') -> where('user_id',$id) -> get();


            //通过订单id查询商品
            if($order) {
                $goods = [];
                foreach($order as $key => $val) {
                    $now_goods = DB::table('order_goods') -> where('order_id',$val -> order_id) -> get();
                    //拿到多件商品查询商品名称
                    $goods[$key]['goods_name'] = DB::table('goods') -> where('id',$now_goods[0] -> goods_id) -> value('goods_name');   //商品名
                    $goods[$key]['goods_num'] = count($now_goods);   //数量
                    $goods[$key]['goods_price'] = $val -> price;  //价格
                    $goods[$key]['md'] = DB::table('md') -> where('id',$val -> md_id) -> value('md_name');  //门店
                    if($val -> status == 0) {
                        $goods[$key]['status'] = '订单未支付';
                    }elseif($val -> status == 1) {
                        $goods[$key]['status'] = '订单已付款';
                    }elseif($val -> status == 2){
                        $goods[$key]['status'] = '订单待发货';
                    }elseif($val -> status == 3){
                        $goods[$key]['status'] = '订单待收货';
                    }elseif($val -> status == 4) {
                        $goods[$key]['status'] = '订单已完成';
                    }
                    $goods[$key]['order_id'] = $val -> order_id;
                    $goods[$key]['order_time'] = date('Y年m月d日 H:i',$val -> order_time);
                }
            }
            if($delorder && $delorder_goods)
            {
                return ['code' => '1000', 'msg' => 'OK','result' => $goods];
            }

        }
        else {
            return ['code' => '没有该用户', 'msg' => 'no'];
        }
    }
    //查询地址编辑地址页面
    public function getAddress(Request $req)
    {
        if(!$req -> token) {
            return ['code' => '1002','msg' => 'err','result' => ''];
        }
        $user = DB::table('user') -> where('token',$req -> token) -> first();
        $address = [];
        $address['id'] = $user -> id;
        $address['name'] = $user -> name;
        $address['phone'] = $user -> phone;
        $address['address'] = $user -> address;
        $address['menpai'] = $user -> menpai;
        return ['code' => '1000','msg' => 'OK','result' => $address];
    }
    //保存地址
    public function saveAddress(Request $req)
    {
        if($id = DB::table('user') -> where('token',$req -> token) -> value('id')) {
            $user = [];
            $user['name'] = $req -> name;
            $user['phone'] = $req -> phone;
            $user['address'] = $req -> address;
            if($req -> menpai){
                $user['menpai'] = $req -> menpai;
            }else{
                $user['menpai'] = '';
            }
            $is = DB::table('user') -> where('id',$id) -> update($user);
            return $is ? ['code'=> '1000','msg'=>'保存成功'] : ['code'=> '1001','msg'=>'保存失败'];
        }else{
            return ['code' => '1002','msg' => 'err','result' => ''];
        }
    }
    public function getUserAddress(Request $req)
    {
        if($req -> token && $user = DB::table('user') -> where('token',$req -> token) -> first()) {
            $address = [];
            $address['name'] =  $user -> name;
            $address['phone'] = $user -> phone;
            $address['address'] = $user -> address;
            $address['menpai'] = $user -> menpai;
            $address['access_price'] = DB::table('access') -> where('user_id',$user -> id) -> value('price');
            return ['code' => '1000','msg' => 'OK','result' => $address];
        }
        return ['code' => '1002','msg' => 'err','result' => ''];
    }
    //获取用户优惠券
    public function getYouhui(Request $req) 
    {
        if($id = DB::table('user') -> where('token',$req -> token) -> value('id')){
            $youhui = DB::table('user_you') -> where('user_id',$id) -> get();
            //处理优惠券  判断是否过期
            if($youhui) {
                $no_use_id = [];   //未使用
                $ok_use_id = [];   //已使用
                $len_use_id = [];  //过期
                foreach($youhui as $key => $val) {
                    //按照时间判断是否过期
                    if($val -> end_date < time()) {  //已过期
                        array_push($len_use_id,$val -> id);
                    }else{  //没过期判断是否已经使用
                        if($val -> status == 1) {
                            array_push($ok_use_id,$val -> id);
                        }else if($val -> status == 0){
                            array_push($no_use_id,$val -> id);
                        }
                    }
                }
                //判断用户订单的数据
                $goods_arr = json_decode($req -> goods,true);  //确认订单商品
                $price = $req -> price / 100;
                $goods = [];
                foreach($goods_arr as $key => $val) {
                    $goods[$key] = DB::table('goods') -> where('goods_name',$val['name']) -> value('id');
                }
                //处理优惠券详情
                $no_use = $this -> takeYouHui($no_use_id,$goods,$req -> md_id,$price);
                $ok_use = $this -> takeYouHui($ok_use_id);
                $len_use = $this -> takeYouHui($len_use_id);

                return ['code'=>'1000','msg'=>'OK','no_use' => $no_use,'ok_use' => $ok_use,'len_use' => $len_use];
            }
        }
        
    }
    //处理优惠券信息
    public function takeYouHui($youhui_id,$goods=null,$md_id=null,$price=null)
    {
        if(count($youhui_id)) {
            $youhui = DB::table('user_you')-> whereIn('id',$youhui_id) -> get();
            $yh = [];
            foreach($youhui as $key => $val) {
                if($goods && $md_id) {
                    //判断门店，判断商品id
                    if($val -> md == $md_id || $val -> md == 0) {
                        $yh[$key]['is_use'] = 1;  //不可用
                        $yh[$key]['errs'] = 0;  //不可用
                        //再次判断价格是否=满足
                            if($val -> use_type == 1) {
                                //需要判断是否价格满减
                                if(!$val -> use_height) {
                                    $yh[$key]['is_use'] = 1;  
                                }else{
                                    if($val -> use_height <= $price) {
                                        $yh[$key]['is_use'] = 1; 
                                    }else{
                                        $yh[$key]['is_use'] = 0;
                                        $yh[$key]['errs'] = 2;
                                    }
                                }
                                
                            }else if($val -> use_type == 2) {
                                //一下可用
                                $size = explode(',',$val -> use_size);   //可用商品组成数组
                                foreach($size as $v) {
                                    if(in_array($v,$goods)) {
                                        //需要判断是否价格满减
                                            if($val -> use_height == 0) {
                                                $yh[$key]['is_use'] = 1;  //当前全部商品可用
                                            }else{
                                                if($val -> use_height <= $price) {
                                                    $yh[$key]['is_use'] = 1;  //当前全部商品可用
                                                }else{
                                                    $yh[$key]['is_use'] = 0;
                                                    $yh[$key]['errs'] = 3;
                                                }
                                            }
                                    }else{
                                        $yh[$key]['is_use'] = 0;  //不可用
                                        $yh[$key]['errs'] = 4;
                                    }
                                }
                            }else{
                                //不可用商品
                                $size = explode(',',$val -> use_size);   //可用商品组成数组
                                foreach($size as $v) {
                                    if(in_array($v,$goods)) {
                                        $yh[$key]['is_use'] = 0;  //不可用
                                        $yh[$key]['errs'] = 5;
                                    }else{
                                        //需要判断是否价格满减
                                            if($val -> use_height == 0) {
                                                $yh[$key]['is_use'] = 1;  //当前全部商品可用
                                            }else{
                                                if($val -> use_height <= $price) {
                                                    $yh[$key]['is_use'] = 1;  //当前全部商品可用
                                                }else{
                                                    $yh[$key]['is_use'] = 0;
                                                    $yh[$key]['errs'] = 6;
                                                }
                                            }
                                    }
                                }
                            }
                    }else{
                        $yh[$key]['is_use'] = 0;
                    }

                }else{
                    $yh[$key]['is_use'] = 0;  //当前可用   4-9
                }
                
                $yh[$key]['id'] = $val -> id;   //优惠券名字
                $yh[$key]['name'] = $val -> name;   //优惠券名字
                
                if($val -> md == 0) {
                    $yh[$key]['md'] = '所有门店';   //使用门店
                    $yh[$key]['md_id'] = $val -> md;   //使用门店id
                }else{
                    $yh[$key]['md'] = DB::table('md') -> where('id',$val -> md) -> value('md_name');
                    $yh[$key]['md_id'] = $val -> md;   //使用门店id
                }
                
                if($val -> type == '1') {
                    $yh[$key]['type'] = '元';
                    $yh[$key]['price'] = $val -> price;  //直减金额
                    $yh[$key]['use_height'] = $val -> use_height;  //满减门槛
                }else{
                    $yh[$key]['type'] = '折';
                    $yh[$key]['price'] = $val -> price / 10;  //折扣力度
                    $yh[$key]['use_height'] = $val -> use_height;  //满减门槛
                }
                $yh[$key]['goods_use_type'] = $val -> use_type;   //以下可用或不可用
                if($val -> use_type == 2) {
                    $yh[$key]['goods_use'] = $val -> use_size;  //可用商品
                }else if($val -> use_type == 3) {
                    $yh[$key]['goods_use'] = $val -> use_size;  //不可用商品
                }else{
                    $yh[$key]['goods_use'] = '';  //全部可用
                }
                $yh[$key]['vip'] = $val -> vip;   //是否vip券   4-3
                $yh[$key]['end_date'] = date('Y年m月d日 H:i:s',$val -> end_date);  //失效时间
            }
            return $yh;
        }
        return '';
        
    }
    public function getPrice(Request $req)
    {
        $yh = json_decode($req -> yh);
        $price = $req -> price / 100;
        $yh_type = $yh[1];
        $yh_price = $yh[2];
        $yh_id = $yh[0];
        $user_yh = DB::table('user_you') -> where('id',$yh_id) -> first();
        if($user_yh -> status == 0) {
            if($user_yh -> type == 1) {
                $res_price = $price - $user_yh -> price;
                $yh_name = '直减'.$user_yh -> price.'元';
            }else{
                $res_price = $price * ($yh_price/10);
                $yh_name = '折扣'.($yh_price / 10).'折';
            }
            return ['code' => '1000','msg' => 'OK','price' => $res_price * 100,'yh_id' => $user_yh -> id,'yh_name' => $yh_name];
        }else{
            return ['code' => '1003','msg' => 'err','result' => '优惠券异常'];
        }
    }
    //点击配送后判断地址的距离和门店是否超过了规定的距离
    public function is_juli(Request $req)
    {
        if(!in_array('',$req -> all())) {
            $md = json_decode($req -> md,true);
            $user = json_decode($req -> user,true);
            $key = $req -> key;
            //根据用户地址获取坐标
            $address = $user['address'].$user['menpai'];
            $user_address_map = $this -> take_address_map($address,$key);   //用户地址转换的坐标
            $results = json_decode($user_address_map,true);
            $lng = $results['result']['location']['lng'];
            $lat = $results['result']['location']['lat'];
            if($lng && $lat) {
                //查询门店的坐标
                $md_info = DB::table('md') -> where('id',$md['id']) -> first();
                $map = explode(',',$md_info -> md_map);
                $juli = $this -> getdistance($lng,$lat,$map[0],$map[1]);
                //判断是否距离超过了
                if($juli < $md_info -> peisong_fanwei) {
                    //在范围内
                    return ['code' => '1000','msg' => 'OK','result' => 1];
                }else{
                    return ['code' => '1000','msg' => 'OK','result' => 0];
                }
            }else{
                return ['code' => '1001','msg' => 'err','result' => '解析位置信息失败'];
            }
        }else{
            return ['code' => '1002','msg' => 'err','result' => '参数错误'];
        }
    }
    //腾讯地图地址转坐标
    public function take_address_map($address,$key)
    {
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/?key='.$key.'&address='.$address.'&output=json';
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;
    }
    //购物车自动获取手机号码
    public function getPhone(Request $req)
    {
            $appid = $req -> appid;//自己配置
            $AppSecret = $req -> secret;//自己配置
            $code =$req -> code;
            $encryptedData = $req -> encryptedData;
            $iv = $req -> iv;
            $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$AppSecret."&js_code=".$code."&grant_type=authorization_code";
            $arr = $this->vget($url);  // 一个使用curl实现的get方法请求
            $arrs = json_decode($arr,true);
            $openid = $arrs['openid'];
            $session_key = $arrs['session_key'];
            $pc = new \WXBizDataCrypt($appid, $session_key);
            $errCode = $pc->decryptData($encryptedData, $iv, $data);
            $datas = json_decode($data,true);
            DB::table('user') -> where('openid',$openid) -> update(['phone' => $datas['purePhoneNumber']]);
            return $this -> getUser($openid);
    }
    //再次更新后查询用户信息
    public function getUser($openid)
    {
        //再查询出来
        $user = DB::table('user') -> where('openid',$openid) -> first();
        $userInfo['name'] = $user -> name;
        $userInfo['phone'] = $user -> phone;
        $userInfo['address'] = $user -> address;
        $userInfo['menpai'] = $user -> menpai;
        $userInfo['access_price'] = DB::table('access') -> where('user_id',$user->id) -> value('price');
        return ['code' => '1000','msg' => 'OK','result' => $userInfo];
    }

    public function vget($url)
    {
        $info=curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info,CURLOPT_URL,$url);
        $output= curl_exec($info);
        curl_close($info);
        return $output;
    }
}
