审查视图

application/api/controller/Order.php 36.7 KB
李忠强 authored
1 2 3 4 5 6 7
<?php


namespace app\api\controller;


use addons\epay\library\Service;
李忠强 authored
8
use app\api\model\GoodsComment;
李忠强 authored
9
use app\api\model\GoodsSpec;
何书鹏 authored
10
use app\api\model\RiderOrder;
李忠强 authored
11 12 13 14 15
use app\api\model\SpecValue;
use app\api\model\Third;
use app\api\model\UserAddress;
use app\api\model\UserCoupon;
use app\common\controller\Api;
何书鹏 authored
16 17
use fast\Http;
use think\Config;
李忠强 authored
18 19
use think\Db;
use think\exception\PDOException;
李忠强 authored
20
use Yansongda\Pay\Pay;
李忠强 authored
21 22 23 24 25 26

/**
 * 订单
 */
class Order extends Api
{
27
    protected $noNeedLogin = ['friendPay','commentOrderDetail','pay','cancelOrderAction'];
李忠强 authored
28
    protected $noNeedRight = ['*'];
李忠强 authored
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

    /**
     * @ApiTitle    (订单列表)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="type", type="integer", required=true, description="类型1全部2待付款3待发货4待收货5待评价")
     * @ApiParams   (name="page", type="integer", required=true, description="页数")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':
        "total": 1, 总条数
        "per_page": 5, 每页数量
        "current_page": 1, 当前页
        "last_page": 1, 最后一页
        "data": [
            {
            "id": 1, 订单id
            "order_no": "adsadasdas", 订单编号
            "discount_price": "0.00", 优惠金额
            "pay_price": "0.00", 实付价格
            "pay_status": "10", 10未支付20已支付
            "freight_status": "10", 10未发货20已发货
            "receipt_status": "10", 10未收货20已收货
            "order_status": "10", 10进行中20已取消30已完成
何书鹏 authored
54
            "comment_status": "10", 评价状态:10=未评价20=已评价
李忠强 authored
55
            "total_sum": 0, 商品总数量
何书鹏 authored
56 57
            "goods": [{
                "goods_id": 1, 商品ID
李忠强 authored
58 59 60 61 62
                "goods_name": "asdasd", 商品名
                "goods_attr": "1", 规格名
                "total_num": 0, 数量
                "total_price": "0.00", 价格
                "image_text": "" 图片
何书鹏 authored
63
                "stock_num": 68, 商品总库存
何书鹏 authored
64
            }],
李忠强 authored
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
            "createtime_text": "" 时间
            }
        ]
    })
     */
    public function orderList()
    {
        $type = $this->request->post('type');
        $page = $this->request->post('page',1);
        if (!in_array($type,[1,2,3,4,5])) $this->error('type参数不合法');
        if (!is_numeric($page)) $this->error('页数不合法');
        switch ($type){
            case 1:
                $where = [
                    'fa_litestore_order.status' => 'normal',
                    'fa_litestore_order.user_id' => $this->auth->id,
                ];
                break;
            case 2:
                $where = [
                    'fa_litestore_order.status' => 'normal',
                    'fa_litestore_order.user_id' => $this->auth->id,
                    'fa_litestore_order.pay_status' => '10',
                ];
                break;
            case 3:
                $where = [
                    'fa_litestore_order.status' => 'normal',
                    'fa_litestore_order.user_id' => $this->auth->id,
何书鹏 authored
94
                    'fa_litestore_order.pay_status' => '20',
李忠强 authored
95 96 97 98 99 100 101
                    'fa_litestore_order.freight_status' => '10',
                ];
                break;
            case 4:
                $where = [
                    'fa_litestore_order.status' => 'normal',
                    'fa_litestore_order.user_id' => $this->auth->id,
何书鹏 authored
102 103
                    'fa_litestore_order.pay_status' => '20',
                    'fa_litestore_order.freight_status' => '20',
李忠强 authored
104 105 106 107 108 109 110
                    'fa_litestore_order.receipt_status' => '10',
                ];
                break;
            default :
                $where = [
                    'fa_litestore_order.status' => 'normal',
                    'fa_litestore_order.user_id' => $this->auth->id,
何书鹏 authored
111 112
                    'fa_litestore_order.pay_status' => '20',
                    'fa_litestore_order.freight_status' => '20',
李忠强 authored
113
                    'fa_litestore_order.receipt_status' => '20',
何书鹏 authored
114
                    'fa_litestore_order.comment_status' => '10',
李忠强 authored
115 116 117 118 119 120 121 122 123 124 125 126 127 128
                ];
                break;
        }

        $model = new \app\api\model\Order();
        $list = $model
            ->with(['goods'])
            ->where($where)
            ->order('id','desc')
            ->paginate(5,false,['page'=>$page])
            ->each(function ($item,$key){
                $sum = 0;
                foreach ($item->getRelation('goods')as $key => $value){
                    $sum += $value['total_num'];
何书鹏 authored
129 130 131
                    // 总库存
                    $value['stock_num'] = GoodsSpec::where('goods_id',$value['goods_id'])->sum('stock_num');
                    $value->visible(['goods_id','goods_name','goods_attr','total_num','total_price'])->append(['stock_num']);
李忠强 authored
132 133 134 135 136
                }
                $item['total_sum'] = $sum;
                $item->visible([
                    'goods','total_sum','order_no','id','pay_price',
                    'discount_price','pay_status','order_status','receipt_status',
何书鹏 authored
137
                    'freight_status','comment_status'
李忠强 authored
138 139 140 141 142 143 144
                ]);
            });
        $this->success('订单列表',$list);
    }

    /**
     * @ApiTitle    (下单页面)
145
     * @ApiSummary ([{id:113 goods_id:22 goods_sku_id:106 number:2} {id:114 goods_id:23 goods_sku_id:66 number:2}])
李忠强 authored
146 147 148
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="data_json", type="string", required=true, description="下单的商品json数据")
149
     * @ApiParams   (name="id", type="integer", required=false, description="购物车或我常买id 此值不传 json数组注释用")
李忠强 authored
150 151 152 153 154 155 156 157 158
     * @ApiParams   (name="goods_id", type="integer", required=false, description="商品id 此值不传 json数组注释用")
     * @ApiParams   (name="goods_sku_id", type="integer", required=false, description="规格id 此值不传 json数组注释用")
     * @ApiParams   (name="number", type="integer", required=false, description="购买数量 此值不传 json数组注释用")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':
        "list": [
            {
159
            "id": 113, 购物车或我常买id
李忠强 authored
160 161 162 163 164 165 166 167 168 169
            "goods_id": 22, 商品id
            "goods_name": "Mate 20 华为 HUAWEI ", 商品名称
            "spec_type": "20", 20多规格10单规格
            "sku_id": 106, 规格id
            "sku_price": "6099.00", 规格单价
            "sku_name": "极光色 8GB+128GB", 规格名称
            "number": 2, 数量
            "image_text": "", 图片
            },
            {
170
            "id": 114,
李忠强 authored
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
            "goods_id": 23,
            "goods_name": "MacBook Pro 13寸",
            "spec_type": "20",
            "sku_id": 66,
            "sku_price": "12688.00",
            "sku_name": "天空灰",
            "number": 2,
            "image_text": "",
            }
        ],
        "price": "37574.00" 总价
    })
     */
    public function orderCalculation()
    {
李忠强 authored
186
        $json = $this->request->param('data_json');
李忠强 authored
187
        if (!$json) $this->error('data_json参数不能为空');
李忠强 authored
188
        $json = str_replace('&quot;','"',$json);
李忠强 authored
189 190 191 192 193 194 195 196 197 198 199 200 201
//        $json = '[{"goods_id":22,"goods_sku_id":106,"number":2},{"goods_id":23,"goods_sku_id":66,"number":2}]';
        $data = json_decode($json,true);
        $goodsmodel = new \app\api\model\Goods();
        $skumodel = new GoodsSpec();
        $specmodel = new SpecValue();
        $goods_array = []; //商品列表
        $sum_price = 0; //总价格
        foreach ($data as $key => $value){
            if (!is_numeric($value['goods_id']) || !is_numeric($value['goods_sku_id']) || !is_numeric($value['number'])){
                $this->error('参数不合法');
            }
            $goods = $goodsmodel->where('goods_id',$value['goods_id'])->field('goods_id,goods_name,image,spec_type')->find();
            if (!$goods) $this->error('商品不存在');
SHW\戥岁。。 authored
202 203
//            $goods->visibleAppend(['image_text']);
            $goods->append(['image_text']);
李忠强 authored
204 205 206 207
            $goods->hidden(['image']);
            $sku = $skumodel->where('goods_spec_id',$value['goods_sku_id'])
                ->field('goods_spec_id,spec_sku_id,goods_price')->find();
            if (!$sku) $this->error('商品规格不存在');
SHW\戥岁。。 authored
208
//            $sku->unsetAppend();
李忠强 authored
209 210 211 212 213 214 215 216 217 218 219

            $goods['sku_id'] = $sku['goods_spec_id'];
            $goods['sku_price'] = $sku['goods_price'];
            if ($goods['spec_type'] == 10){
                $goods['sku_name'] =''; //规格名
            }else{
                $ids = explode('_',$sku['spec_sku_id']);
                $sku_name = $specmodel->whereIn('id',$ids)->column('spec_value');
                $goods['sku_name'] = implode(' ',$sku_name);  //规格名
            }
            $goods['number'] = $value['number'];
何书鹏 authored
220 221 222
            if(!empty($value['id'])){
                $goods['id'] = $value['id'];
            }
李忠强 authored
223 224 225
            $goods_array[] = $goods;
            $sum_price = bcadd($sum_price,bcmul($sku['goods_price'],$value['number'],2),2);
        }
李忠强 authored
226 227 228 229 230 231 232 233 234 235
        $addressmodel = new UserAddress();
        $address = $addressmodel->where('user_id',$this->auth->id)->where('normal_status','1')->find();
        $express_price = 0;
        if ($address){
            // 计算运费
            $lat1 = $address['lat'];
            $lng1 = $address['lng'];
            $admin_address = Db::name('admin_address')->find();
            $lat2 = $admin_address['lat'];
            $lng2 = $admin_address['lng'];
何书鹏 authored
236
            $express_price = $this->distancePrice($lat1,$lng1,$lat2,$lng2,$sum_price);
李忠强 authored
237 238 239 240 241
            if ($express_price === false)  $express_price = 0;
        }else{
            $address = [];
        }
        $sum_price += $express_price;
李忠强 authored
242
        $this->success('下单页详情',['list'=>$goods_array,'price'=>$sum_price,'order_price'=>$sum_price-$express_price,'express_price'=>$express_price,'address'=>$address]);
李忠强 authored
243 244 245
    }

    /**
李忠强 authored
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
     * @ApiTitle    (找人付页面)
     * @ApiMethod   (POST)
     * @ApiParams   (name="order_id", type="integer", required=true, description="订单id")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':
        detail:
            pay_price:实付款
            "goods": [
                {
                "goods_id": 22, 商品id
                "goods_name": "Mate 20 华为 HUAWEI ", 商品名称
                "spec_type": "20", 20多规格10单规格
                "sku_id": 106, 规格id
                "sku_price": "6099.00", 规格单价
                "sku_name": "极光色 8GB+128GB", 规格名称
                "number": 2, 数量
                "image_text": "", 图片
                },
                {
                "goods_id": 23,
                "goods_name": "MacBook Pro 13寸",
                "spec_type": "20",
                "sku_id": 66,
                "sku_price": "12688.00",
                "sku_name": "天空灰",
                "number": 2,
                "image_text": "",
                }
            ],
        "user": 用户信息
    })
     */
    public function friendPay()
    {
        $order_id = $this->request->post('order_id');
        if (!$order_id) $this->error('订单id参数不能为空');
        $ordermodel = new \app\api\model\Order();
        $order = $ordermodel
            ->with(['goods'])
何书鹏 authored
287
            ->where('id',$order_id)
李忠强 authored
288 289 290 291 292 293 294
            ->find();
        $user = \app\api\model\User::get($order['user_id']);
        $user->visible(['nickname']);
        $this->success('下单页详情',['detail'=>$order,'user'=>$user]);
    }

    /**
李忠强 authored
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
     * @ApiTitle    (判断库存)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="sku_id", type="integer", required=true, description="规格id")
     * @ApiParams   (name="number", type="integer", required=true, description="购买数量")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    'data': code 等于1表示未超出最大值
    })
     */
    public function checkStock()
    {
        $sku_id = $this->request->post('sku_id');
        $number = $this->request->post('number');
        if (!$number) $this->error('请选择购买数量');
        if (!$sku_id) $this->error('请选择规格');
        $model = new GoodsSpec();
        $sku = $model::get($sku_id);
        if (!$sku) $this->error('规格已失效,请重新选择');
315 316
        $cart_number = \app\api\model\Cart::where('sku_id',$sku_id)->sum('number');
        if ($sku['stock_num'] < $number+$cart_number) $this->error('已超出最大库存');
李忠强 authored
317 318 319 320
        $this->success('SUCCESS');
    }

    /**
李忠强 authored
321 322 323 324
     * @ApiTitle    (计算运费)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="address_id", type="integer", required=true, description="地址id")
何书鹏 authored
325
     * @ApiParams   (name="goods_total_price", type="string", required=true, description="商品总价")
李忠强 authored
326 327
     * @ApiReturn   ({
    'code':'1',
李忠强 authored
328
    'msg':'计算运费'
李忠强 authored
329
    'data':
何书鹏 authored
330 331
        "price": "37574.00", 总价
        "delivery_threshold": "20.00", 起送价
李忠强 authored
332 333 334 335 336
    })
     */
    public function freightCalculation()
    {
        $address_id = $this->request->post('address_id');
何书鹏 authored
337
        $goods_total_price = $this->request->post('goods_total_price');
李忠强 authored
338
        if (!$address_id) $this->error('请选择地址');
何书鹏 authored
339
        if (!$goods_total_price) $this->error('请计算商品总价');
李忠强 authored
340 341 342 343 344 345 346 347
        $model = new UserAddress();
        $address = $model::get($address_id);
        if (!$address) $this->error('地址不存在');
        $lat1 = $address['lat'];
        $lng1 = $address['lng'];
        $admin_address = Db::name('admin_address')->find();
        $lat2 = $admin_address['lat'];
        $lng2 = $admin_address['lng'];
何书鹏 authored
348
        $sum_price = $this->distancePrice($lat1,$lng1,$lat2,$lng2,$goods_total_price);
李忠强 authored
349
        if ($sum_price === false) $this->error('地址超出配送距离');
何书鹏 authored
350 351 352 353 354
        $delivery_threshold = Db::name('litestore_rider_rule')->value('delivery_threshold');
        $this->success('计算运费',[
            'price' => $sum_price,
            'delivery_threshold' => $delivery_threshold
        ]);
李忠强 authored
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    }

    /**
     * @ApiTitle    (选择优惠券)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="price", type="float", required=true, description="订单价格")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": [
        {
            "id": 1,
            "user_id": 1,
            "coupon_id": 1,
            "name": "手动阀手动阀",
            "price": "1.00", 优惠券金额
            "full_price": "10.00", 满减金额
            "createtime": 111122244,
            "endtime": 1641869388,
            "status": "0",
            "endtime_text": "2022年01月11日到期"
        }
    ]
    })
     */
    public function chooseCoupon()
    {
何书鹏 authored
383 384 385
        $model = new UserCoupon();

        // 更新已过期状态
何书鹏 authored
386
        $model->where('status','0')->where('user_id',$this->auth->id)->where('endtime','<',time())->update(['status'=>'2']);
何书鹏 authored
387
李忠强 authored
388 389
        $price = $this->request->post('price');
        if (!is_numeric($price)) $this->error('订单价格不合法');
何书鹏 authored
390
李忠强 authored
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
        $list = $model
            ->where('status','0')
            ->where('user_id',$this->auth->id)
            ->where('full_price','<',$price)
            ->select();
        $this->success('用户优惠券列表',$list);
    }

    /**
     * @ApiTitle    (下单)
     * @ApiMethod   (POST)
     * @ApiSummary ([{goods_id:22 goods_sku_id:106 number:2} {goods_id:23 goods_sku_id:66 number:2}])
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="data_json", type="string", required=true, description="下单的商品json数据")
     * @ApiParams   (name="goods_id", type="integer", required=false, description="商品id 此值不传 json数组注释用")
     * @ApiParams   (name="goods_sku_id", type="integer", required=false, description="规格id 此值不传 json数组注释用")
     * @ApiParams   (name="number", type="integer", required=false, description="购买数量 此值不传 json数组注释用")
     * @ApiParams   (name="coupon_id", type="integer", required=true, description="优惠券id 无优惠券传0")
     * @ApiParams   (name="address_id", type="integer", required=true, description="地址id")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':

    })
     */
    public function addOrder()
    {
李忠强 authored
419 420 421
        $json = $this->request->param('data_json');
        $coupon_id = $this->request->param('coupon_id');
        $address_id = $this->request->param('address_id');
李忠强 authored
422 423 424 425 426 427 428 429 430 431 432 433
        if (!$json) $this->error('data_json参数不能为空');
//        $json = '[{"goods_id":22,"goods_sku_id":106,"number":2},{"goods_id":23,"goods_sku_id":66,"number":2}]';
        $address = Db::name('user_address')
            ->where('id',$address_id)
            ->where('user_id',$this->auth->id)
            ->find();
        if (!$address) $this->error('地址不存在');
        $coupon = [];
        if ($coupon_id > 0){
            $coupon = Db::name('user_coupon')
                ->where('id',$coupon_id)
                ->where('user_id',$this->auth->id)
何书鹏 authored
434
                ->where('status','0')
李忠强 authored
435 436 437
                ->find();
            if (!$coupon) $this->error('优惠券不存在');
        }
李忠强 authored
438
        $json = str_replace('&quot;','"',$json);
李忠强 authored
439 440 441 442 443 444
        $data = json_decode($json,true);
        $goodsmodel = new \app\api\model\Goods();
        $skumodel = new GoodsSpec();
        $ordermodel = new \app\api\model\Order();
        $ordergoodsmodel = new \app\api\model\OrderGoods();
        $orderaddressmodel = new \app\api\model\OrderAddress();
李忠强 authored
445
        $cartmodel = new \app\api\model\Cart();
李忠强 authored
446 447 448 449 450 451 452 453 454 455 456 457 458
        $specmodel = new SpecValue();
        $goods_array = []; //商品列表
        $sum_price = 0; //总价格
        $user_id = $this->auth->id;

        foreach ($data as $key => $value){
            if (!is_numeric($value['goods_id']) || !is_numeric($value['goods_sku_id']) || !is_numeric($value['number'])){
                $this->error('参数不合法');
            }
            $goods = $goodsmodel->where('goods_id',$value['goods_id'])->find();
            if (!$goods) $this->error('商品不存在');
            $sku = $skumodel->where('goods_spec_id',$value['goods_sku_id'])->find();
            if (!$sku) $this->error('商品规格不存在');
李忠强 authored
459
            if ($sku['stock_num'] < $value['number']) $this->error('库存不足');
李忠强 authored
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
            if ($goods['spec_type'] == 10){
                $sku_name =''; //规格名
            }else{
                $ids = explode('_',$sku['spec_sku_id']);
                $sku_name = $specmodel->whereIn('id',$ids)->column('spec_value');
                $sku_name = implode(' ',$sku_name);  //规格名
            }

            // 组装订单商品数组
            $goods_array[] = [
                'goods_id' => $goods['goods_id'],
                'goods_name' => $goods['goods_name'],
                'image' => $goods['image'],
                'deduct_stock_type' => $goods['deduct_stock_type'],
                'spec_type' => $goods['spec_type'],
                'spec_sku_id' => $sku['spec_sku_id'],
                'goods_spec_id' => $sku['goods_spec_id'],
                'goods_attr' => $sku_name,
                'content' => $goods['content'],
                'goods_no' => $goods['number'],
                'goods_price' => $sku['goods_price'],
                'goods_weight' => $sku['goods_weight'],
                'total_num' => $value['number'],
                'total_price' => bcmul($sku['goods_price'],$value['number'],2),
                'user_id' => $user_id,
            ];

            $sum_price = bcadd($sum_price,bcmul($sku['goods_price'],$value['number'],2),2);
        }

        // 计算运费
        $lat1 = $address['lat'];
        $lng1 = $address['lng'];
        $admin_address = Db::name('admin_address')->find();
        $lat2 = $admin_address['lat'];
        $lng2 = $admin_address['lng'];
何书鹏 authored
496
        $distance_price = $this->distancePrice($lat1,$lng1,$lat2,$lng2,$sum_price);
李忠强 authored
497 498
        if ($distance_price === false) $this->error('地址超出配送距离');
何书鹏 authored
499
        if ($coupon !== [] && $coupon['full_price'] > $sum_price) $this->error('优惠券不可使用');
李忠强 authored
500
何书鹏 authored
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        // 给骑手佣金
        $rider_rule = Db::name('litestore_rider_rule')->find();
        if ($sum_price < $rider_rule['delivery_threshold']){
            $last_price = $rider_rule['delivery_threshold'] - $sum_price;
            $this->error('差'.$last_price.'元起送');
        }
        $distance = ceil(getDistance($lat1,$lng1,$lat2,$lng2));
        if ($distance > $rider_rule['first']){
            $first_rider_fee = $rider_rule['first_rider_fee'];
            $subdistance = $distance-$rider_rule['first'];
            $count = ceil(bcdiv($subdistance,$rider_rule['additional'],1));
            $second_rider_price = bcmul($count,$rider_rule['additional_rider_fee'],2);
            $rider_price = bcadd($first_rider_fee,$second_rider_price,2);
        }else{
            $rider_price = $rider_rule['first_rider_fee'];
        }
李忠强 authored
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        // 订单地址
        $order_address = [
            'name' => $address['username'],
            'phone' => $address['mobile'],
            'address' => $address['address'],
            'detail' => $address['address_detail'],
            'lng' => $address['lng'],
            'lat' => $address['lat'],
            'user_id' => $user_id,
        ];


        $sum_price += $distance_price; // 订单总价
        $order_no = 'LQ-'.time().mt_rand(1000,9999); // 订单号
        $couponprice = isset($coupon['price'])?$coupon['price']:0;  // 优惠价格
何书鹏 authored
533
李忠强 authored
534 535 536 537 538
        // 订单信息
        $order = [
            'order_no' => $order_no,
            'total_price' => $sum_price,  // 订单总价
            'discount_price' => $couponprice,  // 优惠价格
539
            'pay_price' => bcsub($sum_price,$couponprice,2),  // 支付总价
李忠强 authored
540
            'express_price' => $distance_price,  // 骑手费用
541
            'user_id' => $user_id,
何书鹏 authored
542 543
            'user_coupon_id' => $coupon_id > 0 ? $coupon_id : 0,
            'rider_price' => $rider_price
李忠强 authored
544 545 546 547 548 549 550 551
        ];

        // 添加订单
        try {
            Db::startTrans();
            $ordermodel->save($order);
            foreach ($goods_array as $key => &$value){
                $value['order_id'] = $ordermodel->id;
李忠强 authored
552 553 554 555
                // 减少库存
                if ($value['deduct_stock_type'] == 10){
                    $skumodel->where('goods_spec_id',$value['goods_spec_id'])->setDec('stock_num',$value['total_num']);
                }
李忠强 authored
556 557 558 559
            }
            $ordergoodsmodel->saveAll($goods_array);
            $order_address['order_id'] = $ordermodel->id;
            $orderaddressmodel->save($order_address);
李忠强 authored
560 561 562 563 564 565 566 567 568 569 570
            // 删除购物车
            $goodsids = [];
            $skuids = [];
            foreach ($goods_array as $key => $value){
                $goodsids[] = $value['goods_id'];
                $skuids[] = $value['goods_spec_id'];
            }
            $cartmodel->whereIn('goods_id',$goodsids)
                ->whereIn('sku_id',$skuids)
                ->where('user_id',$this->auth->id)
                ->delete();
571 572
            // 如果使用了优惠券,就把优惠券状态变为已使用
            UserCoupon::where('id',$coupon_id)->update(['status'=>'1']);
573
            // 待支付自动关闭
何书鹏 authored
574
            $close_minue = 2;
575
            \think\Queue::later(($close_minue * 60), '\app\api\job\OrderAutoOper@autoClose', ['order_id' => $ordermodel->id], 'temporaryfood');
李忠强 authored
576 577 578 579 580 581 582 583 584 585 586 587 588 589
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('下单成功',$ordermodel->id);
    }

    /**
     * @ApiTitle    (支付订单)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
何书鹏 authored
590
     * @ApiParams   (name="code", type="string", required=false, description="代付人code")
李忠强 authored
591 592 593 594 595 596 597 598
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function pay()
    {
        $order_id = $this->request->post('id');
何书鹏 authored
599
        $code = $this->request->post('code');
何书鹏 authored
600
        empty($order_id) && $this->error('缺少必需参数');
李忠强 authored
601 602 603 604

        $model = new \app\api\model\Order();
        $order = $model::get($order_id);
        if (!$order) $this->error('订单不存在');
何书鹏 authored
605
        $third = Third::alias('a')
何书鹏 authored
606
            ->join('user b','b.id = a.user_id')
何书鹏 authored
607
            ->where('a.user_id',$order['user_id'])
何书鹏 authored
608 609
            ->field('a.openid')
            ->find();
何书鹏 authored
610 611
        if (!$third) $this->error('下单人未注册');
何书鹏 authored
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
        // 获取代付人的openid
        $openid = $third['openid'];
        if(!empty($code)){
            $wxapi = Http::get('https://api.weixin.qq.com/sns/jscode2session',[
                'js_code' => $code,
                'grant_type' => 'authorization_code',
                'secret' => Config::get('site.secret'),
                'appid' => Config::get('site.appid')
            ]);//请求openid
            $wxapi = json_decode($wxapi,true);
            if (isset($wxapi['errcode'])){
                $this->error($wxapi['errmsg']);
            }
            $openid = $wxapi['openid'];
        }
李忠强 authored
628 629
        $params = [
            'type'         => 'wechat',
李忠强 authored
630
            'orderid'      => $order['order_no'],
李忠强 authored
631
            'title'        => '订单号-'.$order['order_no'],
何书鹏 authored
632 633
            'amount'       => $order['pay_price'],
//            'amount'       => 0.01,
李忠强 authored
634
            'method'       => 'miniapp',
何书鹏 authored
635
            'openid'       => $openid,
李忠强 authored
636 637 638 639 640 641 642
            'notifyurl'    => $this->request->domain().'/api/notify/orderNotify/type/wechat',
            'returnurl'    => '',
        ];
        $result = Service::submitOrder($params);
        $this->success('支付信息',$result);
    }
李忠强 authored
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

    /**
     * @ApiTitle    (确认收货)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function takeover()
    {
        $order_id = $this->request->post('id');
        if (!is_numeric($order_id)) $this->error('参数不合法');

        $model = new \app\api\model\Order();
何书鹏 authored
660 661 662 663 664 665 666 667 668 669
        $order = $model->get($order_id);
        empty($order) && $this->error('订单不存在');
        $order['receipt_status'] == '20' && $this->error('订单已收货,请勿重复提交');
        $rider_order = RiderOrder::where('order_id',$order_id)->find();
        empty($rider_order) && $this->error('骑手订单不存在');

        // 修改订单信息
        $order->rider_status = '20'; //送达状态:已送达
        $order->receipt_status = '20'; //收货状态:已收货
        $order->receipt_time = time(); //收货时间
何书鹏 authored
670
        $order->order_status = '30'; //订单状态变为已完成
何书鹏 authored
671 672 673 674 675 676
        $order->save();
        // 修改配送单信息
        $rider_order->status = '2'; //已送达
        $rider_order->sendtime = time(); //送达时间
        $rider_order->save();
        // 发放订单运费
何书鹏 authored
677
        \app\common\model\User::money($order->rider_price,$order->rider_user_id,'订单运费');
何书鹏 authored
678
李忠强 authored
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
        $this->success('收货成功');
    }


    /**
     * @ApiTitle    (提醒发货)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function remind()
    {
        $order_id = $this->request->post('id');
        if (!is_numeric($order_id)) $this->error('参数不合法');

        $model = new \app\api\model\Order();
何书鹏 authored
699
        $model->where('id',$order_id)->update(['remind_status'=>'20']);
李忠强 authored
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
        $this->success('提醒成功');
    }


    /**
     * @ApiTitle    (取消订单)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function cancelOrder()
    {
        $order_id = $this->request->post('id');
        if (!is_numeric($order_id)) $this->error('参数不合法');
        $model = new \app\api\model\Order();
李忠强 authored
719
        $order = $model->where('id',$order_id)->find();
720 721
        empty($order) && $this->error('订单不存在');
何书鹏 authored
722
        $res = self::cancelOrderAction($order);
723 724 725 726 727 728 729 730 731
        $res['code'] == 0 && $this->error($res['msg']);

        $this->success('取消成功');
    }

    /**
     * 取消订单操作
     * @ApiInternal
     */
何书鹏 authored
732
    public static function cancelOrderAction($order)
733
    {
何书鹏 authored
734
        \think\Log::write('订单数据:'.json_encode($order));
735 736 737
        if($order['freight_status'] == '20'){
            return ['code' => 0,'msg' => '订单已发货无法取消'];
        }
李忠强 authored
738 739
        $goodsmodel = new \app\api\model\OrderGoods();
        $skumodel = new \app\api\model\GoodsSpec();
740 741 742 743 744 745 746 747 748

        Db::startTrans();
        try {
            // 增加库存
            $list = $goodsmodel->where('order_id',$order['id'])->select();
            foreach ($list as $key => $value){
                if ($value['deduct_stock_type'] == 10){
                    $skumodel->where('goods_spec_id',$value['goods_spec_id'])->setInc('stock_num',$value['total_num']);
                }
李忠强 authored
749
            }
750 751 752 753 754

            // 已支付就退款
            if($order['pay_status'] == '20'){
                $config = Service::getConfig('wechat');
                $config['app_id'] = $config['miniapp_id'];
何书鹏 authored
755
                $config['notify_url'] = request()->domain().'api/notify/refund/type/wechat';
756 757 758 759
                $config['return_url'] = '';
                $wechat = Pay::wechat($config);
                $refund_no = 'LQ-'.time().mt_rand(10000,99999);
                $param = [
何书鹏 authored
760 761 762 763
                    'total_fee' => $order['pay_price'],
                    'refund_fee' => $order['pay_price'],
//                    'total_fee' => 1,
//                    'refund_fee' => 1,
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
                    'out_trade_no' => $order['order_no'],
                    'out_refund_no' => $refund_no
                ];
                $wechat->refund($param);
                $order->refund_no = $refund_no;
                $order->refund_time = time();
            }
            // 状态变为已取消
            $order->order_status = '20';
            $order->status = 'hidden';
            $order->isUpdate(true)->save();

            // 如果使用了优惠券,就把优惠券状态变为待使用或者已过期
            if($order['user_coupon_id'] > 0){
                $user_coupon = UserCoupon::get($order['user_coupon_id']);
                if($user_coupon){
                    $status = $user_coupon['endtime'] > time() ? '0' : '2';
                    $user_coupon->save(['status'=>$status]);
                }
            }
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
787
            return ['code' => 0,'msg' => $e->getMessage()];
何书鹏 authored
788
        }
789
        return ['code' => 1,'msg' => '取消成功'];
李忠强 authored
790 791 792
    }

    /**
李忠强 authored
793
     * @ApiTitle    (评价订单详情页)
李忠强 authored
794 795 796 797 798
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
李忠强 authored
799 800 801 802 803 804
    'data':
        order_id:订单id
        goods_name:商品名称
        goods_id:商品id
        goods_attr:规格描述
        image_text:商品图片
李忠强 authored
805 806
    })
     */
李忠强 authored
807
    public function commentOrderDetail()
李忠强 authored
808 809 810
    {
        $order_id = $this->request->post('id');
        if (!is_numeric($order_id)) $this->error('订单id参数不合法');
李忠强 authored
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840

        $model = new \app\api\model\OrderGoods();
        $list = $model
            ->where('order_id',$order_id)
            ->field('order_id,goods_name,goods_id,goods_attr,image')
            ->select();

        $this->success('商品列表',$list);
    }

    /**
     * @ApiTitle    (评价订单)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="data_json", type="string", required=true, description="评价数据 json对象")
     * @ApiParams   (name="order_id", type="integer", required=false, description="订单ID 不传")
     * @ApiParams   (name="score", type="integer", required=false, description="评价分数 不传")
     * @ApiParams   (name="comment", type="string", required=false, description="评价内容 不传")
     * @ApiParams   (name="goods_id", type="string", required=false, description="商品id 不传")
     * @ApiParams   (name="images", type="string", required=false, description="评价图片逗号隔开 不传")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function commentOrder()
    {
        $data = $this->request->post('data_json');
        if (!$data) $this->error('data_json参数缺失');
何书鹏 authored
841
        $data = json_decode(htmlspecialchars_decode($data),true);
李忠强 authored
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
        $params = [];
        $orderids = [];
        foreach ($data as $key => $value){
            if (!is_numeric($value['order_id'])) $this->error('订单id参数不合法');
            if (!is_numeric($value['goods_id'])) $this->error('商品id参数不合法');
            if (!is_numeric($value['score']) || $value['score']>5 || $value['score']<1) $this->error('评价分数不合法');
            if (!$value['comment']) $this->error('请填写评价内容');
            if ($value['images']){
                $arr = explode(',',$value['images']);
                if (count($arr) > 3) $this->error('请上传最多3张评价图片');
            }
            $params[] = [
                'user_id' => $this->auth->id,
                'order_id' => $value['order_id'],
                'goods_id' => $value['goods_id'],
                'comment' => $value['comment'],
                'images' => $value['images'],
                'score' => $value['score'],
            ];
            $orderids[] = $value['order_id'];
李忠强 authored
862 863
        }
李忠强 authored
864
        $ordermodel = new \app\api\model\Order();
何书鹏 authored
865
        $ordermodel->whereIn('id',$orderids)->update(['comment_status'=>'20','comment_time'=>time()]);
李忠强 authored
866 867 868
        $commentmodel = new GoodsComment();
        $commentmodel->isUpdate(false)->saveAll($params);
        $this->success('评价成功');
李忠强 authored
869 870
    }
李忠强 authored
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890

    /**
     * @ApiTitle    (删除订单)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="order_id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    })
     */
    public function delOrder()
    {
        $order_id = $this->request->post('order_id');
        if (!is_numeric($order_id)) $this->error('order_id参数不合法');
        $ordermodel = new \app\api\model\Order();
        $ordermodel->where('id',$order_id)->isUpdate()->save(['status'=>'hidden']);
        $this->success('SUCCESS');
    }
何书鹏 authored
891 892 893 894 895 896 897 898 899 900 901 902 903
    /**
     * @ApiTitle    (订单数量)
     * @ApiMethod   (GET)
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn({
        "code": 1,
        "msg": "订单数量",
        "time": "1609138878",
        "data": {
            "nopay": 2, //待支付(数量)
            "nosend": 3, //待发货(数量)
            "noget": 0, //待收货(数量)
            "nocomment": 0, //待评价(数量)
何书鹏 authored
904
            "coupon": 0, //待使用优惠券(数量)
何书鹏 authored
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
        }
    })
     */
    public function statusNum () {
        $model = new \app\api\model\Order();
        $nopay = $model->where([
                'status' => 'normal',
                'user_id' => $this->auth->id,
                'pay_status' => '10',
            ])->count();
        $nosend = $model->where([
            'status' => 'normal',
            'user_id' => $this->auth->id,
            'pay_status' => '20',
            'freight_status' => '10',
        ])->count();
        $noget = $model->where([
            'status' => 'normal',
            'user_id' => $this->auth->id,
            'pay_status' => '20',
            'freight_status' => '20',
            'receipt_status' => '10',
        ])->count();
        $nocomment = $model->where([
            'status' => 'normal',
            'user_id' => $this->auth->id,
            'pay_status' => '20',
            'freight_status' => '20',
            'receipt_status' => '20',
何书鹏 authored
934
            'comment_status' => '10'
何书鹏 authored
935
        ])->count();
何书鹏 authored
936 937 938 939 940
        $coupon = UserCoupon::where([
            'user_id' => $this->auth->id,
            'status' => '0'
        ])->count();
        $this->success('订单数量', compact('nopay','nosend','noget','nocomment','coupon'));
何书鹏 authored
941
    }
李忠强 authored
942
}