<?php


namespace app\api\controller;


use addons\epay\library\Service;
use app\api\model\GoodsComment;
use app\api\model\RiderOrder;
use app\api\model\Third;
use app\api\model\UserMoneyLog;
use app\api\model\Withdraw;
use app\common\controller\Api;
use app\common\model\User;
use EasyWeChat\Factory;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 骑手
 */
class Rider extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['service'];

    /**
     * @ApiTitle    (骑手订单页)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=type, type=integer, required=true, description="1配送中2=已完成")
     * @ApiParams   (name=page, type=integer, required=true, description="页数")
     * @ApiParams   (name=lat, type=integer, required=true, description="骑手纬度")
     * @ApiParams   (name=lng, type=integer, required=true, description="骑手经度")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':
        "total": 2,
        "per_page": 5,
        "current_page": 1,
        "last_page": 1,
        "data": [
            {
            "id": 1,
            "distance": 111.263, 距离
            "address": {
                "name": "1", 收件人
                "phone": "13549059988", 电话号码
                "detail": "阿松大", 地址
                "address": "阿松大", 门牌号
            },
            "orderdetail": {
                "order_no": "LQ-16420622494781", 订单编号
                "createtime_text": ""
            }
            }
        ]
    })
     */
    public function index()
    {
        $type = $this->request->post('type');
        $page = $this->request->post('page',1);
        $lat = $this->request->post('lat');
        $lng = $this->request->post('lng');
        if (!in_array($type,[1,2])) $this->error('type参数不合法');
        if (!is_numeric($page)) $this->error('页数不合法');
        if (!is_numeric($lat)) $this->error('纬度不合法');
        if (!is_numeric($lng)) $this->error('经度不合法');
        $model = new RiderOrder();
        if ($type == 1){
            $EARTH=6378.137; //地球半径
            $PI=3.14; //PI值 圆周率
            $list = $model
                ->with(['address','orderdetail'])
                ->where('fa_rider_order.user_id',$this->auth->id)
                ->where('fa_rider_order.status','1')
                ->field('Round((2 * '.$EARTH.'* ASIN(SQRT(POW(SIN('.$PI.'*('.$lat.'-lat)/360),2)
            +COS('.$PI.'*'.$lat.'/180)* COS(lat * '.$PI.'/180)
            *POW(SIN('.$PI.'*('.$lng.'-lng)/360),2)))),3) as distance')
                ->order('distance')
                ->paginate(5,false,['page'=>$page])
                ->each(function ($item,$key){
                    $item->getRelation('orderdetail')->visible(['order_no']);
                    $item->getRelation('address')->visible(['name','phone','address','detail']);
                    $item->visible(['orderdetail','address','distance','id']);
                });
        }else{
            $list = $model
                ->with(['address','orderdetail'])
                ->where('fa_rider_order.user_id',$this->auth->id)
                ->where('fa_rider_order.status','2')
                ->order('fa_rider_order.id','desc')
                ->paginate(5,false,['page'=>$page])
                ->each(function ($item,$key){
                    $item->getRelation('orderdetail')->visible(['order_no']);
                    $item->getRelation('address')->visible(['name','address','detail']);
                    $item->visible(['orderdetail','address','distance','id']);
                });
        }

        $this->success('订单列表',$list);
    }


    /**
     * @ApiTitle    (骑手个人页面)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':
        "avatar": 头像,
        "nickname": 昵称,
        "money": 余额,
        "today_price": 今日所得,
        "seven_price": 七日所得,
        "all_price": 历史所得,
        "today_order": 今日订单数,
        "seven_order": 七日订单数,
        "all_order": 历史订单数,
    })
     */
    public function userIndex()
    {
        $data = [
            'avatar' => cdnurl($this->auth->avatar,true),
            'nickname' => $this->auth->nickname,
            'money' => $this->auth->money
        ];
        $model = new RiderOrder();
        $todaytime = strtotime(date('Y-m-d',time()));
        $seventime = $todaytime-86400*7;
        $today = $model
            ->where('user_id',$this->auth->id)
            ->where('status','2')
            ->where('sendtime','>',$todaytime)
            ->sum('price');
        $todaycount = $model
            ->where('user_id',$this->auth->id)
            ->where('status','2')
            ->where('sendtime','>',$todaytime)
            ->count();
        $seven = $model
            ->where('user_id',$this->auth->id)
            ->where('status','2')
            ->where('sendtime','>',$seventime)
            ->sum('price');
        $sevencount = $model
            ->where('user_id',$this->auth->id)
            ->where('status','2')
            ->where('sendtime','>',$seventime)
            ->count();
        $all = $model
            ->where('user_id',$this->auth->id)
            ->where('status','2')
            ->sum('price');
        $allcount = $model
            ->where('user_id',$this->auth->id)
            ->where('status','2')
            ->count();
        $data['today_price'] = $today;
        $data['seven_price'] = $seven;
        $data['all_price'] = $all;
        $data['today_order'] = $todaycount;
        $data['seven_order'] = $sevencount;
        $data['all_order'] = $allcount;
        $this->success('骑手个人页',$data);
    }


    /**
     * @ApiTitle    (骑手未送达订单详情)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiHeaders  (name=id, type=integer, required=true, description="骑手订单id")
     * @ApiHeaders  (name=lat, type=float, required=true, description="纬度")
     * @ApiHeaders  (name=lng, type=float, required=true, description="经度")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':
    "id": 7,
    "order_no": "LQ-16420622494781", 订单编号
    "distance": 111.3195, 距离
    "address": {
        "id": 1,
        "name": "1", 姓名
        "phone": "13549059988",
        "detail": "阿松大1", 门牌号
        "address": "阿松大", 地址
        "order_id": 7,
        "user_id": 1,
        "lat": "116.397128",
        "lng": "39.916527",
        "createtime": 0,
        "province_id": 1,
        "city_id": 2,
        "region_id": 3,
        "mobile_hide": "135****9988"  电话号码
    },
    "goods": [
        {
        "goods_name": "Mate 20 华为 HUAWEI ",
        "goods_attr": "极光色 8GB+128GB",
        "image_text": "http://temporaryfood.qiniu.broing.cn123132"
        },
        {
        "goods_name": "MacBook Pro 13寸",
        "goods_attr": "天空灰",
        "image_text": "http://temporaryfood.qiniu.broing.cn123132"
        }
    ],
    "createtime_text": ""
    })
     */
    public function orderDetail()
    {
        $id = $this->request->post('id');
        $lat = $this->request->post('lat');
        $lng = $this->request->post('lng');
        $rider_order = RiderOrder::get($id);
        $ordermodel = new \app\api\model\Order();
        $order = $ordermodel
            ->with(['address','goods'])
            ->where('fa_litestore_order.id',$rider_order['order_id'])
            ->find();
        $order->visible(['order_no','address','goods','id','distance']);
        foreach ($order->getRelation('goods') as $key => $value){
            $value->visible(['goods_name','goods_attr','total_num']);
        }
        $lat1 = $order['address']['lat'];
        $lng1 = $order['address']['lng'];
        $lat2 = $lat;
        $lng2 = $lng;
        $order['distance'] = getDistance($lat1,$lng1,$lat2,$lng2);
        $this->success('骑手个人页',$order);
    }


    /**
     * @ApiTitle    (骑手已送达订单详情)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiHeaders  (name=id, type=integer, required=true, description="骑手订单id")
     * @ApiReturn   ({
    'code':'1',
    'msg':'订单详情'
    'data':
    "id": 7,
    "order_no": "LQ-16420622494781", 订单编号
    "distance": 111.3195, 距离
    "address": {
        "id": 1,
        "name": "1", 姓名
        "phone": "13549059988",
        "detail": "阿松大1", 门牌号
        "address": "阿松大", 地址
        "order_id": 7,
        "user_id": 1,
        "lat": "116.397128",
        "lng": "39.916527",
        "createtime": 0,
        "province_id": 1,
        "city_id": 2,
        "region_id": 3,
        "mobile_hide": "135****9988"  电话号码
    },
    "goods": [
        {
        "goods_name": "Mate 20 华为 HUAWEI ",
        "goods_attr": "极光色 8GB+128GB",
        "total_num": "1", 购买数量
        "image_text": "http://temporaryfood.qiniu.broing.cn123132"
        },
        {
        "goods_name": "MacBook Pro 13寸",
        "goods_attr": "天空灰",
        "total_num": "1",
        "image_text": "http://temporaryfood.qiniu.broing.cn123132"
        }
    ],
    "createtime_text": ""
    })
     */
    public function orderOverDetail()
    {
        $id = $this->request->post('id');
        $rider_order = RiderOrder::get($id);
        $ordermodel = new \app\api\model\Order();
        $order = $ordermodel
            ->with(['address','goods'])
            ->where('fa_litestore_order.id',$rider_order['order_id'])
            ->find();
        $order->visible(['order_no','address','goods','id','distance','comment']);
        foreach ($order->getRelation('goods') as $key => $value){
            $value->visible(['goods_name','goods_attr','total_num']);
        }
        $comment = new GoodsComment();
        $content = $comment->where('order_id',$order->id)->select();
        $order['comment'] = $content;
        $this->success('订单详情',$order);
    }


    /**
     * @ApiTitle    (骑手已送达)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiHeaders  (name=id, type=integer, required=true, description="骑手订单id")
     * @ApiReturn   ({
    'code':'1',
    'msg':'送达成功'
    })
     */
    public function orderService()
    {
        $id = $this->request->post('id');

        $rider_order = RiderOrder::get($id);
        empty($rider_order) && $this->error('骑手订单不存在');
        $ordermodel = new \app\api\model\Order();
        $order = $ordermodel->get($rider_order['order_id']);
        empty($order) && $this->error('订单不存在');
        if ($order['rider_status'] == 20) $this->error('该订单已送达');

        // 修改订单信息
        $order->rider_status = '20'; //送达状态:已送达
        $order->receipt_status = '20'; //收货状态:已收货
        $order->receipt_time = time(); //收货时间
        $order->order_status = '30'; //订单状态变为已完成
        $order->save();
        // 修改配送单信息
        $rider_order->status = '2'; //已送达
        $rider_order->sendtime = time(); //送达时间
        $rider_order->save();
        // 发放订单运费
        User::money($order->rider_price,$order->rider_user_id,'订单运费');

        $this->success('送达成功',$order);
    }


    /**
     * @ApiTitle    (骑手提现)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiHeaders  (name=money, type=integer, required=true, description="提现金额")
     * @ApiReturn   ({
    'code':'1',
    'msg':'提现成功'
    })
     */
    public function withdraw()
    {
        $money = $this->request->post('money');
        $user = $this->auth->getUser();
        if ($user['money'] < $money) $this->error('可提现金额不足');
        // 禁止连点
        !empty(cache('withdraw_'.$user['id'])) && $this->error('提现频繁,请稍后再试');
        cache('withdraw_'.$user['id'],'123',5);

        Db::startTrans();
        try{
            $order_sn = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            $withdraw = Withdraw::create([
                'user_id' => $user['id'],
                'order_sn' => $order_sn,
                'money' => $money,
            ]);
            // 变更会员余额
            User::money(-$money,$user['id'],'提现');

            $config = Service::getConfig('wechat');
            $config['app_id'] = $config['miniapp_id'];
            $config['cert_path'] = $config['cert_client'];
            $config['key_path'] = $config['cert_key'];
            $app = Factory::payment($config);
            $result = $app->transfer->toBalance([
                'partner_trade_no' => $order_sn, // 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有符号)
                'openid' => Third::where('user_id',$this->auth->id)->value('openid'),
                'check_name' => 'NO_CHECK', // NO_CHECK:不校验真实姓名, FORCE_CHECK:强校验真实姓名
//                    're_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK,则必填用户真实姓名
                'amount' => $money * 100, // 企业付款金额,单位为分
                'desc' => '骑手提现', // 企业付款操作说明信息。必填
            ]);
            \think\Log::write('企业付款到返回数据:'.json_encode($result,JSON_UNESCAPED_UNICODE));
            if($result['result_code'] != 'SUCCESS'){
                $this->error($result['err_code_des']);
            }
            // 记录企业付款单号
            $withdraw->payment_no = $result['payment_no'];
            $withdraw->payment_time = $result['payment_time'];
            $withdraw->status = '1';
            $withdraw->save();

            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提现成功');
    }

    /**
     * @ApiTitle    (骑手提现页面)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'提现成功'
    })
     */
    public function withdrawDetail()
    {
        $data = [
            'money' => $this->auth->money,
            'content' => Config::get('site.withdraw_content')
        ];
        $this->success('提现成功',$data);
    }


    /**
     * @ApiTitle    (联系客服)
     * @ApiMethod   (POST)
     * @ApiReturn   ({
    'code':'1',
    'msg':'客服信息'
    })
     */
    public function service()
    {
        $data = [
            'qrcode' => cdnurl(Config::get('site.work_qrcode'),true),
            'time' => Config::get('site.work_time'),
            'mobile' => Config::get('site.work_mobile')
        ];
        $this->success('客服信息',$data);
    }

    /**
     * @ApiTitle    (余额明细)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=page, type=integer, required=true, description="页数")
     * @ApiReturn   ({
    'code':'1',
    'msg':'余额明细'
    })
     */
    public function moneyList()
    {
        $page = $this->request->post('page',1);
        $model = new UserMoneyLog();
        $list = $model
            ->where('user_id',$this->auth->id)
            ->order('id','desc')
            ->paginate(10,false,['page'=>$page]);
        $this->success('余额明细',$list);
    }
}