order

<?php

namespace app\api\controller;

use addons\shopro\model\OrderAction;
use addons\shopro\model\User;
use app\admin\model\Market;
use app\common\controller\Api;
use app\common\model\GoodsComment;
use app\common\model\GoodsLabel;
use app\common\model\ServingCell;
use app\common\model\ShopCategory;
use app\common\model\ShopConfigs;
use app\common\model\ShopCoupons;
use app\common\model\ShopMarket;
use app\common\model\ShopOrder;
use app\common\model\ShopOrderItem;
use app\common\model\ShopServingCell;
use app\common\model\ShopCart;
use app\common\model\Goods;
use app\common\model\ShopUserCoupons;
use app\common\model\ShopUserCouponsLog;
use app\common\model\ShopUserCouponsNum;
use app\common\model\UserServingCell;
use app\common\model\shop\refund\Reason;


use think\Collection;
use think\Db;
use think\Exception;

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

    /**
     * 用户订单列表
     *
     */
    public function orderList()
    {
        $order_type = $this->request->post("order_type");
        $page = $this->request->post('page',1);
        $limit = $this->request->post('limit',10);

        $user = $this->auth->getUserinfo();
        $param = [
            'user_id'   => $user['id'],
            'order_type'=> $order_type,
        ];
        $result = ShopOrder::getUserOrderList($param,$page,$limit);
        $this->success('成功', $result);
    }

    /**
     * 用户订单商品详情
     *
     */
    public function orderDetails()
    {
        $order_id = $this->request->post("order_id");
        if(!$order_id){
            $this->error('参数错误!');
        }
        $result = ShopOrder::getOrderDetails($order_id);
        $this->success('成功', $result);
    }

    /**
     * 下单前准备购物车信息
     *
     */
    public function beforeOrderCart()
    {
        $shop_id = $this->request->post("shop_id");
        $cart_ids = $this->request->post("cart_ids");
        $platform_coupons = $this->request->post("platform_coupons",''); //平台券
        $shop_coupons = $this->request->post("shop_coupons",'');

        if(!$shop_id){
            $this->error('店铺参数错误!');
        }
        if(!$cart_ids){
            $this->error('购物车参数错误');
        }
        $time = time();
        $user = $this->auth->getUserinfo();
        $cell = UserServingCell::getMyDefServingCell($user['id']);

        $goodsList = ShopCart::getShopCartInfo($cart_ids);
        $cart_price = 0;
        if($goodsList){
            foreach ($goodsList as $value){
                $market = ShopMarket::getMarket($value->market_id);


                if($market){

                    if(strtotime(date("Y-m-d").$market->order_endtime) < $time){
                        $this->error('超出下单时间');
                    }
                }

                //计算订单价格
                $cart_price += bcmul($value['goods_num'],$value['price'],2);
            }

        }
        //优惠总金额
        $coupons_all =0;
        $platform_coupons_price = 0;
        $shop_coupons_price = 0;
        if($platform_coupons!==""){
           //查询一次
            $res = ShopUserCoupons::with(['shopcoupons'])->where(['tcs_shop_user_coupons.id'=>$platform_coupons,'source'=>1])->find()->toArray();
            if(!empty($res)){
                if($res['shopcoupons']['amount']<$cart_price) {
                    $cart_price = bcsub($cart_price, $res['shopcoupons']['amount'], 2);
                    $coupons_all +=$res['shopcoupons']['amount'];
                    $platform_coupons_price = $res['shopcoupons']['amount'];
                }
            }

        }
        if($shop_coupons!==""){
            //查询一次
            $res = ShopUserCoupons::with(['shopcoupons'])->where(['tcs_shop_user_coupons.id'=>$shop_coupons,'source'=>2])->find()->toArray();
            if(!empty($res)){
                if($res['shopcoupons']['amount']<$cart_price) {
                    $cart_price = bcsub($cart_price, $res['shopcoupons']['amount'], 2);
                    $coupons_all +=$res['shopcoupons']['amount'];
                    $shop_coupons_price = $res['shopcoupons']['amount'];
                }
            }
        }

        //查询打包费 添加打包费
        $configs = ShopConfigs::where(['name' => 'order'])->find();
        $configs_value = json_decode($configs['value'], true);

        $cart_price = bcadd($configs_value['packing_charge'],$cart_price,2);


         $Mycoupons = ShopUserCoupons::getMyShopCouponsNum($user['id']);
        $result = [
            'cell_info'     => $cell,
            'goods_info'    => $goodsList,
            'coupons_goods' => $Mycoupons,
            'cart_price'=>$cart_price,
            'coupons_all'=>$coupons_all,
            'platform_coupons_price'=>$platform_coupons_price,
            'shop_coupons_price'=>$shop_coupons_price,
            'packing_charge'=>$configs_value['packing_charge'],
        ];
        $this->success('成功', $result);
    }

    /**
     * 下单前准备服务小区信息
     *
     */
    public function beforeOrderCell()
    {
        $cell_id = $this->request->post("cell_id");

        if(!$cell_id){
            $this->error('请选择服务小区!');
        }
        $cell = UserServingCell::getMyServingCellOne($cell_id);
        $this->success('成功', $cell);
    }

    /**
     * 下单前准备集市送达时间
     *
     */
    public function beforeOrderMarket()
    {
        $market_id = $this->request->post("market_id");
        if(!$market_id){
            $this->error('参数错误!');
        }
        $res = ShopMarket::where(['id' => $market_id])->find();
        $this->success('成功', $res);
    }

    /**
     * 获取我的优惠券
     *
     */
    public function myCoupons()
    {
        $shop_id = $this->request->post("shop_id");
        $cart_ids = $this->request->post("cart_ids");
        $source = $this->request->post("source", ""); //优惠券来源:1.平台,2.店铺
        $coupons_type = $this->request->post('type',0);   //类型:1=满减券,2=营销次券 //优惠券类型:1.商品券,2.店铺券
        if($coupons_type == 0){
            $coupons_type = 2;  //优惠券类型:1.商品券,2.店铺券
        }else{
            $coupons_type = 1;
        }
        $where = [];
        if($source==2){
            $where['tcs_shop_coupons.coupons_type'] = ['=', $coupons_type];
        }


        $user = $this->auth->getUserinfo();
        $goodsList = ShopCart::getShopCartInfo($cart_ids);
        if(!$goodsList){
            $this->error('购物车参数有误');
        }
        $goodsList = collection($goodsList)->toArray();
        $price = 0;
        $goods_ids = [];
        foreach ($goodsList as $value){
            array_push($goods_ids, $value['goods_id']);
            $price = $price + $value['price'] * $value['goods_num'];
        }
//        $Mycoupons = ShopUserCoupons::getMyShopCouponsAll($user['id'], $source,$coupons_type);


        $Mycoupons = ShopUserCoupons::with(['shopcoupons'])
            ->where(['user_id'=>$user['id'],'source'=>$source])
            ->where($where)
            ->paginate()->toArray();

        if($Mycoupons['data']){
            //获取今日开始时间戳和结束时间戳
            $today_start = mktime(0,0,0,date('m'),date('d'),date('Y'));
            $today_end = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

            foreach ($Mycoupons['data'] as &$v){
                $coupons_log_num = ShopUserCouponsLog::where([
                    'coupons_id' => $v['coupons_id'],
                    'user_id' => $user['id'],
                    'createtime' => ['between', [$today_start, $today_end]],
                ])->count();

                $v['not_use'] = '';
                if($coupons_log_num >= $v['use_times']){
                    $v['not_use'] = '已达当天使用限制';
                    continue;
                }
                if($v['status'] == 2 && $v['endtime'] < time()){
                    $v['not_use'] = '已过期';
                    continue;
                }
                if($v['shop_id'] != $shop_id && $v['shopcoupons']['source'] == 2){
                    $v['not_use'] = '不是该店铺优惠券';
                    continue;
                }
                if($v['coupon_type'] == 1 && $v['shopcoupons']['enough'] > $price){
                    $v['not_use'] = '不满足金额门槛';
                    continue;
                }
                if($v['shopcoupons']['goods_ids'] == '0'){
                    continue;
                }
                if($goods_ids){
                    $num = 0;
                    foreach ($goods_ids as $item){
                        $goodsInfo = Goods::where(['id' => $item])->find();
                        if(!$goodsInfo){
                            $this->error('商品信息异常');
                        }
                        if(in_array($item, explode(',', $v['shopcoupons']['goods_ids'])) || $v['shopcoupons']['goods_ids'] == 0){
                            $num = $num + 1;
                        }
                        if($goodsInfo->goods_label){
                            $goods_label = json_decode($goodsInfo->goods_label, true);
                            if($goods_label){
                                foreach ($goods_label as $val){
                                    $title = GoodsLabel::where(['id' => $val['id']])->value('name');
                                    if($title == '限量折扣' || $title == '限购产品'){
                                        if($v['coupons_type'] == 1){
                                            $v['not_use'] = '有折扣或限购,该商品券不可用!';
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if($num < 1){
                        $v['not_use'] = '指定商品可用!';
                    }
                }
            }
        }
        $this->success('成功', $Mycoupons);
    }

    /**
     * 下单
     *
     */
    public function addOrder()
    {
        $shop_id = $this->request->post("shop_id");
        $cell_id = $this->request->post("cell_id");
        $coupons_id = $this->request->post("coupons_id");
        $cart_ids = $this->request->post("cart_ids");
        $num_goods_id = $this->request->post("num_goods_id");
        $remark = $this->request->post("remark");
        $platform = $this->request->post("platform", "App");
        $market_id = $this->request->post("market_id");
        $expect_send_time = $this->request->post("expect_send_time");
        $user = $this->auth->getUserinfo();
        if(!$shop_id){
            $this->error('店铺参数错误');
        }
        if(!$cart_ids){
            $this->error('购物车参数错误');
        }
        $cell = UserServingCell::getMyServingCellOne($cell_id);

        $goodsList = ShopCart::getShopCartInfo($cart_ids);

        //追加 折扣价格 优惠价格[1平台优惠 2店铺优惠[1全部优惠2指定商品优惠]]
        $goodsList = array_map(function($item){
            $item['dis_price'] = 0; // 折扣价格
            $item['dis_num']   = 0; // 折扣个数
            $item['cou_price'] = 0; // 优惠价格
            $item['cou_id']    = 0; // 指定商品优惠券id
            return $item;
        }, $goodsList);

        if(!$goodsList){
            $this->error('购物车参数有误');
        }
        $goodsList = collection($goodsList)->toArray();

        $coupons_ids = explode(',', $coupons_id); //我的优惠券iD //查询用户优惠券关联ID
        //查询优惠券总数
        $coupon = ShopCoupons::where('id','in',$coupons_ids)->select();

        $ShopUserCouponsData = [];
        $ShopUserCouponsNum = [];
        $ShopUserCoupons = ShopUserCoupons::where(['user_id' => $user['id'], 'coupons_id' => ['in', $coupons_id]])->select();
        foreach ($ShopUserCoupons as $couponValue){
            if($couponValue->use_num == 0){
                $this->error("可使用次数已用完");
            }
            if($couponValue->use_num == 1){
                $ShopUserCouponsData[]['status'] = 2;
            }
            $ShopUserCouponsData[]['coupons_id'] = $couponValue->coupons_id;
            $ShopUserCouponsData[]['coupon_type'] = $couponValue->coupon_type;
            $ShopUserCouponsData[]['use_num'] = $couponValue->use_num - 1;
            $ShopUserCouponsData[]['used_num'] = $couponValue->used_num + 1;
        }

        if($num_goods_id) {
            $nunCouponsInfo = ShopCoupons::getGoodsCoupons($num_goods_id);
            $ShopUserCouponsNum = ShopUserCoupons::where(['user_id' => $user['id'], 'coupons_id' => $nunCouponsInfo->id])->find();
            if($ShopUserCouponsNum) {
                if ($ShopUserCouponsNum->use_num == 0) {
                    $this->error("次券可使用次数已用完");
                }
            }
        }
        $price = 0;
        $discount_fee = 0; //优惠券优惠价格
        $pay_fee = 0;      //实际支付价格
        $coupon_fee = 0;
        $goods_ids = [];
        $platform_coupon_id = 0;
        $shop_coupon_id = 0;

        $discount_price = [];
        $pay_price = [];
        $goods_amount = 0; //商品总价
        $total_amount = 0; //订单总金额
        $discounted_price = 0;
        $week = date("w");
        if($week == 0){
            $week = 7;
        }

        $time = date('H:i:s',strtotime('now'));
        //获取今日开始时间戳和结束时间戳
        $today_start = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $today_end = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

        $send_endtime = '';
        //查询集市结束时间
        $endtime = ShopMarket::where(['id' =>$market_id])->find();

        if(strtotime(date('Y-m-d'. $endtime->order_endtime)) < strtotime(date('Y-m-d'. $time))){
            $this->error('超出下单时间');
        }

        foreach ($goodsList as &$value){

            $market_id = $value['market_id']; //集市id
            $goodsInfo = Goods::where(['id' => $value['goods_id']])->find(); //根据id获取商品
            $market = ShopMarket::where(['id' => $value['market_id']])->find();

            
            if(!$market){
                $this->error('集市参数错误');
            }
            $send_endtime = $market->send_endtime;

            if($goodsInfo->goods_type == 1){
                if(!$goodsInfo->shop_id){
                    $this->error('门店参数有误');
                }
                $shopInfo = \app\common\model\Shop::where(['id' => $goodsInfo->shop_id])->find();
                if($shopInfo){

                    if($shopInfo->status==2){
                        $this->error('该门店正在休息中');
                    }

                    if(!in_array($week, explode(',', $shopInfo->job_days))){
                        $this->error('该门店不在营业时间');
                    }
                }
            }
            if($goodsInfo->goods_type == 2){
                if(!$goodsInfo->supplier_id){
                    $this->error('供应商参数有误');
                }
                $supplierInfo = \app\common\model\Supplier::where(['id' => $goodsInfo->supplier_id])->find();
                if($supplierInfo){
                    var_dump($week);
                    var_dump($supplierInfo->job_days);
                    if(!in_array($week, explode(',', $supplierInfo->job_days))){
                        $this->error('商品:' . $value['title'] . '已售罄');
                    }
                }
            }

            array_push($goods_ids, $value['goods_id']);
            $goods_amount += bcmul($value['price'], $value['goods_num'],2);

            $price += bcmul($value['price'], $value['goods_num'],2); //20231018 zss


            $discount_price[$value['goods_id']] = 0;
            $pay_price[$value['goods_id']] = $value['price'] * $value['goods_num'];


            if(empty($value['goods_label']) && empty($coupon)){

                $pay_fee = $price; //不适使用优惠券 和则扣  没有使用优惠券走了
            }



            if(!empty($value['goods_label'])){


                $goods_label = json_decode($value['goods_label'], true);


                foreach ($goods_label as $v){

                    if($v['time']){
                        if((time() + $v['time']*60) > strtotime(date('Y-m-d'.$market->send_endtime))){
                            $this->error('商品预制时间超过送达时间,不可购买!');
                        }
                    }

                    if((int)$v['id']!==1) {

                        if ((int)$v['id']== 2 || (int)$v['id']== 3) {
                            if ($v['discount']) {  //限量折扣


                                if ($value['goods_num'] >= $v['quota']) {

                                    if ($value['goods_num'] == $v['quota']) {

                                        $item_discount_fee = bcmul($v['discount'], bcmul($value['price'], $value['goods_num'], 2), 2); //折扣后的价格

                                        $discount_price[$value['goods_id']] = $item_discount_fee;
                                    } else {
                                        //计算出超出价格
                                        $alery_price = bcmul($value['price'], bcsub($value['goods_num'], $v['quota']), 2);
                                        //未超出价格
                                        $nob_price = bcmul($v['discount'], bcmul($value['price'], $v['quota'], 2), 2);

                                        $discount_price[$value['goods_id']] = bcadd($alery_price, $nob_price, 2);
                                    }


                                } else {
                                    $item_discount_fee = bcmul($v['discount'], bcmul($value['price'], $value['goods_num'], 2), 2); //折扣后的价格

                                    $discount_price[$value['goods_id']] = $item_discount_fee;
                                }

                                //折扣价格
                                $discounted_price += bcsub($pay_price[$value['goods_id']], $discount_price[$value['goods_id']], 2);
                                $pay_price[$value['goods_id']] = $discount_price[$value['goods_id']];


                                $value['dis_price'] = $discounted_price; //定义折扣价格
                                $value['dis_num'] = $v['quota'];       //定义折扣个数


                            } else {
                                if ($value['goods_num'] > $v['quota']) {
                                    $this->error('超出商品限购,订单异常!');
                                }
                            }

                        }
                    }


                }

            }



            if($coupon){
                foreach ($coupon as $item){
                    $coupons_log_num = ShopUserCouponsLog::where([
                        'coupons_id' => $item->id,
                        'user_id' => $user['id'],
                        'createtime' => ['between', [$today_start, $today_end]],
                    ])->count();
                    if($coupons_log_num >= $item->use_times){
                        $this->error('优惠券已达当天限制!');
                    }
                    $value['coupons_type'] = $item->source;

                    if($item->source == 1){ //平台券
                        $platform_coupon_id = $item->id;
                        $platform_coupon_amount = $item->amount;
                        $platform_coupon_enough = $item->enough;
                    }else{ //店铺券
                        if($item->coupons_type == 1){ //优惠券类型:1.商品券,2.店铺券
//                            if($title == '限量折扣' || $title == '限购产品'){
//                                $this->error('有折扣或限购时不可使用商品券!');
//                            }
                            if(in_array($value['goods_id'], explode(',', $item->goods_ids)) || $item->goods_ids == '0'){
                                $discount_fee = bcadd($discount_fee, $item->amount, 2);

                                $value['cou_price'] = $discount_fee; //定义指定商品优惠价格
                                $value['cou_id'] = $item->id;       //定义指定商品优惠id

//                                $pay_fee = bcsub($price, $discount_fee, 2);
                                $discount_price[$value['goods_id']] = $item->amount;
                                $pay_price[$value['goods_id']] = bcsub($pay_price[$value['goods_id']], $discount_price[$value['goods_id']], 2);

                            }
                        } else { //店铺券
                            if($platform_coupon_id){
                                $this->error('平台券和店铺通用券不能同时使用');
                            }
                            $shop_coupon_id = $item->id;
                            $shop_coupon_amount = $item->amount;
                            $shop_coupon_enough = $item->enough;
                        }
                    }
                }
            }

        }


//        var_dump($discounted_price.'折扣价格');
//        var_dump($pay_fee.'支付价格');
//        var_dump($price.'计算价格');
//        var_dump($discount_fee.'优惠价格');





        if($platform_coupon_id==0 && $shop_coupon_id==0){
            $pay_fee = bcsub($price, $discount_fee, 2);
        }
        if($platform_coupon_id){  //平台优惠券优惠价格
            if($price >= $platform_coupon_enough){
                $discount_fee = bcadd($discount_fee, $platform_coupon_amount, 2);
                if($pay_fee){
                    $pay_fee = bcsub($pay_fee, $discount_fee, 2);
                } else { //没有折扣 没有券
                    $pay_fee = bcsub($price, $discount_fee, 2);
                }
            }
        }
        if($shop_coupon_id){  //店铺优惠券优惠价格
            if($price >= $shop_coupon_enough){
                $discount_fee = bcadd($discount_fee, $shop_coupon_amount, 2);
                if($pay_fee){
                    $pay_fee = bcsub($pay_fee, $discount_fee, 2);
                } else {  //没有折扣 没有券
                    $pay_fee = bcsub($price, $discount_fee, 2);
                }
            }
        }

//
//        var_dump($pay_fee);
//        var_dump($discounted_price);
            //减去折扣价格
        $pay_fee = bcsub($pay_fee,$discounted_price,2);

//        var_dump($pay_fee.'未加过打包价格');
        //添加打包费
        $configs = ShopConfigs::where(['name' => 'order'])->find();
        $configs_value = json_decode($configs['value'], true);
        $pay_fee = bcadd($pay_fee,$configs_value['packing_charge'],2);

//        var_dump($pay_fee.'加过打包价格');
        $order_data = [
            'shop_id'       =>(int)$shop_id,
            'shoper_id'     => \app\common\model\Shop::where(['id' => $shop_id])->value('shoper_id'),
            'order_sn'      => ShopOrder::getSn($user['id']),
            'user_id'       => $user['id'],
            'cell_id'       => $cell_id,
            'market_id'     => $market_id,
            'phone'         => $cell->take_phone,
            'consignee'     => $cell->take_name,
            'address'       => $cell->name,
            'remark'        => $remark,
            'dispatch_amount'=>0,  //没有运费
            'packing_charge'=> $configs_value['packing_charge'], //打包费
            'goods_amount'  => $goods_amount,                          //商品总价
            'total_amount'  => $price,                          //订单总金额
            'total_fee'     => $pay_fee,                        //支付金额
            'discount_fee'  => $discounted_price,               //折扣总金额
            'coupon_fee'    => $discount_fee,                      //优惠券价格
            'all_coupon_fee'=> bcadd($discount_fee,$discounted_price,2),//优惠券折扣券总金额
            'pay_fee'       => $pay_fee,                        //实际支付价格
            'coupons_id'    => $coupons_id,                     //优惠券id
            'platform'      => $platform,
            'expect_send_time'=> strtotime($send_endtime),
        ];

        if($expect_send_time){
            $order_data['expect_send_time'] = strtotime($expect_send_time);
            $order_data['is_expect'] = 1;
        }

        ShopOrder::startTrans();
        try {
//            var_dump($order_data);
//            exit();
            $order = ShopOrder::create($order_data);

            if($order){
//                var_dump($goodsList);
//                exit();

                foreach ($goodsList as $v){

                    $order_item_data = [
                        'shop_id'               => $shop_id,
                        'order_id'              => $order->id,
                        'user_id'               => $user['id'],
                        'goods_id'              => $v['goods_id'],
                        'coupons_type'          => isset($v['coupons_type'])?$v['coupons_type']:0,
                        'coupons_id'            => $v['cou_id'],
                        'goods_title'           => $v['goods_name'],
                        'goods_image'           => $v['image'],
                        'goods_original_price'  => $v['original_price'],
                        'goods_price'           => $v['price'],
                        'discount_fee'          => $v['dis_price'],//折扣金额
                        'coupons_fee'           => $v['cou_price'],
                        'goods_num'             => $v['goods_num'],
                        'pay_price'             => $pay_price[$v['goods_id']],

                    ];
//var_dump($order_item_data);
                    ShopOrderItem::create($order_item_data);

                }
//                exit();

                //用户使用优惠券记录
                if($ShopUserCouponsData){
                    $ShopUserCouponsData = json_decode(json_encode($ShopUserCoupons),true);
                    foreach ($ShopUserCouponsData as $SUCDvolue) {
                        $coupon_id = $SUCDvolue['coupons_id'];

                        $SUCDvolue['use_order_id'] = $order->id;
                        $SUCDvolue['used_num'] = 1;
                        $SUCDvolue['usetime'] = time();
                        unset($SUCDvolue['coupons_id']);
                        ShopUserCoupons::update($SUCDvolue, ['coupons_id' => $coupon_id]);
                        $logData = [
                            'coupon_type'   => $SUCDvolue['coupon_type'],
                            'shop_id'       => $shop_id,
                            'user_id'       => $user['id'],
                            'coupons_id'    => $coupon_id,
                            'order_id'      => $order->id,
                        ];
                        ShopUserCouponsLog::create($logData);
                    }
                }

                if($num_goods_id){
                    $numGoodsInfo = Goods::get($num_goods_id);
                    $num_order_item_data = [
                        'shop_id'               => $shop_id,
                        'order_id'              => $order->id,
                        'user_id'               => $user['id'],
                        'goods_id'              => $numGoodsInfo->id,
                        'goods_title'           => $numGoodsInfo->title,
                        'goods_image'           => $numGoodsInfo->image,
                        'goods_original_price'  => $numGoodsInfo->original_price,
                        'goods_price'           => $numGoodsInfo->price,
                        'discount_fee'          => $numGoodsInfo->price,
                        'goods_num'             => 1,
                        'pay_price'             => 0,
                    ];
                    ShopOrderItem::create($num_order_item_data);

                    if($ShopUserCouponsNum){
                        if($ShopUserCouponsNum->use_num == 1){
                            $ShopUserCouponsNum->status = 2;
                        }
                        $ShopUserCouponsNum->use_num -= 1;
                        $ShopUserCouponsNum->used_num += 1;
                        $ShopUserCouponsNum->usetime = time();
                        $ShopUserCouponsNum->save();
                    }

                    $shop_user_coupons_num = [
                        'user_id'           => $user['id'],
                        'user_coupons_id'   => $nunCouponsInfo->id,
                        'use_order_id'      => $order->id,
                        'usetime'           => time(),
                    ];
                    ShopUserCouponsNum::create($shop_user_coupons_num);
                }
                ShopCart::delUserShopCart(['user_id' => $user['id'], 'shop_id' => $shop_id]);
            }
            ShopOrder::commit();
        } catch (Exception $e){
            $this->error($e->getMessage());
            ShopOrder::rollback();
        }

        $this->success('下单成功!', $order);
    }

    /**
     * 计算退款金额接口
     */
    public function countRefundOrder()
    {

        $order_id = $this->request->post('order_id');
        $order_item_ids = $this->request->post('refund_data/a');

        if(empty($order_item_ids)){

            $order_item_ids = null;
        }else{
            $order_item_ids = json_encode($order_item_ids);
        }

        $can_refund_price = 0; //可退金额
        $refund_goods_num = 0;
        $NoCouPrice = 0;//重新计算使用了平台券或者店铺通用券的应付金额
        $goods_all_price  = 0; //商品总价格
        $goods_coupons_fee= 0; //店铺指定商品优惠券
        $coupons_fee  = 0; //平台 or 店铺 优惠券减免 金额
        $discount_fee = 0; //商品折扣价

        $all_refund_goodscount = 0;
            //查询订单详情
            $order = \app\common\model\ShopOrder::where(['id'=>$order_id])->find()->toArray();

            if($order){

                $order['goodsCount'] = ShopOrderItem::where(['order_id' =>$order_id])->count();
                $order['all_goods_num'] = ShopOrderItem::where(['order_id' =>$order_id])->sum('goods_num');
                $order['goods_item'] = ShopOrderItem::alias('soi')
                        ->field("soi.*,g.is_refund")
                        ->join("goods g", "g.id = soi.goods_id", "LEFT")
                        ->where(['soi.order_id' => $order_id])
                        ->select();






                 if(!empty($order['goods_item'])) {

                   if (!empty($order_item_ids)) { //做退款减法运算部分退款  //不为空 退款计算

                       $order_item_ids = json_decode($order_item_ids, true);
                       //查询退款商品个数
                       foreach ($order_item_ids as $k => $v) {
                           $refund_goods_num += $v['count'];
                       }
                       if ((int)$order['all_goods_num'] == $refund_goods_num) {  //全部退款



                           $can_refund_price = $order['pay_fee'];
                           $order['can_refund_price'] = $can_refund_price;






                       }else{   //个别退款计算
$ij=0;

                           foreach ($order['goods_item'] as $k => &$v) {
                               foreach ($order_item_ids as $i => $h) {
                                   if ($h['id'] == $v['id']) {
                                       $v['refund_goods_num'] = $v['goods_num'] - $h['count']; //退钱数量
                                       if ($v['refund_goods_num'] == 0) {   //0全退商品 //部分退款  //未退商品
                                           $v['refund_goods_num'] = $v['goods_num'];
                                       } elseif($v['refund_goods_num']>0){
                                           $v['refund_goods_num'] = $v['refund_goods_num']; //没有退款商品
                                       }else{
                                           $v['refund_goods_num'] == 0;
                                       }

                                   //计算退款
                                   if ($v['refund_goods_num'] !== 0) {
                                       //1.判断是否使用指定商品优惠券
                                       if ($v['coupons_id'] !== 0) {  //当前商品使用指定优惠券
                                           //查询优惠券优惠金额
                                           $Specify_coupon = ShopCoupons::where('id', $v['coupons_id'])->find();
                                           if ($v['goods_num'] == $h['count']) {
                                               $can_refund_price += $v['pay_price'];
                                           } else {
                                               $can_refund_price += bcmul(bcdiv(bcsub(bcmul($v['goods_num'], $v['goods_price'], 2), $Specify_coupon['amount'], 2), $v['goods_num'], 2), $v['refund_goods_num'], 2);
                                           }


                                       } else {  //普通商品支付
//2.平台优惠券 || 店铺优惠券
//查询订单使用优惠券
//(1)使用一张满10减2元的通用满减券,买A+B+C
//需要支付(10+8+5)-2 =21元,
//仅退A时  退21/23*10=9.13
//仅退B时  退21/23*8=7.3
//仅退C时  退21/23*5=4.56
//退A+B时   退21/23*(10+8)=16.43   以此类推
//按照比例退款
                                           foreach ($order['goods_item'] as $n) {
                                               if ($n['coupons_id'] == 0) {
                                                   $NoCouPrice += bcmul($n['goods_num'], $n['goods_price'], 2);
                                               }
                                           }

                                           //查询平台或者店铺通用优惠券
                                           $common_coupon = ShopCoupons::where('id', 'in', explode(',', $order['coupons_id']))->where('coupons_type', 'neq', 1)->find();
                                           //判断是否有折扣商品
                                           if ($v['discount_fee'] !== 0.00) {

                                               $can_refund_price += bcsub(bcmul(bcmul(bcdiv(bcsub($NoCouPrice, $common_coupon['amount'], 2), $NoCouPrice, 2), $v['goods_price'], 2), $v['refund_goods_num'], 2), $v['discount_fee'], 2);

                                               $ij++;
                                           } else {
                                               var_dump(11111);
                                               $can_refund_price += bcmul(bcmul(bcdiv(bcsub($NoCouPrice, $common_coupon['amount'], 2), $NoCouPrice, 2), $v['goods_price'], 2), $v['refund_goods_num'], 2);
                                           }
                                           $NoCouPrice = 0;
//

                                       }


                                   }
                               }
                                   var_dump($can_refund_price);
                                   $order['can_refund_price'] = $can_refund_price;

                                }
                             }
///////////////////////////////////




///////////////////////////////////////////
                      }


                    }

                  }else{
                       $this->error('退款商品不能为空');
                  }




                }



                $this->success('获取成功',$order);
            }





    /**
     * 订单退款
     */
    public function refundOrder()
    {
        $order_id = $this->request->post("order_id");
        $order_item_ids = $this->request->post("order_item_ids");
        $refund_data = $this->request->post('refund_data/a');
        $refund_reason_id = $this->request->post("refund_reason_id"); //退款原因
        $refund_images = $this->request->post("images"); //图片
        $remark = $this->request->post("remark"); //退款备注
        if(!$order_id){
            $this->error('参数错误!');
        }
        if($order_item_ids){
            $order_item_ids = explode(',', $order_item_ids);
        }

        $result = ShopOrder::refundOrder($order_id, $order_item_ids,$refund_data,$refund_reason_id,$refund_images, $remark);
        if(!$result){
            $this->error('失败!');
        }
        if($result['code'] == 0){
            $this->error($result['msg']);
        }
        $this->success('成功!');
    }

    /**
     * 查询退款原因
     */
    public function getRefundReason()
    {
        if(request()->Ispost()){
           $res = Reason::where('status',1)->select();
           $this->success('获取成功',$res);
        }
    }

    public function doCancel()
    {
        if(request()->isPost()) {
            $order_id = $this->request->post('order_id');
            $type = 'user';
            $userInfo = $this->auth->getUserinfo();
            $order = \addons\shopro\model\Order::with('item')->where('user_id', $userInfo['id'])->where('id', $order_id)->nopay()->find();

            if (!$order) {
                new \addons\shopro\exception\Exception('订单不存在或已取消');
            }
            $user = User::info();
            $order = Db::transaction(function () use ($order, $user, $type) {
                $data = ['order' => $order];
                \think\Hook::listen('order_cancel_before', $data);

                $order->status = \addons\shopro\model\Order::STATUS_CANCEL;        // 取消订单
                $order->ext = json_encode($order->setExt($order, ['cancel_time' => time()]));      // 取消时间
                $order->save();

                OrderAction::operAdd($order, null, $user, $type, ($type == 'user' ? '用户' : '管理员') . '取消订单');

                // 订单取消,退回库存,退回优惠券积分,等
                $data = ['order' => $order];
                \think\Hook::listen('order_cancel_after', $data);

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

        }

    }




    /**
     * 订单评价
     *
     */
    public function commentOrder()
    {
        $order_id = $this->request->post("order_id");
        $level = $this->request->post("level", 5);
        $goods_level = $this->request->post("goods_level", 5);
        $delivery_level = $this->request->post("delivery_level", 5);
        $content = $this->request->post("content");
        $images = $this->request->post("images");
        if(!$order_id || !$level || !$goods_level || !$delivery_level){
            $this->error('参数错误!');
        }
        $userInfo = $this->auth->getUserinfo();
        $orderInfo = ShopOrder::getUserOrderOne($order_id);
        if(!$orderInfo){
            $this->error("订单参数异常!");
        }
        if($orderInfo->status != 2){
            $this->error("该订单未完成,不可评价!");
        }
        if($orderInfo->comment_status == 1){
            $this->error("该订单已评价过!");
        }
        $orderItem = ShopOrderItem::getOrderItem($order_id);
        if(!$orderItem){
            $this->error("订单详情参数异常!");
        }
        $data = [];
        $itemData = [];
        foreach ($orderItem as $value){
            if($value->comment_status == 0){
                $itemData[] = [
                    'id'            => $value->id,
                    'comment_status'=> 1,
                ];
                $data[] = [
                    'shop_id'       => $value->shop_id,
                    'goods_id'      => $value->goods_id,
                    'order_id'      => $order_id,
                    'order_item_id' => $value->id,
                    'user_id'       => $userInfo['id'],
                    'level'         => $level,
                    'goods_level'   => $goods_level,
                    'delivery_level'=> $delivery_level,
                    'content'       => $content,
                    'images'        => $images,
                ];
            }
        }
        $GoodsComment = new GoodsComment();
        $res = $GoodsComment->saveAll($data);
        if($res){
            ShopOrder::update(['comment_status' => 1], ['id' => $order_id]);
            $ShopOrderItem = new ShopOrderItem();
            $ShopOrderItem->saveAll($itemData);
        }

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

 

posted @ 2023-11-06 11:55  blog_zss小帅-博客猿  阅读(7)  评论(0编辑  收藏  举报