Order.php 13.2 KB
<?php
/**
 * Created by PhpStorm.
 * User: 86132
 * Date: 2020/7/16
 * Time: 9:42
 */

namespace app\api\controller;

use think\Db;
use app\common\controller\Api;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * @ApiTitle    (订单接口-选择收货地址)
     * @ApiSummary  (选择收货地址)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Order/SelectShippingAddress)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="shop_id", type="string", required=true, description="购物车ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1', code:9999911[请先添加地址],code:9999910[请先设置默认地址]
    'msg':'返回成功'
    "data": [
    {
    "address_id": "地址ID",
    "name": "收货人姓名",
    "address": "地址",
    "address_con": "详细地址",
    "mobile": "手机号",
    "type": 是否默认地址[1=是,0=否]
    }
    ]
    })
     */
    public function SelectShippingAddress()
    {
        $user_id = $this->is_token($this->request->header());
        //判断是否有设置地址
        $IsAddress = Db::name('address')->where(['user_id' => $user_id])->find();
        if (empty($IsAddress)) {
            $this->success('请先添加地址', 1, 9999911);
        }
        //判断是否有默认地址
        $DefaultAddress = Db::name('address')->where(['user_id' => $user_id])->where(['status' => 1])->find();
        if (empty($DefaultAddress)) {
            $this->success('请先设置默认地址', 1, 9999910);
        }
        $address_arr = Db::name('address')->where(['user_id' => $user_id])->select();
        foreach ($address_arr as $k => $v) {
            $return[$k]['name'] = $v['name'];
            $return[$k]['address_id'] = $v['id'];
            $return[$k]['address'] = $v['address'];
            $return[$k]['address_con'] = $v['address_con'];
            $return[$k]['mobile'] = $v['mobile'];
            $return[$k]['type'] = $v['status'];
        }
        $this->success('成功', $return);
    }


    /**
     * @ApiTitle    (订单接口-订单计算)
     * @ApiSummary  (订单计算)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Order/OrderPriceCalculation)
     * @ApiParams   (name="data", type="json", required=true, description="product_id:商品ID,buy_num:商品数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    " "data": {
    "count_price": 订单总价,
    "count_number": 件数,
    "list": [
    {
    "avatar": "http://qco519e0n.bkt.clouddn.com/uploads/20200703/Fpi3RGA38eqT3eDk_sh99hOZ7wAA.png",
    "name": "12kf(123)+10.50v",
    "class_con": "详细分类4",
    "logo": "品牌1",
    "price": 商品金额,
    "gradient": [
    {
    "tidu": "100",
    "price": "0.10"
    }
    ]
    }
    ]
    }
    })
     */
    public function OrderPriceCalculation()
    {
        $data = input('data');
        $arr = json_decode(htmlspecialchars_decode($data), true);
        foreach ($arr as $k => $v) {
            $list[$k] = $this->GenerateOrderPriceCalculation($v['product_id'], $v['buy_num']);
        }
        foreach ($list as $value) {
            foreach ($value as $v) {
                $listitem[] = $v;
            }
        }
        $count_price = array_sum(array_column($listitem, 'price'));
        foreach ($arr as $k => $v) {
            foreach ($listitem as $k1 => $v1) {
                $listitem[$k]['buy_num'] = $v['buy_num'];
            }
        }
        $return['count_price'] = round($count_price, 2);
        $return['count_number'] = count($arr);
        $return['list'] = $listitem;
        $this->success('', $return);
    }


    /**
     * @ApiTitle    (订单接口-提交订单)
     * @ApiSummary  (提交订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Order/PlaceOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="data", type="json", required=true, description="product_id:商品ID,buy_num:商品数量")
     * @ApiParams   (name="address_id", type="int", required=true, description="地址ID")
     * @ApiParams   (name="total", type="int", required=true, description="订单总价")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": {
    }
    })
     */
    public function PlaceOrder()
    {
        $user_id = $this->is_token($this->request->header());
        $param = $this->request->param();
        $arr = json_decode(htmlspecialchars_decode($param['data']), true);
        foreach ($arr as $k => $v) {
            $stock[$k] = Db::name('product')->where(['id' => $v['product_id']])->value('stock');
            $num[$k] = $stock[$k] - $v['buy_num'];
            $res[$k] = Db::name('product')->where(['id' => $v['product_id']])->update(['stock' => $num[$k]]);
        }
        //生成订单号
        $order_sn = $this->order_sn();
        //查询地址
        $address = Db::name('address')->where(['id' => $param['address_id']])->find();
        $order_data = [
            'total' => $param['total'],
            'user_id' => $user_id,
            'order_sn' => $order_sn,
            'order_status' => 0,
            'invoice_status' => 0,
            'address' => $address['address'],
            'address_con' => $address['address_con'],
            'mobile' => $address['mobile'],
            'name' => $address['name'],
            'createtime' => time(),
            'updatetime' => time()
        ];
        $insert_order = Db::name('order')->insert($order_data);
        if (!$insert_order) {
            $this->error('订单生成失败', 0);
        }
        foreach ($arr as $k => $v) {
            $insert_orderCon[$k] = Db::name('order_con')->insert(['product_id' => $v['product_id'], 'buy_num' => $v['buy_num'], 'order_sn' => $order_sn, 'createtime' => time(), 'updatetime' => time()]);
        }
        if (!$insert_orderCon) {
            $this->error('订单详情生成失败', 0);
        }
        $this->success('成功', 1);
    }


    /**
     * @ApiTitle    (订单接口-删除购物车)
     * @ApiSummary  (删除购物车)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Order/DeleteShopCar)
     * @ApiParams   (name="shop_id", type="int", required=true, description="购物车ID多个用,分割[直接购买:传null,或不传]")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": {
    }
    })
     */
    public function DeleteShopCar()
    {
        $param = $this->request->param();
        $this->DeleteCar($param['shop_id']);
        $this->success('成功', 1);
    }


    /**
     * @ApiTitle    (订单接口-我的订单)
     * @ApiSummary  (我的订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Order/MyOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="type", type="int", required=true, description="订单状态:[null=全部订单,0=待审核,1=待收货,2=已完成]")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1', code:9999911[请先添加地址],code:9999910[请先设置默认地址]
    'msg':'返回成功'
    "data": {
    "ToBeReviewed": 待审核,
    "GoodsToBeReceived": 待收货,
    "Completed": 已完成,
    "itemList": [
    {
    "total": "总价",
    "order_sn": "订单号",
    "username": "下单人",
    "order_status": 订单状态:0=待审核,1=待收货,2=已完成,
    "invoice_status": 发票状态:0=没有开票资格,1=待开票,2=开票中,3=已开票,
    "shopping": nul[快递单号:没有为NULL],
    "shop_order": null[快递公司:没有为NULL],
    "buy_num": 数量,
    "list": [
    {
    "avatar": "商品头图",
    "name": "12kf(123)+10.50v",
    "class_con": "详细分类3",
    "logo": "品牌1",
    "price": 单价,
    "gradient": [
    {
    "tidu": "100",
    "price": "0.10"
    }
    ]
    }
    ]
    }
    ]
    }
    })
     */
    public function MyOrder()
    {
        $user_id = $this->is_token($this->request->header());
        $type = input('type');
        $ToBeReviewed_arr = Db::name('order')->where(['user_id' => $user_id])->where(['order_status' => 0])->select();
        $GoodsToBeReceived_arr = Db::name('order')->where(['user_id' => $user_id])->where(['order_status' => 1])->select();
        $Completed_arr = Db::name('order')->where(['user_id' => $user_id])->where(['order_status' => 2])->select();
        $return['ToBeReviewed'] = count($ToBeReviewed_arr);
        $return['GoodsToBeReceived'] = count($GoodsToBeReceived_arr);
        $return['Completed'] = count($Completed_arr);
        $map = [];
        $map2 = [];
        if (!empty($type) || $type != null || $type != '') {
            $map['o.order_status'] = array('eq', $type);
            $map2['order_status'] = array('eq', $type);
        }
        $list = Db::name('order')
            ->alias('o')
            ->where(['user_id' => $user_id])
            ->where($map)
            ->join('user u', 'u.id=o.user_id')
            ->field('o.total,o.order_sn,u.username,o.order_status,invoice_status')
            ->select();
//        $id_arr = Db::name('order')->where(['user_id' => $user_id])->select();
//        foreach ($id_arr as $k => $v) {
//            foreach ($list as $k1 => $v1) {
//                $list[$k]['oid'] = $v['id'];
//            }
//        }
        $shopping = Db::name('order')->where(['user_id' => $user_id])->where($map2)->select();
        foreach ($shopping as $k => $v) {
            if ($v['shopping'] == NULL) {
                foreach ($list as $k1 => $v1) {
                    $list[$k]['shopping'] = null;
                    $list[$k]['shop_order'] = null;
                    $list[$k]['kuaidi'] = null;
                }
            } else {
                foreach ($list as $k1 => $v1) {
                    $code = Db::name('kuaidicode')->where(['kuaidi' => $v['shopping']])->value('code');
                    $logisticResult[$k] = $this->getOrderTracesByJson($code, $v['shop_order']);
                    $kuaidi[$k] = json_decode(htmlspecialchars_decode($logisticResult[$k]), true);
                    $shopname[$k] = Db::name('kuaidicode')->where(['code' => $kuaidi[$k]['ShipperCode']])->value('kuaidi');
                    $shop_kuaidi[$k]['LogisticCode'] = $kuaidi[$k]['LogisticCode'];
                    $shop_kuaidi[$k]['ShipperCode'] = $shopname[$k];
                    $shop_kuaidi[$k]['Traces'] = $kuaidi[$k]['Traces'];
                    $list[$k]['kuaidi'] = $shop_kuaidi[$k];
                    $list[$k]['shopping'] = $v['shopping'];
                    $list[$k]['shop_order'] = $v['shop_order'];
                }
            }
        }
        foreach ($shopping as $k => $v) {
            $order_con_arr[0] = Db::name('order_con')->where(['order_sn' => $v['order_sn']])->select();
            $order_con = $this->three_arr($order_con_arr);
            foreach ($order_con as $k1 => $v1) {
                $product_arr[$k1] = $this->GenerateOrderPriceCalculation($v1['product_id'], $v1['buy_num']);
                $buy_num[$k1] = $v1['buy_num'];
            }
            $product_list = $this->three_arr($product_arr);
            $list[$k]['buy_num'] = array_sum($buy_num);
            $list[$k]['list'] = $product_list;
        }
        $return['itemList'] = $list;
        $this->success('成功', $return);
    }


    /**
     * @ApiTitle    (订单接口-取消订单)
     * @ApiSummary  (我的订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Order/CancellationOfOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="order_sn", type="string", required=true, description="订单号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": {
    }
    })
     */
    public function CancellationOfOrder()
    {
        $user_id = $this->is_token($this->request->header());
        $order_sn = input('order_sn');
        $res = Db::name('order')->where(['order_sn' => $order_sn])->where(['user_id' => $user_id])->delete();
        Db::name('order_con')->where(['order_sn' => $order_sn])->delete();
        if ($res) {
            $this->success('成功', 1);
        } else {
            $this->error('失败', 0);
        }
    }
}