<?php

namespace app\api\controller;

use addons\kdniao\library\Kdniao;
use app\api\model\AreaExtend;
use app\api\model\OrderDetail;
use app\api\model\OrderRefund;
use app\api\model\UserScoreLog;
use app\common\controller\Api;
use think\Db;
use think\Validate;
use wxapp\pay\WeixinPay;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $orderModel;
    protected $carModel;
    protected $areaExtendModel;
    protected $integralGoodsModel;
    protected $goodsModel;
    protected $ticketCodeModel;
    protected $userTicketModel;
    protected $orderAddressModel;
    protected $orderAddressInvoiceModel;
    protected $orderInfoModel;
    protected $orderDetailModel;
    protected $userModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->orderModel = new \app\api\model\Order();
        $this->carModel = new \app\api\model\Car();
        $this->areaExtendModel = new \app\api\model\AreaExtend();
        $this->integralGoodsModel = new \app\api\model\IntegralGoods();
        $this->goodsModel = new \app\api\model\Goods();
        $this->ticketCodeModel = new \app\api\model\Ticketcode();
        $this->userTicketModel = new \app\api\model\UserTicket();
        $this->orderAddressModel = new \app\api\model\OrderAddress();
        $this->orderAddressInvoiceModel = new \app\api\model\OrderAddressInvoice();
        $this->orderInfoModel = new \app\api\model\OrderInfo();
        $this->orderDetailModel = new \app\api\model\OrderDetail();
        $this->userModel = new \app\api\model\User();
    }

    /**
     * @ApiTitle    (确认订单(购物车))
     * @ApiSummary  (确认订单(购物车))
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true description="请求的Token")
     * @ApiParams  (name=car_id, type=string, required=true, description="购物车id 例 1,2,3")
     * @ApiParams  (name=ticket_user_id, type=string, required=false, description="用户优惠券id")
     * @ApiParams  (name=ticket_code, type=string, required=false, description="优惠码")
     * @ApiParams  (name=province_id, type=string, required=false, description="省id /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=city_id, type=string, required=false, description="市 /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=county_id, type=string, required=false, description="县 /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=postage_type, type=string, required=false, description="配送类型:1=闪送,2=普通配送  /api/user_address/getUserAddressDefault 接口获取")
     * @ApiRoute    (/api/order/order)
     * @ApiReturn({
    "code": 1,
    "msg": "success",
    "time": "1587691008",
    "data": {
    "price": 263.7, 总价
    "discount_price": 12.3, 折扣价
    "original_price": 246,  原价
    "ticketcode_discount_price": 5,  优惠码优惠价
    "ticket_discount_price": 10,   优惠券优惠价
    "integral": 0,  积分
    "postage": "30.00"  运费
    }
    },
    })
     */
    public function order()
    {
        $carModel = new \app\api\model\Car();
        $goodsModel = new \app\api\model\Goods();
        $ticketCodeModel = new \app\api\model\Ticketcode();
        $userTicketModel = new \app\api\model\UserTicket();
        $userId = $this->getUserId();
        $carId = $this->request->param('car_id');
        $ticketId = $this->request->param('ticket_user_id');
        $ticketCode = $this->request->param('ticket_code');
        $provinceId = $this->request->param('province_id',1);  //默认地址为北京
        $cityId = $this->request->param('city_id',2);  //默认地址为北京
        $countyId = $this->request->param('county_id',3);  //默认地址为北京
        $postageType = $this->request->param('postage_type',2); //默认普通配送
        if (empty($carId)) $this->error('缺少参数 car_id!');
        //判断优惠券和优惠码不能同时使用
        if (!empty($ticketCode) && !empty($ticketId)) $this->error('优惠券与优惠码不能同时使用!');
        //获取普通商品id
        $goodsIds = $carModel->where(['id' => ['in', $carId], 'type' => 1])->column('goods_id');
        //获取积分商品id
        $goodsIntegralIds = $carModel->where(['id' => ['in', $carId], 'type' => 2])->column('goods_id');
        //获取普通商品状态
        if ($goodsIds) {
            $goodsList = $goodsModel->selectGoodsStatus(['id' => ['in', $goodsIds]]);

            //判断商品是否有库存和状态
            foreach ($goodsList as $k => $v) {
                if ($v['status'] == 2) $this->error($v['ch_name'] . '商品已下架');
                if ($v['stock_num'] == 0) $this->error($v['ch_name'] . '商品库存不足');
                //判断用户收货区域是否有库存
                $areaStock = $goodsModel->getAreaStockNum(['g.id' => $v['id'], 'd.area_id' => $provinceId]);
                if (!empty($areaStock) && $areaStock['stock_num'] == 0) $data['is_lack_stock'] = 1;
            }
        }

        //获取积分商品状态
        if ($goodsIntegralIds) {
            $goodsIntegralList = $this->integralGoodsModel->selectGoodsStatus(['id' => ['in', $goodsIntegralIds]]);

            //判断商品是否有库存和状态
            foreach ($goodsIntegralList as $k => $v) {
                if ($v['status'] == 2) $this->error($v['ch_name'] . '商品已下架');
                if ($v['stock_num'] == 0) $this->error($v['ch_name'] . '商品库存不足');
                //判断用户收货区域是否有库存
                $areaStock = $this->integralGoodsModel->getAreaStockNum(['g.id' => $v['id'], 'd.area_id' => $provinceId]);
                if (!empty($areaStock) && $areaStock['stock_num'] == 0) $data['is_lack_stock'] = 1;
            }
        }
        //判断优惠码是否可用
        if (!empty($ticketCode)) {
            $ticketCodeInfo = $ticketCodeModel->where('code', $ticketCode)->find();
            if (!$ticketCodeInfo) $this->error('优惠码不存在!');
            if ($ticketCodeInfo['validtime'] < time()) $this->error('优惠码已过期!');
            if ($ticketCodeInfo['user_id']) $this->error('优惠码已使用!');
        }

        //判断优惠券是否可用
        if (!empty($ticketId)) {
            $ticketInfo = $userTicketModel->where(['user_id' => $userId, 'id' => $ticketId, 'status' => 1])->find();
            if (!$ticketInfo) $this->error('优惠码不存在!');
        }

        //获取原价,现价,折扣
        $priceArr = $this->carModel->getCarMoney(['id' => ['in', $carId]]);
        $data['price'] = 0; //折扣后价格
        $data['discount_price'] = 0; //折扣金额
        $data['original_price'] = 0; //原价
        $data['integral'] = 0; //积分
        foreach ($priceArr as $k => $v) {
            $priceArr[$k]['user_type'] = $this->user['type'];
            $data['price'] += round(get_price($v), 2);
            $data['discount_price'] += round(get_discount_price($v), 2);
            $data['original_price'] += $v['goods_price'];
            if (!empty($v['integral'])) $data['integral'] += $v['integral'];

        }
        //判断积分
        if ($data['integral'] > $this->user['score']) $this->error('积分不足');
        //获取运费
        $is_special = $this->areaExtendModel->where(['province_id' => $provinceId])->value('is_special');
        //特殊地区满200免运费
        if ($is_special == 1 && $data['price'] >= 200) {
            $postage = 0;
            //其他地区满300免运费,闪送无免运费
        } elseif ($data['price'] >= 300 && $postageType != 2) {
            $postage = 0;
        } else {
            //都不满足获取对应的运费
            $postageWhere = ['province_id' => $provinceId, 'city_id' => $cityId, 'county_id' => $countyId];
            if ($postageType == 1) {
                //配送为闪送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage2');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $provinceId])->value('postage2');
                }
            } else {
                //配送为普通配送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage1');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $provinceId])->value('postage1');
                }
            }
        }
        $data['postage'] = $postage;
        $data['price'] += $postage;

        //使用优惠码
        if (!empty($ticketCodeInfo)) {
            $data['price'] = $data['price'] - $ticketCodeInfo['price'];
            $data['ticketcode_discount_price'] = $ticketCodeInfo['price'];
        }

        //使用优惠券
        if (!empty($ticketInfo)) {
            $data['price'] = $data['price'] - $ticketInfo['price'];
            $data['ticket_discount_price'] = $ticketInfo['price'];
        }

        $this->success('success', $data);

    }


    /**
     * @ApiTitle    (创建订单(购物车))
     * @ApiSummary  (创建订单(购物车))
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true description="请求的Token")
     * @ApiParams  (name=car_id, type=string, required=true, description="购物车id 例 1,2,3")
     * @ApiParams  (name=pay_type, type=string, required=false, description="支付类型:1=微信支付,2=余额支付")
     * @ApiParams  (name=ticket_user_id, type=string, required=false, description="用户优惠券id")
     * @ApiParams  (name=ticket_code, type=string, required=false, description="优惠码")
     * @ApiParams  (name=province_id, type=string, required=true, description="商品收货地址省id")
     * @ApiParams  (name=city_id, type=string, required=true, description="商品收货地址市id")
     * @ApiParams  (name=county_id, type=string, required=true, description="商品收货地址县id")
     * @ApiParams  (name=address, type=string, required=true, description="商品收货地址")
     * @ApiParams  (name=name, type=string, required=true, description="商品收货人")
     * @ApiParams  (name=mobile, type=string, required=true, description="商品收货电话")
     * @ApiParams  (name=present_id, type=string, required=false, description="赠品id")
     * @ApiParams  (name=postage_type, type=string, required=true, description="配送类型:1=闪送,2=普通配送")
     * @ApiParams  (name=postage_date, type=string, required=false, description="配送日期")
     * @ApiParams  (name=postage_time, type=string, required=false, description="配送时间")
     * @ApiParams  (name=invoice_status, type=string, required=true, description="发票状态:1=个人或事业单位,2=企业,3=不需要开发票")
     * @ApiParams  (name=invoice_type, type=string, required=false, description="发票类型:1=纸质发票,2=电子发票")
     * @ApiParams  (name=invoice_email, type=string, required=false, description="电子发票邮箱")
     * @ApiParams  (name=taitou, type=string, required=false, description="发票抬头")
     * @ApiParams  (name=duty_num, type=string, required=false, description="发票税号")
     * @ApiParams  (name=invoice_province_id, type=string, required=false, description="发票收货地址省id")
     * @ApiParams  (name=invoice_city_id, type=string, required=false, description="发票收货地址市id")
     * @ApiParams  (name=invoice_county_id, type=string, required=false, description="发票收货地址县id")
     * @ApiParams  (name=invoice_address, type=string, required=false, description="发票收货地址")
     * @ApiParams  (name=invoice_name, type=string, required=false, description="发票收货人")
     * @ApiParams  (name=invoice_mobile, type=string, required=false, description="发票收货电话")
     * @ApiParams  (name=order_note, type=string, required=false, description="订单备注")
     * @ApiRoute    (/api/order/createOrder)
     * @ApiReturn({

    },
    })
     */
    public function createOrder()
    {
        $userId = $this->getUserId();
        $param = $this->request->param();
        $param['user_id'] = $userId;
        $validate = new Validate([
            'car_id' => 'require',
            'pay_type' => 'require',
            'name' => 'require',
            'mobile' => 'require',
            'address' => 'require',
            'province_id' => 'require',
            'city_id' => 'require',
            'county_id' => 'require',
            'postage_type' => 'require',
            'invoice_status' => 'require',

        ]);

        $validate->message([
            'car_id' => '缺少参数 car_id!',
            'pay_type' => '缺少参数 pay_type!',
            'name' => '缺少参数 name!',
            'mobile' => '缺少参数 mobile!',
            'address' => '缺少参数 address!',
            'province_id' => '缺少参数 province_id!',
            'city_id' => '缺少参数 city_id!',
            'county_id' => '缺少参数 county_id!',
            'postage_type' => '缺少参数 postage_type!',
            'invoice_status' => '缺少参数 invoice_status!',
        ]);

        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        if (($param['pay_type'] == 2 && $this->user['type'] == 3) || ($param['pay_type'] == 2 && $this->user['type'] == 4)) $this->error('员工或代理不能使用余额支付!');
        //判断优惠券和优惠码不能同时使用
        if (!empty($param['ticket_code']) && !empty($param['ticket_user_id'])) $this->error('优惠券与优惠码不能同时使用!');
        //获取普通商品id
        $goodsIds = $this->carModel->where(['id' => ['in', $param['car_id']], 'type' => 1])->column('goods_id');
        //获取积分商品id
        $goodsIntegralIds = $this->carModel->where(['id' => ['in', $param['car_id']], 'type' => 2])->column('goods_id');
        //获取普通商品状态
        if ($goodsIds) {
            $goodsList = $this->goodsModel->selectGoodsStatus(['id' => ['in', $goodsIds]]);
            //判断商品是否有库存和状态
            foreach ($goodsList as $k => $v) {
                if ($v['status'] == 2) $this->error($v['ch_name'] . '商品已下架');
                if ($v['stock_num'] == 0) $this->error($v['ch_name'] . '商品库存不足');
            }
        }
        //获取积分商品状态
        if ($goodsIntegralIds) {
            $goodsIntegralList = $this->integralGoodsModel->selectGoodsStatus(['id' => ['in', $goodsIntegralIds]]);

            //判断商品是否有库存和状态
            foreach ($goodsIntegralList as $k => $v) {
                if ($v['status'] == 2) $this->error($v['ch_name'] . '商品已下架');
                if ($v['stock_num'] == 0) $this->error($v['ch_name'] . '商品库存不足');
            }
        }
        //判断优惠码是否可用
        if (!empty($param['ticket_code'])) {
            $ticketCodeInfo = $this->ticketCodeModel->where('code', $param['ticket_code'])->find();
            if (!$ticketCodeInfo) $this->error('优惠码不存在!');
            if ($ticketCodeInfo['validtime'] < time()) $this->error('优惠码已过期!');
            if ($ticketCodeInfo['user_id']) $this->error('优惠码已使用!');
        }

        //判断优惠券是否可用
        if (!empty($param['ticket_user_id'])) {
            $ticketInfo = $this->userTicketModel->where(['user_id' => $userId, 'id' => $param['ticket_user_id'], 'status' => 1])->find();
            if (!$ticketInfo) $this->error('优惠码不存在!');
        }

        //获取原价,现价,折扣
        $priceArr = $this->carModel->getCarMoney(['id' => ['in', $param['car_id']]]);
        $data['price'] = 0; //折扣后价格
        $data['discount_price'] = 0; //折扣金额
        $data['original_price'] = 0; //原价
        $data['integral'] = 0; //积分
        foreach ($priceArr as $k => $v) {
            $priceArr[$k]['user_type'] = $this->user['type'];
            $data['price'] += round(get_price($v), 2);
            $data['discount_price'] += round(get_discount_price($v), 2);
            $data['original_price'] += $v['goods_price'];
            if (!empty($v['integral'])) $data['integral'] += $v['integral'];

        }
        //判断积分
        if ($data['integral'] > $this->user['score']) $this->error('积分不足');
        //获取运费
        $is_special = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('is_special');
        //特殊地区满200免运费
        if ($is_special == 1 && $data['price'] >= 200) {
            $postage = 0;
            //其他地区满300免运费,闪送无免运费
        } elseif ($data['price'] >= 300 && $param['postage_type'] != 2) {
            $postage = 0;
        } else {
            //都不满足获取对应的运费
            $postageWhere = ['province_id' => $param['province_id'], 'city_id' => $param['city_id'], 'county_id' => $param['county_id']];
            if ($param['postage_type'] == 1) {
                //配送为闪送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage2');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('postage2');
                }
            } else {
                //配送为普通配送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage1');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('postage1');
                }
            }
        }
        $data['postage'] = $postage;
        $data['price'] += $postage;


        Db::startTrans();
        try {
            //使用优惠码
            if (!empty($ticketCodeInfo)) {
                $data['price'] = $data['price'] - $ticketCodeInfo['price'];
                $data['ticketcode_discount_price'] = $ticketCodeInfo['price'];
                $data['ticketcode_id'] = $ticketCodeInfo['id'];
                $this->ticketCodeModel->where('id', $ticketCodeInfo['id'])->update(['user_id' => $userId]);
            }

            //使用优惠券
            if (!empty($ticketInfo)) {
                $data['price'] = $data['price'] - $ticketInfo['price'];
                $data['ticket_discount_price'] = $ticketInfo['price'];
                $data['user_ticket_id'] = $ticketInfo['id'];
                $this->userTicketModel->where('id', $ticketInfo['id'])->update(['status' => 2]);

            }

            //order表数据
            $orderData = [
                'order_num' => get_order_num(),
                'user_id' => $userId,
                'pay_type' => $param['pay_type'],
                'goods_total' => $data['original_price'],
                'pay_total' => $data['price'],
                'discount_price' => $data['discount_price'],
                'score' => $data['integral'],
                'present_id' => !empty($param['present_id']) ? $param['present_id'] : '',
                'postage_total' => $postage,
                'postage_type' => $param['postage_type'],
                'postage_date' => !empty($data['postage_date']) ? $data['postage_date'] : '',
                'postage_time' => !empty($data['postage_time']) ? $data['postage_time'] : '',
                'user_ticket_id' => !empty($data['user_ticket_id']) ? $data['user_ticket_id'] : '',
                'ticket_price' => !empty($data['ticket_discount_price']) ? $data['ticket_discount_price'] : '',
                'ticketcode_id' => !empty($data['ticketcode_id']) ? $data['ticketcode_id'] : '',
                'ticketcode_price' => !empty($data['ticketcode_discount_price']) ? $data['ticketcode_discount_price'] : '',
                'invoice_status' => $param['invoice_status'],
                'invoice_type' => !empty($param['invoice_type']) ? $param['invoice_type'] : '',
                'invoice_email' => !empty($param['invoice_email']) ? $param['invoice_email'] : '',
                'taitou' => !empty($param['taitou']) ? $param['taitou'] : '',
                'duty_num' => !empty($param['duty_num']) ? $param['duty_num'] : '',
                'order_note' => !empty($param['order_note']) ? $param['order_note'] : '',
                'type' => 1,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $res1 = $this->orderModel->insertGetId($orderData);

            //收货地址数据
            $orderAddress = [
                'order_id' => $res1,
                'name' => $param['name'],
                'mobile' => $param['mobile'],
                'address' => $param['address'],
                'province_id' => $param['province_id'],
                'city_id' => $param['city_id'],
                'county_id' => $param['county_id'],
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $res2 = $this->orderAddressModel->insertData($orderAddress);
            if ($param['invoice_status'] != 3) {
                //收货地址数据
                $orderAddressInvoice = [
                    'order_id' => $res1,
                    'name' => $param['invoice_name'],
                    'mobile' => $param['invoice_mobile'],
                    'address' => $param['invoice_address'],
                    'province_id' => $param['invoice_province_id'],
                    'city_id' => $param['invoice_city_id'],
                    'county_id' => $param['invoice_county_id'],
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                $res3 = $this->orderAddressInvoiceModel->insertData($orderAddressInvoice);
            }

            //获取商品详情列表
            $list = $this->carModel->getCarMoney(['id' => ['in', $param['car_id']]]);
            $orderInfoData = [];
            $integral_total = 0;
            foreach ($list as $k => $goodsItem) {
                $goodsItem['user_type'] = $this->user['type'];
                $orderInfoData[$k] = [
                    'order_id' => $res1,
                    'pay_type' => $param['pay_type'],
                    'user_id' => $userId,
                    'goods_id' => $goodsItem['id'],
                    'ch_goods_name' => $goodsItem['ch_name'],
                    'en_goods_name' => $goodsItem['en_name'],
                    'goods_image' => strstr($goodsItem['image'],'/uploads'),
                    'number' => $goodsItem['number'],
                    'type' => $goodsItem['type'],
                    'score' => !empty($goodsItem['integral']) ? $goodsItem['integral'] : 0,
                    'goods_total' => get_price($goodsItem),
                    'pay_total' => $data['price'],
                    'postage_total' => $postage,
                ];
                $integral_total += $orderInfoData[$k]['score'];

            }
            $res4 = $this->orderInfoModel->saveAll($orderInfoData);

            if ($res1 && $res2 && $res4 && (empty($res3) || $res3)) {
                Db::commit();
                $this->success('success',['order_id'=>$res1,'order_num'=>$orderData['order_num']]);
            } else {
                $this->error('error');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('error');
        }
    }

    /**
     * @ApiTitle    (确认订单(积分商品))
     * @ApiSummary  (确认订单(积分商品))
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true description="请求的Token")
     * @ApiParams  (name=goods_id, type=string, required=true, description="商品id")
     * @ApiParams  (name=ticket_user_id, type=string, required=false, description="用户优惠券id")
     * @ApiParams  (name=ticket_code, type=string, required=false, description="优惠码")
     * @ApiParams  (name=province_id, type=string, required=false, description="省id /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=city_id, type=string, required=false, description="市 /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=county_id, type=string, required=false, description="县 /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=postage_type, type=string, required=false, description="配送类型:1=闪送,2=普通配送  /api/user_address/getUserAddressDefault 接口获取")
     * @ApiRoute    (/api/order/orderIntegral)
     * @ApiReturn({
    "code": 1,
    "msg": "success",
    "time": "1587691008",
    "data": {
    "price": 263.7, 总价
    "discount_price": 12.3, 折扣价
    "original_price": 246,  原价
    "ticketcode_discount_price": 5,  优惠码优惠价
    "ticket_discount_price": 10,   优惠券优惠价
    "integral": 0,  积分
    "postage": "30.00"  运费
    }
    },
    })
     */
    public function orderIntegral()
    {
        $carModel = new \app\api\model\Car();
        $goodsModel = new \app\api\model\Goods();
        $ticketCodeModel = new \app\api\model\Ticketcode();
        $userTicketModel = new \app\api\model\UserTicket();
        $userId = $this->getUserId();
        $goodsId = $this->request->param('goods_id');
        $ticketId = $this->request->param('ticket_user_id');
        $ticketCode = $this->request->param('ticket_code');
        $provinceId = $this->request->param('province_id',1);  //默认地址为北京
        $cityId = $this->request->param('city_id',2);  //默认地址为北京
        $countyId = $this->request->param('county_id',3);  //默认地址为北京
        $postageType = $this->request->param('postage_type',2); //默认普通配送
        if (empty($goodsId)) $this->error('缺少参数 goods_id!');
        //判断优惠券和优惠码不能同时使用
        if (!empty($ticketCode) && !empty($ticketId)) $this->error('优惠券与优惠码不能同时使用!');


        //获取积分商品状态
        $goodsInfo = $this->integralGoodsModel->where(['id' => $goodsId])->field('id,status,stock_num,goods_price,integral')->find();

        //判断商品是否有库存和状态
        if ($goodsInfo['status'] == 2) $this->error($goodsInfo['ch_name'] . '商品已下架');
        if ($goodsInfo['stock_num'] == 0) $this->error($goodsInfo['ch_name'] . '商品库存不足');
        //判断用户收货区域是否有库存
        $areaStock = $this->integralGoodsModel->getAreaStockNum(['g.id' => $goodsInfo['id'], 'd.area_id' => $provinceId]);
        if (!empty($areaStock) && $areaStock['stock_num'] == 0) $data['is_lack_stock'] = 1;

        //判断优惠码是否可用
        if (!empty($ticketCode)) {
            $ticketCodeInfo = $ticketCodeModel->where('code', $ticketCode)->find();
            if (!$ticketCodeInfo) $this->error('优惠码不存在!');
            if ($ticketCodeInfo['validtime'] < time()) $this->error('优惠码已过期!');
            if ($ticketCodeInfo['user_id']) $this->error('优惠码已使用!');
        }

        //判断优惠券是否可用
        if (!empty($ticketId)) {
            $ticketInfo = $userTicketModel->where(['user_id' => $userId, 'id' => $ticketId, 'status' => 1])->find();
            if (!$ticketInfo) $this->error('优惠码不存在!');
        }

        //获取原价,现价,折扣
        $goodsInfo['user_type'] = $this->user['type'];
        $data['price'] = round(get_price($goodsInfo), 2); //折扣后价格
        $data['discount_price'] = round(get_discount_price($goodsInfo), 2);//折扣金额
        $data['original_price'] = $goodsInfo['goods_price'];//原价
        $data['integral'] = $goodsInfo['integral']; //积分


        //判断积分
        if ($data['integral'] > $this->user['score']) $this->error('积分不足');
        //获取运费
        $is_special = $this->areaExtendModel->where(['province_id' => $provinceId])->value('is_special');
        //特殊地区满200免运费
        if ($is_special == 1 && $data['price'] >= 200) {
            $postage = 0;
            //其他地区满300免运费,闪送无免运费
        } elseif ($data['price'] >= 300 && $postageType != 2) {
            $postage = 0;
        } else {
            //都不满足获取对应的运费
            $postageWhere = ['province_id' => $provinceId, 'city_id' => $cityId, 'county_id' => $countyId];
            if ($postageType == 1) {
                //配送为闪送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage2');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $provinceId])->value('postage2');
                }
            } else {
                //配送为普通配送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage1');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $provinceId])->value('postage1');
                }
            }
        }
        $data['postage'] = $postage;
        $data['price'] += $postage;

        //使用优惠码
        if (!empty($ticketCodeInfo)) {
            $data['price'] = $data['price'] - $ticketCodeInfo['price'];
            $data['ticketcode_discount_price'] = $ticketCodeInfo['price'];
        }

        //使用优惠券
        if (!empty($ticketInfo)) {
            $data['price'] = $data['price'] - $ticketInfo['price'];
            $data['ticket_discount_price'] = $ticketInfo['price'];
        }

        $this->success('success', $data);

    }


    /**
     * @ApiTitle    (创建订单(积分商品))
     * @ApiSummary  (创建订单(积分商品))
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true description="请求的Token")
     * @ApiParams  (name=goods_id, type=string, required=true, description="商品id")
     * @ApiParams  (name=pay_type, type=string, required=false, description="支付类型:1=微信支付,2=余额支付")
     * @ApiParams  (name=ticket_user_id, type=string, required=false, description="用户优惠券id")
     * @ApiParams  (name=ticket_code, type=string, required=false, description="优惠码")
     * @ApiParams  (name=province_id, type=string, required=true, description="商品收货地址省id")
     * @ApiParams  (name=city_id, type=string, required=true, description="商品收货地址市id")
     * @ApiParams  (name=county_id, type=string, required=true, description="商品收货地址县id")
     * @ApiParams  (name=address, type=string, required=true, description="商品收货地址")
     * @ApiParams  (name=name, type=string, required=true, description="商品收货人")
     * @ApiParams  (name=mobile, type=string, required=true, description="商品收货电话")
     * @ApiParams  (name=present_id, type=string, required=false, description="赠品id")
     * @ApiParams  (name=postage_type, type=string, required=true, description="配送类型:1=闪送,2=普通配送")
     * @ApiParams  (name=postage_date, type=string, required=false, description="配送日期")
     * @ApiParams  (name=postage_time, type=string, required=false, description="配送时间")
     * @ApiParams  (name=invoice_status, type=string, required=true, description="发票状态:1=个人或事业单位,2=企业,3=不需要开发票")
     * @ApiParams  (name=invoice_type, type=string, required=false, description="发票类型:1=纸质发票,2=电子发票")
     * @ApiParams  (name=invoice_email, type=string, required=false, description="电子发票邮箱")
     * @ApiParams  (name=taitou, type=string, required=false, description="发票抬头")
     * @ApiParams  (name=duty_num, type=string, required=false, description="发票税号")
     * @ApiParams  (name=invoice_province_id, type=string, required=false, description="发票收货地址省id")
     * @ApiParams  (name=invoice_city_id, type=string, required=false, description="发票收货地址市id")
     * @ApiParams  (name=invoice_county_id, type=string, required=false, description="发票收货地址县id")
     * @ApiParams  (name=invoice_address, type=string, required=false, description="发票收货地址")
     * @ApiParams  (name=invoice_name, type=string, required=false, description="发票收货人")
     * @ApiParams  (name=invoice_mobile, type=string, required=false, description="发票收货电话")
     * @ApiParams  (name=order_note, type=string, required=false, description="订单备注")
     * @ApiRoute    (/api/order/createOrderIntegral)
     * @ApiReturn({

    },
    })
     */
    public function createOrderIntegral()
    {
        $ticketCodeModel = new \app\api\model\Ticketcode();
        $userTicketModel = new \app\api\model\UserTicket();
        $userId = $this->getUserId();
        $param = $this->request->param();
        $param['user_id'] = $userId;
        $validate = new Validate([
            'goods_id' => 'require',
            'pay_type' => 'require',
            'name' => 'require',
            'mobile' => 'require',
            'address' => 'require',
            'province_id' => 'require',
            'city_id' => 'require',
            'county_id' => 'require',
            'postage_type' => 'require',
            'invoice_status' => 'require',

        ]);

        $validate->message([
            'goods_id' => '缺少参数 goods_id!',
            'pay_type' => '缺少参数 pay_type!',
            'name' => '缺少参数 name!',
            'mobile' => '缺少参数 mobile!',
            'address' => '缺少参数 address!',
            'province_id' => '缺少参数 province_id!',
            'city_id' => '缺少参数 city_id!',
            'county_id' => '缺少参数 county_id!',
            'postage_type' => '缺少参数 postage_type!',
            'invoice_status' => '缺少参数 invoice_status!',
        ]);

        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        if (($param['pay_type'] == 2 && $this->user['type'] == 3) || ($param['pay_type'] == 2 && $this->user['type'] == 4)) $this->error('员工或代理不能使用余额支付!');
        //判断优惠券和优惠码不能同时使用
        if (!empty($param['ticket_code']) && !empty($param['ticket_user_id'])) $this->error('优惠券与优惠码不能同时使用!');
        //获取积分商品状态
        $goodsInfo = $this->integralGoodsModel->where(['id' => $param['goods_id']])->field('id,ch_name,en_name,image,status,stock_num,goods_price,integral')->find();

        //判断商品是否有库存和状态
        if ($goodsInfo['status'] == 2) $this->error($goodsInfo['ch_name'] . '商品已下架');
        if ($goodsInfo['stock_num'] == 0) $this->error($goodsInfo['ch_name'] . '商品库存不足');
        //判断用户收货区域是否有库存
        $areaStock = $this->integralGoodsModel->getAreaStockNum(['g.id' => $goodsInfo['id'], 'd.area_id' => $param['province_id']]);
        if (!empty($areaStock) && $areaStock['stock_num'] == 0) $data['is_lack_stock'] = 1;

        //判断优惠码是否可用
        if (!empty($param['ticket_code'])) {
            $ticketCodeInfo = $ticketCodeModel->where('code', $param['ticket_code'])->find();
            if (!$ticketCodeInfo) $this->error('优惠码不存在!');
            if ($ticketCodeInfo['validtime'] < time()) $this->error('优惠码已过期!');
            if ($ticketCodeInfo['user_id']) $this->error('优惠码已使用!');
        }

        //判断优惠券是否可用
        if (!empty($param['ticket_user_id'])) {
            $ticketInfo = $userTicketModel->where(['user_id' => $userId, 'id' => $param['ticket_user_id'], 'status' => 1])->find();
            if (!$ticketInfo) $this->error('优惠码不存在!');
        }

        //获取原价,现价,折扣
        $goodsInfo['user_type'] = $this->user['type'];
        $data['price'] = round(get_price($goodsInfo), 2); //折扣后价格
        $data['discount_price'] = round(get_discount_price($goodsInfo), 2);//折扣金额
        $data['original_price'] = $goodsInfo['goods_price'];//原价
        $data['integral'] = $goodsInfo['integral']; //积分

        //判断积分
        if ($data['integral'] > $this->user['score']) $this->error('积分不足');
        //获取运费
        $is_special = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('is_special');
        //特殊地区满200免运费
        if ($is_special == 1 && $data['price'] >= 200) {
            $postage = 0;
            //其他地区满300免运费,闪送无免运费
        } elseif ($data['price'] >= 300 && $param['postage_type'] != 2) {
            $postage = 0;
        } else {
            //都不满足获取对应的运费
            $postageWhere = ['province_id' => $param['province_id'], 'city_id' => $param['city_id'], 'county_id' => $param['county_id']];
            if ($param['postage_type'] == 1) {
                //配送为闪送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage2');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('postage2');
                }
            } else {
                //配送为普通配送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage1');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('postage1');
                }
            }
        }
        $data['postage'] = $postage;
        $data['price'] += $postage;

        Db::startTrans();
        try {
            //使用优惠码
            if (!empty($ticketCodeInfo)) {
                $data['price'] = $data['price'] - $ticketCodeInfo['price'];
                $data['ticketcode_discount_price'] = $ticketCodeInfo['price'];
                $data['ticketcode_id'] = $ticketCodeInfo['id'];
                $this->ticketCodeModel->where('id', $ticketCodeInfo['id'])->update(['user_id' => $userId]);
            }

            //使用优惠券
            if (!empty($ticketInfo)) {
                $data['price'] = $data['price'] - $ticketInfo['price'];
                $data['ticket_discount_price'] = $ticketInfo['price'];
                $data['user_ticket_id'] = $ticketInfo['id'];
                $this->userTicketModel->where('id', $ticketInfo['id'])->update(['status' => 2]);

            }

            //order表数据
            $orderData = [
                'order_num' => get_order_num(),
                'user_id' => $userId,
                'pay_type' => $param['pay_type'],
                'goods_total' => $data['original_price'],
                'pay_total' => $data['price'],
                'discount_price' => $data['discount_price'],
                'score' => $data['integral'],
                'present_id' => !empty($param['present_id']) ? $param['present_id'] : '',
                'postage_total' => $postage,
                'postage_type' => $param['postage_type'],
                'postage_date' => !empty($data['postage_date']) ? $data['postage_date'] : '',
                'postage_time' => !empty($data['postage_time']) ? $data['postage_time'] : '',
                'user_ticket_id' => !empty($data['user_ticket_id']) ? $data['user_ticket_id'] : '',
                'ticket_price' => !empty($data['ticket_discount_price']) ? $data['ticket_discount_price'] : '',
                'ticketcode_id' => !empty($data['ticketcode_id']) ? $data['ticketcode_id'] : '',
                'ticketcode_price' => !empty($data['ticketcode_discount_price']) ? $data['ticketcode_discount_price'] : '',
                'invoice_status' => $param['invoice_status'],
                'invoice_type' => !empty($param['invoice_type']) ? $param['invoice_type'] : '',
                'invoice_email' => !empty($param['invoice_email']) ? $param['invoice_email'] : '',
                'taitou' => !empty($param['taitou']) ? $param['taitou'] : '',
                'duty_num' => !empty($param['duty_num']) ? $param['duty_num'] : '',
                'order_note' => !empty($param['order_note']) ? $param['order_note'] : '',
                'type' => 2,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $res1 = $this->orderModel->insertGetId($orderData);

            //收货地址数据
            $orderAddress = [
                'order_id' => $res1,
                'name' => $param['name'],
                'mobile' => $param['mobile'],
                'address' => $param['address'],
                'province_id' => $param['province_id'],
                'city_id' => $param['city_id'],
                'county_id' => $param['county_id'],
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $res2 = $this->orderAddressModel->insertData($orderAddress);
            if ($param['invoice_status'] != 3) {
                //收货地址数据
                $orderAddressInvoice = [
                    'order_id' => $res1,
                    'name' => $param['invoice_name'],
                    'mobile' => $param['invoice_mobile'],
                    'address' => $param['invoice_address'],
                    'province_id' => $param['invoice_province_id'],
                    'city_id' => $param['invoice_city_id'],
                    'county_id' => $param['invoice_county_id'],
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                $res3 = $this->orderAddressInvoiceModel->insertData($orderAddressInvoice);
            }

            //获取商品详情列表
            $orderInfoData = [
                'order_id' => $res1,
                'pay_type' => $param['pay_type'],
                'user_id' => $userId,
                'goods_id' => $goodsInfo['id'],
                'ch_goods_name' => $goodsInfo['ch_name'],
                'en_goods_name' => $goodsInfo['en_name'],
                'goods_image' => strstr($goodsInfo['image'],'/uploads'),
                'number' => 1,
                'type' => 2, //积分商品
                'score' => !empty($data['integral']) ? $data['integral'] : 0,
                'goods_total' => get_price($goodsInfo),
                'pay_total' => $data['price'],
                'postage_total' => $postage,
            ];

            $res4 = $this->orderInfoModel->save($orderInfoData);

            if ($res1 && $res2 && $res4 && (empty($res3) || $res3)) {
                Db::commit();
                $this->success('success',['order_id'=>$res1,'order_num'=>$orderData['order_num']]);
            } else {
                $this->error('error');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('error');
        }
    }

    /**
     * @ApiTitle    (确认订单(团购商品))
     * @ApiSummary  (确认订单(团购商品))
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true description="请求的Token")
     * @ApiParams  (name=goods_id, type=string, required=true, description="商品id")
     * @ApiParams  (name=province_id, type=string, required=false, description="省id /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=city_id, type=string, required=false, description="市 /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=county_id, type=string, required=false, description="县 /api/user_address/getUserAddressDefault 接口获取")
     * @ApiParams  (name=postage_type, type=string, required=false, description="配送类型:1=闪送,2=普通配送  /api/user_address/getUserAddressDefault 接口获取")
     * @ApiRoute    (/api/order/orderTeam)
     * @ApiReturn({
    "code": 1,
    "msg": "success",
    "time": "1587691008",
    "data": {
    "price": 263.7, 总价
    "discount_price": 12.3, 折扣价
    "original_price": 246,  原价
    "integral": 0,  积分
    "postage": "30.00"  运费
    "is_lack_stock": "1"  收货地址没货
    }
    },
    })
     */
    public function orderTeam()
    {
        $userId = $this->getUserId();
        $goodsId = $this->request->param('goods_id');
        $provinceId = $this->request->param('province_id',1);  //默认地址为北京
        $cityId = $this->request->param('city_id',2);  //默认地址为北京
        $countyId = $this->request->param('county_id',3);  //默认地址为北京
        $postageType = $this->request->param('postage_type',2); //默认普通配送
        if (empty($goodsId)) $this->error('缺少参数 goods_id!');

        $goodsInfo = $this->goodsModel->where(['id' => $goodsId])->field('id,status,stock_num,is_group,group_num,group_price,grouptime,goods_price')->find();
        //判断商品是否有库存和状态
        if ($goodsInfo['status'] == 2) $this->error('商品已下架');
        if ($goodsInfo['stock_num'] == 0) $this->error('商品库存不足');
        if ($goodsInfo['is_group'] != 1) $this->error('该商品不是团购商品');
        //判断用户收货区域是否有库存
        $areaStock = $this->goodsModel->getAreaStockNum(['g.id' => $goodsId, 'd.area_id' => $provinceId]);
        if (!empty($areaStock) && $areaStock['stock_num'] == 0) $data['is_lack_stock'] = 1;

        //获取原价,现价,折扣
        $data['price'] = 0; //折扣后价格
        $data['discount_price'] = 0; //折扣金额
        $data['original_price'] = 0; //原价
        $goodsInfo['user_type'] = $this->user['type'];
        $data['price'] += round(get_price($goodsInfo), 2);
        $data['discount_price'] += round(get_discount_price($goodsInfo), 2);
        $data['original_price'] += $goodsInfo['group_price'];

        //获取运费
        $is_special = $this->areaExtendModel->where(['province_id' => $provinceId])->value('is_special');
        //特殊地区满200免运费
        if ($is_special == 1 && $data['price'] >= 200) {
            $postage = 0;
            //其他地区满300免运费,闪送无免运费
        } elseif ($data['price'] >= 300 && $postageType != 2) {
            $postage = 0;
        } else {
            //都不满足获取对应的运费
            $postageWhere = ['province_id' => $provinceId, 'city_id' => $cityId, 'county_id' => $countyId];
            if ($postageType == 1) {
                //配送为闪送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage2');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $provinceId])->value('postage2');
                }
            } else {
                //配送为普通配送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage1');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $provinceId])->value('postage1');
                }
            }
        }
        $data['postage'] = $postage;
        $data['price'] += $postage;


        $this->success('success', $data);

    }

    /**
     * @ApiTitle    (创建订单(团购商品))
     * @ApiSummary  (创建订单(团购商品))
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true description="请求的Token")
     * @ApiParams  (name=goods_id, type=string, required=false, description="商品id")
     * @ApiParams  (name=team_group_id, type=string, required=false, description="拼团id")
     * @ApiParams  (name=pay_type, type=string, required=false, description="支付类型:1=微信支付,2=余额支付")
     * @ApiParams  (name=province_id, type=string, required=true, description="商品收货地址省id")
     * @ApiParams  (name=city_id, type=string, required=true, description="商品收货地址市id")
     * @ApiParams  (name=county_id, type=string, required=true, description="商品收货地址县id")
     * @ApiParams  (name=address, type=string, required=true, description="商品收货地址")
     * @ApiParams  (name=name, type=string, required=true, description="商品收货人")
     * @ApiParams  (name=mobile, type=string, required=true, description="商品收货电话")
     * @ApiParams  (name=present_id, type=string, required=false, description="赠品id")
     * @ApiParams  (name=postage_type, type=string, required=true, description="配送类型:1=闪送,2=普通配送")
     * @ApiParams  (name=postage_date, type=string, required=false, description="配送日期")
     * @ApiParams  (name=postage_time, type=string, required=false, description="配送时间")
     * @ApiParams  (name=invoice_status, type=string, required=true, description="发票状态:1=个人或事业单位,2=企业,3=不需要开发票")
     * @ApiParams  (name=invoice_type, type=string, required=false, description="发票类型:1=纸质发票,2=电子发票")
     * @ApiParams  (name=invoice_email, type=string, required=false, description="电子发票邮箱")
     * @ApiParams  (name=taitou, type=string, required=false, description="发票抬头")
     * @ApiParams  (name=duty_num, type=string, required=false, description="发票税号")
     * @ApiParams  (name=invoice_province_id, type=string, required=false, description="发票收货地址省id")
     * @ApiParams  (name=invoice_city_id, type=string, required=false, description="发票收货地址市id")
     * @ApiParams  (name=invoice_county_id, type=string, required=false, description="发票收货地址县id")
     * @ApiParams  (name=invoice_address, type=string, required=false, description="发票收货地址")
     * @ApiParams  (name=invoice_name, type=string, required=false, description="发票收货人")
     * @ApiParams  (name=invoice_mobile, type=string, required=false, description="发票收货电话")
     * @ApiParams  (name=order_note, type=string, required=false, description="订单备注")
     * @ApiRoute    (/api/order/createOrderTeam)
     * @ApiReturn({

    },
    })
     */
    public function createOrderTeam()
    {
        $userId = $this->getUserId();
        $param = $this->request->param();
        $param['user_id'] = $userId;
        $validate = new Validate([
            'goods_id' => 'require',
            'pay_type' => 'require',
            'name' => 'require',
            'mobile' => 'require',
            'address' => 'require',
            'province_id' => 'require',
            'city_id' => 'require',
            'county_id' => 'require',
            'postage_type' => 'require',
            'invoice_status' => 'require',

        ]);

        $validate->message([
            'goods_id' => '缺少参数 goods_id!',
            'pay_type' => '缺少参数 pay_type!',
            'name' => '缺少参数 name!',
            'mobile' => '缺少参数 mobile!',
            'address' => '缺少参数 address!',
            'province_id' => '缺少参数 province_id!',
            'city_id' => '缺少参数 city_id!',
            'county_id' => '缺少参数 county_id!',
            'postage_type' => '缺少参数 postage_type!',
            'invoice_status' => '缺少参数 invoice_status!',
        ]);

        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        if (($param['pay_type'] == 2 && $this->user['type'] == 3) || ($param['pay_type'] == 2 && $this->user['type'] == 4)) $this->error('员工或代理不能使用余额支付!');

        $goodsInfo = $this->goodsModel->where(['id' => $param['goods_id']])->field('id,status,stock_num,is_group,group_num,group_price,grouptime,goods_price,ch_name,en_name,image')->find();
        //判断商品是否有库存和状态
        if ($goodsInfo['status'] == 2) $this->error('商品已下架');
        if ($goodsInfo['stock_num'] == 0) $this->error('商品库存不足');
        if ($goodsInfo['is_group'] != 1) $this->error('该商品不是团购商品');
        //判断用户收货区域是否有库存
        $areaStock = $this->goodsModel->getAreaStockNum(['g.id' => $param['goods_id'], 'd.area_id' => $param['province_id']]);
        if (!empty($areaStock) && $areaStock['stock_num'] == 0) $data['is_lack_stock'] = 1;

        //判断团购是否满人
        if (!empty($param['team_group_id'])) {
            $teamInfo = Db::name('team_group')->where('id', $param['team_group_id'])->field('group_num,grouptime')->find();
            $count = Db::name('team_group_info')->where('team_group_id', $param['team_group_id'])->count();
            $is_join_team = Db::name('team_group_info')->where(['team_group_id' => $param['team_group_id'], 'user_id' => $userId])->count();
            if (!$teamInfo) $this->error('没有此拼团信息');
            if ($teamInfo['grouptime'] <= time()) $this->error('拼团已失效');
            if ($teamInfo['group_num'] <= $count) $this->error('参团人数已满');
            if ($is_join_team) $this->error('您已参团了');
        }

        //获取原价,现价,折扣
        $data['price'] = 0; //折扣后价格
        $data['discount_price'] = 0; //折扣金额
        $data['original_price'] = 0; //原价
        $goodsInfo['user_type'] = $this->user['type'];
        $data['price'] += round(get_price($goodsInfo), 2);
        $data['discount_price'] += round(get_discount_price($goodsInfo), 2);
        $data['original_price'] += $goodsInfo['group_price'];

        //获取运费
        $is_special = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('is_special');
        //特殊地区满200免运费
        if ($is_special == 1 && $data['price'] >= 200) {
            $postage = 0;
            //其他地区满300免运费,闪送无免运费
        } elseif ($data['price'] >= 300 && $param['postage_type'] != 2) {
            $postage = 0;
        } else {
            //都不满足获取对应的运费
            $postageWhere = ['province_id' => $param['province_id'], 'city_id' => $param['city_id'], 'county_id' => $param['county_id']];
            if ($param['postage_type'] == 1) {
                //配送为闪送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage2');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('postage2');
                }
            } else {
                //配送为普通配送
                $postage = $this->areaExtendModel->where($postageWhere)->value('postage1');
                if (!$postage) {
                    $postage = $this->areaExtendModel->where(['province_id' => $param['province_id']])->value('postage1');
                }
            }
        }
        $data['postage'] = $postage;
        $data['price'] += $postage;


        Db::startTrans();
        try {
            //order表数据
            $orderData = [
                'order_num' => get_order_num(),
                'user_id' => $userId,
                'pay_type' => $param['pay_type'],
                'goods_total' => $data['original_price'],
                'pay_total' => $data['price'],
                'discount_price' => $data['discount_price'],
                'present_id' => !empty($param['present_id']) ? $param['present_id'] : '',
                'team_group_id' => !empty($param['team_group_id']) ? $param['team_group_id'] : '',
                'team_group_status' => 1,
                'postage_total' => $postage,
                'postage_type' => $param['postage_type'],
                'postage_date' => !empty($data['postage_date']) ? $data['postage_date'] : '',
                'postage_time' => !empty($data['postage_time']) ? $data['postage_time'] : '',
                'user_ticket_id' => !empty($data['user_ticket_id']) ? $data['user_ticket_id'] : '',
                'ticket_price' => !empty($data['ticket_discount_price']) ? $data['ticket_discount_price'] : '',
                'ticketcode_id' => !empty($data['ticketcode_id']) ? $data['ticketcode_id'] : '',
                'ticketcode_price' => !empty($data['ticketcode_discount_price']) ? $data['ticketcode_discount_price'] : '',
                'invoice_status' => $param['invoice_status'],
                'invoice_type' => !empty($param['invoice_type']) ? $param['invoice_type'] : '',
                'invoice_email' => !empty($param['invoice_email']) ? $param['invoice_email'] : '',
                'taitou' => !empty($param['taitou']) ? $param['taitou'] : '',
                'duty_num' => !empty($param['duty_num']) ? $param['duty_num'] : '',
                'order_note' => !empty($param['order_note']) ? $param['order_note'] : '',
                'type' => 3,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $res1 = $this->orderModel->insertGetId($orderData);

            //收货地址数据
            $orderAddress = [
                'order_id' => $res1,
                'name' => $param['name'],
                'mobile' => $param['mobile'],
                'address' => $param['address'],
                'province_id' => $param['province_id'],
                'city_id' => $param['city_id'],
                'county_id' => $param['county_id'],
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $res2 = $this->orderAddressModel->insertData($orderAddress);
            if ($param['invoice_status'] != 3) {
                //收货地址数据
                $orderAddressInvoice = [
                    'order_id' => $res1,
                    'name' => $param['invoice_name'],
                    'mobile' => $param['invoice_mobile'],
                    'address' => $param['invoice_address'],
                    'province_id' => $param['invoice_province_id'],
                    'city_id' => $param['invoice_city_id'],
                    'county_id' => $param['invoice_county_id'],
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                $res3 = $this->orderAddressInvoiceModel->insertData($orderAddressInvoice);
            }

            //获取商品详情
            $orderInfoData = [
                'order_id' => $res1,
                'pay_type' => $param['pay_type'],
                'user_id' => $userId,
                'goods_id' => $param['goods_id'],
                'ch_goods_name' => $goodsInfo['ch_name'],
                'en_goods_name' => $goodsInfo['en_name'],
                'goods_image' => strstr($goodsInfo['image'],'/uploads'),
                'number' => 1, //团购商品购买数量只能是1
                'type' => 3,
                'goods_total' => $data['original_price'],
                'pay_total' => $data['price'],
                'postage_total' => $postage,
            ];

            $res4 = $this->orderInfoModel->save($orderInfoData);

            if ($res1 && $res2 && $res4 && (empty($res3) || $res3)) {
                Db::commit();
                $this->success('success',['order_id'=>$res1,'order_num'=>$orderData['order_num']]);
            } else {
                $this->error('error');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('error');
        }
    }

    /**
     * @ApiTitle    (订单付款)
     * @ApiSummary  (订单付款)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/orderPay)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=order_id, type=string, required=true, description="订单id")
     * @ApiReturn   ({
    })
     */
    public function orderPay()
    {
        $userId = $this->getUserId();
        $param = $this->request->param();
        $rule = [
            'order_id' => 'require',
        ];

        $msg = [
            'order_id' => '缺少参数 order_id!',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $order = $this->orderModel->where(['id' => $param['order_id']])->find();
        if (!$order) $this->error('订单不存在');
        if ($order['status'] == 2) $this->error('订单已支付');
        if ($order['status'] == -1) $this->error('订单已取消');
        //判断积分
        if ($order['score'] > $this->user['score']) $this->error('积分不足');
        //获取订单商品id,库存
        $goodsList = $this->orderInfoModel->where('order_id', $order['id'])->field('goods_id,number,ch_goods_name,type,score')->select();
        foreach ($goodsList as $k => $v) {
            if ($v['type'] == 2) {
                //判断积分商品是否有库存
                $is_stock = $this->integralGoodsModel->checkStockNum($v['goods_id'], $v['number']);
                if (!$is_stock) $this->error($v['ch_goods_name'] . ' 库存不足');
            } else {
                //判断商品是否有库存
                $is_stock = $this->goodsModel->checkStockNum($v['goods_id'], $v['number']);
                if (!$is_stock) $this->error($v['ch_goods_name'] . ' 库存不足');
            }
        }
        //判断团购是否满人
        if (!empty($order['team_group_id'])) {
            $teamInfo = Db::name('team_group')->where('id', $order['team_group_id'])->field('group_num,grouptime')->find();
            $count = Db::name('team_group_info')->where('team_group_id', $order['team_group_id'])->count();
            if ($teamInfo['group_num'] <= $count) $this->error('参团人数已满');
            if ($teamInfo['grouptime'] <= time()) $this->error('拼团已失效');
        }
        $amount = $order['pay_total'];
        $payType = $order['pay_type'];
        if ($payType == '2') {
            //余额支付
            if ($this->user['money'] >= $amount) {
                $res = $this->orderModel->balancePay($param['order_id'], $userId, $amount, $goodsList);
                if ($res && empty($res['code'])) $this->success('支付成功');
                elseif (!empty($res['code'])) $this->error($res['msg']);
                else $this->error('支付失败');
            } else {
                $this->error('余额不足');
            }
        } elseif ($payType == '1') {
            $pay = new Pay();
            $openid = $this->userModel->getOpenid($userId);
            //微信支付
            $res = $pay->wx_pay($order['order_num'], '下单', $order['pay_total'], 'api/pay/notify', $openid);
            $resArr = json_decode($res);
            if ($resArr) {
                $this->success('success', $resArr);
            } else {
                $this->error($res);
            }
        }
    }

    /**
     * @ApiTitle    (取消订单)
     * @ApiSummary  (取消订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/orderCancel)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=order_id, type=string, required=true, description="订单id")
     * @ApiReturn   ({
    })
     */
    public function orderCancel()
    {
        $userId = $this->getUserId();
        $param = $this->request->param();
        $rule = [
            'order_id' => 'require',
        ];

        $msg = [
            'order_id' => '缺少参数 order_id!',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $order = $this->orderModel->where(['id' => $param['order_id']])->find();
        if (!$order) $this->error('订单不存在');
        if ($order['status'] == 2) $this->error('订单已支付');
        if ($order['status'] == -1) $this->error('订单已取消');

        $res = $this->orderModel->orderCancel($order);
        if ($res) $this->success('取消订单成功');
        else $this->error('取消订单失败');
    }

    /**
     * @ApiTitle    (删除订单)
     * @ApiSummary  (删除订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/orderDel)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=order_id, type=string, required=true, description="订单id")
     * @ApiReturn   ({
    })
     */
    public function orderDel()
    {
        $userId = $this->getUserId();
        $param = $this->request->param();
        $rule = [
            'order_id' => 'require',
        ];

        $msg = [
            'order_id' => '缺少参数 order_id!',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }
        $order = $this->orderModel->where(['id' => $param['order_id']])->find();
        if (!$order) $this->error('订单不存在');
        if ($order['status'] != -1) $this->error('此订单状态不可删除');

        $res = $this->orderModel->where('id',$param['order_id'])->delete();
        if ($res) $this->success('删除订单成功');
        else $this->error('删除订单失败');
    }
    /**
     * @ApiTitle    (确认收货)
     * @ApiSummary  (确认收货)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/receiving)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=order_detail_id, type=string, required=true, description="订单id")
     * @ApiReturn({
    })
     */
    public function receiving(){
        $model = new OrderDetail();
        $order_detail_id = $this->request->param('order_detail_id');
        if (!$order_detail_id) $this->error('缺少参数 order_detail_id');
        $orderInfo = $model->where(['id'=>$order_detail_id])->find();
        if ($orderInfo['status'] != 3) $this->error('此订单状态不可确认收货');
        $res = $model->where(['id'=>$order_detail_id])->update(['status'=>4]);
        if ($res) $this->success('确认收货成功');
        else $this->error('确认收货失败');
    }
    /**
     * @ApiTitle    (订单详情)
     * @ApiSummary  (订单详情)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/orderInfo)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=order_id, type=string, required=true, description="订单id")
     * @ApiParams  (name=order_detail_id, type=string, required=false, description="订单子表id")
     * @ApiReturn   ({
    {
    "code": 1,
    "msg": "success",
    "time": "1588041622",
    "data": {
    "createtime": "2020-04-27 16:56:31",    下单时间
    "order_num": "2020042710254102",   订单号
    "status": "2",
    "postage_date": "",    配送日期
    "postage_time": "",    配送时间
    "pay_type": "2",      支付类型
    "pay_total": "55.65",   支付金额
    "goods_total": "27.00",   商品金额
    "postage_total": "30.00",    运费
    "discount_price": "1.35",    折扣金额
    "score": "",       积分
    "ticket_price": "0.00",   优惠券金额
    "ticketcode_id": 0,
    "ticketcode": 0,  优惠码
    "name": "",   收货人姓名
    "mobile": "13752011792",    收货人手机号
    "address": 123,    收货详情地址
    "ch_province_name": "天津",   收货地址省
    "ch_city_name": "天津市",        收货地址市
    "ch_county_name": "和平区",  收货地址县
    "status_text": "已完成"  订单状态
    }
    }
    })
     */
    public function orderInfo()
    {
        $userId = $this->getUserId();
        $param = $this->request->param();
        $tickcodeModel = new \app\api\model\Ticketcode();
        $rule = [
            'order_id' => 'require',
        ];

        $msg = [
            'order_id' => '缺少参数 order_id!',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            $this->error(__($validate->getError()));
        }

        $order = $this->orderModel->getInfo(['o.id' => $param['order_id']]);
        if (!$order) $this->error('订单不存在');

        $order['image'] = cdnurl_arr($this->orderInfoModel->where('order_id',$param['order_id'])->column('goods_image'));

        if (!empty($order['ticketcode_id'])) {
            $order['ticketcode'] = $this->ticketCodeModel->where('id', $order['ticketcode_id'])->value('code');
        }else{
            $order['ticketcode'] = '';
        }
        $detailInfo = $this->orderDetailModel->where('id', $param['order_detail_id'])->field('shipper_code,logistic_code,status')->find();
        if (!empty($order['team_group_status'] && $order['team_group_status'] == 1 && $order['status'] == 2)) {
            $order['status'] = '6';
            $order['status_text'] = '待成团';
        } elseif (!empty($order['team_group_status'] && $order['team_group_status'] == 2 && $detailInfo['status'] == 2)) {
            $order['status_text'] = '待发货';
        } elseif (!empty($order['team_group_status'] && $order['team_group_status'] == 3 && $order['status'] == 1)) {
            $order['status'] = '7';
            $order['status_text'] = '拼团失败';
        } elseif ($order['status'] == 2) {
            $order['status_text'] = $this->orderDetailModel->where('order_id', $param['order_id'])->field('status')->find()['status_text'];
        } elseif ($order['status'] == 1) {
            $order['status_text'] = '待付款';
        } elseif ($order['status'] == 3) {
            $order['status'] = '8';
            $order['status_text'] = '已退款';
            $orderRefundModel = new OrderRefund();
            $orderRefundInfo = $orderRefundModel->where('order_num',$order['order_num'])->find();
            if ($orderRefundInfo){
                $order['refund_time'] = date('Y-m-d H:i:s',$orderRefundInfo['createtime']);
                if ($orderRefundInfo['type'] == 1) $order['refund_remark'] = '退款至余额钱包';
                else $order['refund_remark'] = '退款至微信钱包';
                $order['refund_price'] = $orderRefundInfo['total'];
            }

        }

        if ($detailInfo['status'] == 3 || $detailInfo['status'] == 4 || $detailInfo['status'] == 5) {
            if (empty($detailInfo['shipper_code']) || empty($detailInfo['logistic_code'])) {
                $this->error('该订单缺少物流单号或者快递公司编码参数');
            }
            $code = $detailInfo['logistic_code'];
            $company = $detailInfo['shipper_code'];
            $kdniao = new Kdniao();

            $wuliu = $kdniao->getOrderTracesByJson($company, $code);
            $wuliu = json_decode($wuliu, true);
            $wuliu = isset($wuliu['Traces']) && count($wuliu['Traces']) ? array_reverse($wuliu['Traces']) : ['AcceptStation' => '暂无物流信息', 'AcceptTime' => date('Y-m-d H:i:s', time())];
            if (!empty($wuliu[0])) {
                $order['wuliu'] = $wuliu[0];
            } else {
                $order['wuliu'] = $wuliu;
            }
        }

        $this->success('success', $order);
    }

    /**
     * @ApiTitle    (订单物流详情)
     * @ApiSummary  (订单物流详情)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/order/orderLogisticsInfo)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name=order_detail_id, type=string, required=true, description="订单子表id")
     * @ApiReturn   ({
    })
     */
    public function orderLogisticsInfo()
    {
        $user_id = $this->getUserId();
        $order_detail_id = $this->request->param('order_detail_id');
        $orderDetailModel = new OrderDetail();
        $where['user_id'] = ['eq', $user_id];
        $where['id'] = ['eq', $order_detail_id];
        $data = $orderDetailModel->where($where)->field('shipper_code,logistic_code')->find();
        if (empty($data)) {
            $this->error('查询为空');
        }

        if (empty($data['shipper_code']) || empty($data['logistic_code'])) {
            $this->error('该订单缺少物流单号或者快递公司编码参数');
        }
        $code = $data['logistic_code'];
        $company = $data['shipper_code'];
        $kdniao = new Kdniao();

        $wuliu = $kdniao->getOrderTracesByJson($company, $code);
        $wuliu = json_decode($wuliu, true);
        $wuliu = isset($wuliu['Traces']) && count($wuliu['Traces']) ? array_reverse($wuliu['Traces']) : [['AcceptStation' => '暂无物流信息', 'AcceptTime' => date('Y-m-d H:i:s', time())]];
        $data['company_name'] = Db::name('kdniao')->where(['code' => $data['logistic_code']])->value('company');
        $data['wuliu'] = $wuliu;
        $this->success('SUCCESS', $data);
    }
}