<?php

namespace App\Http\Controllers;

use App\Events\AuthRefundTip;
use App\Models\DwbsUser;
use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderRefund;
use App\Models\OrderDetail;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class RefundController extends Controller
{
    //获取退款订单原始信息
    public function getOriginOrderInfo(Request $request)
    {
        $order_no=$request->input('order_no');
        $data=Order::with(['address','cancel'=>function($query){$query->where('using',1);},'store:id,name,img,phone']);
        $order=$data->where('order_no',$order_no)->first()->toArray();
        if(empty($order)){
            return $this->error('450001','订单不存在');
        }
        $goods_ids=OrderDetail::where('order_no',$order['order_no'])->groupBy('goods_id')->pluck('goods_id');
        $goods=[];
        foreach($goods_ids as $key=>$val){
            $goods[$val]=Goods::select('id','name','img','main_attr')->where('id',$val)->first()->toArray();
            $order_details=OrderDetail::where('order_no',$order['order_no'])->where('goods_id',$val)->get()->toArray();
            if(count($order_details)>0){
                $sku=[];
                foreach($order_details as $k=>$v){
                    $sku[$v['sku_id']]=$v;
                }
                $goods[$val]['sku']=$sku;
                $goods[$val]['price']=$order_details[0]['price'];
            }
        }
        $order['goods']=$goods;
        $refund_nos=OrderRefund::where('order_no',$order_no)->whereIn('status',[0,1,3])->pluck('refund_no');
        $refund_goods_ids=OrderDetail::whereIn('order_no',$refund_nos)->groupBy('goods_id')->pluck('goods_id');
        $refunds=[];
        foreach($refund_goods_ids as $key=>$val){
            $refunds[$val]=Goods::select('id','name','img','main_attr')->where('id',$val)->first()->toArray();
            $refunds_details=OrderDetail::select('goods_id','sku_id','type','size',DB::raw('sum(num) as num'))
            ->whereIn('order_no',$refund_nos)->where('goods_id',$val)->groupBy('sku_id')->get()->toArray();
            if(count($refunds_details)>0){
                $sku=[];
                foreach($refunds_details as $k=>$v){
                    $sku[$v['sku_id']]=$v;
                }
                $refunds[$val]['sku']=$sku;
            }
        }
        $order['refunds']=$refunds;
        $products=[];
        foreach($goods as $key=>$val){
            $products[$key]= $goods[$key];
            $sku=[];
            foreach($val['sku'] as $k=>$v){
                if(empty($refunds[$key]['sku'][$k])){
                    unset($products[$key]['sku']);
                    $sku[$k]= $goods[$key]['sku'][$k];
                }else{
                    if($goods[$key]['sku'][$k]['num'] > $refunds[$key]['sku'][$k]['num']){
                        unset($products[$key]['sku']);
                        $sku[$k] = $goods[$key]['sku'][$k];
                        $sku[$k]['num']=$goods[$key]['sku'][$k]['num'] - $refunds[$key]['sku'][$k]['num'];
                    }else{
                        unset($products[$key]['sku']);
                    }
                }
            }
            $products[$key]['sku']= $sku;
            if(empty($products[$key]['sku'])){
                unset($products[$key]);
            }
        }
        $order['products']=$products;
        return $this->success($order);
    }
    //提交退货订单
    public function submitRefundOrder(Request $request)
    {
        $sku = $request->input('sku');
        $reason = $request->input('reason');
        $reason_all = $request->input('reason_all');
        $img = $request->input('img');
        $origin_order_no=$request->input('origin_order_no');
        $origin_order=Order::where('order_no',$origin_order_no)->first();
        if($origin_order->is_refund==1){
            return $this->error('450001','该订单存在正在审核中的退货订单');
        }
        if($origin_order->is_refund==3){
            return $this->error('450001','该订单已全部退货');
        }
        $refund_no=Order::order_no('th');
        $account = $total = 0;
        $list = $sku_ids = [];
        foreach($sku as $key=>$val){
            if($val[1] > 0){
                $order_detail=OrderDetail::with(['goods'])->where('id',$val[0])->first();
                if($order_detail->num < $val[1]){
                    $num = $order_detail->num;
                }else{
                    $num = $val[1];
                }
                $list[$key]['num']=$num;
                $list[$key]['price']=$order_detail->price;
                $list[$key]['account']=$order_detail->price * $num;
                $list[$key]['order_no']=$refund_no;
                $list[$key]['goods_id']=$order_detail->goods_id;
                $list[$key]['sku_id']=$order_detail->sku_id;
                $list[$key]['size']=$order_detail->size;
                $list[$key]['type']=$order_detail->type;
                $list[$key]['style']=2;
                $list[$key]['created_at']=date("Y-m-d H:i:s");
                $list[$key]['updated_at']=date("Y-m-d H:i:s");
                $total += $num;
                $account += $order_detail->price * $num;
            }
        }
        $data=[
            'refund_no'=>$refund_no,
            'order_no'=>$origin_order_no,
            'store_id'=>$origin_order->store_id,
            'user_id'=>$origin_order->user_id,
            'reason'=>$reason,
            'reason_all'=>$reason_all,
            'total'=>$total,
            'account'=>$account,
            'img'=>json_encode($img),
            'status'=>0,
            'op_name'=>Auth::user()->nickname,
            'op_type'=>1,
            'remark'=>null,
        ];
        try{
            DB::transaction(function ()use($list,$data,$origin_order_no){
                OrderDetail::insert($list);
                OrderRefund::create($data);
                Order::where('order_no',$origin_order_no)->update(['is_refund'=>1]);
            },5);
            //申请退货提醒
            $store=Store::where('id',$origin_order->store_id)->first();
            $user=DwbsUser::withTrashed()->where('id',$store->user_id)->first();
            if($user->openid){
                $data['openid']=$user->openid;
                $data['data']=[
                    'first' => '您的客户提交了新的退货信息',
                    'keyword1' => $origin_order->order_no,
                    'keyword2' => '客户退货',
                ];
                event(new AuthRefundTip($data));
            }
            return $this->success($refund_no);
        }catch(\Exception $e){
            return $this->error('450001',$e->getMessage());
        }
    }
    //取消退货审核
    public function cancelRefundOrder(Request $request){
        $refund_id=$request->input('refund_id');
        $refund=OrderRefund::where('id',$refund_id)->first();
        if(empty($refund)){
            return $this->error('450001','退货单不存在');
        }
        if($refund->status==1){
            return $this->error('450001','已成功退货,不能取消');
        }
        if($refund->status==2){
            return $this->error('450001','退货申请已被驳回,不能取消');
        }

        try{
            DB::transaction(function()use($refund){
                OrderRefund::where('id',$refund->id)->delete();

                $auth_count=OrderRefund::where('order_no',$refund->order_no)->where('status',0)->count();
                if($auth_count>=1){
                    Order::where('order_no',$refund->order_no)->update([
                        'is_refund'=>1
                    ]);
                }else{
                    $count=OrderRefund::where('order_no',$refund->order_no)->where('status',1)->count();
                    if($count>=1){
                        Order::where('order_no',$refund->order_no)->update([
                            'is_refund'=>2
                        ]);
                    }else{
                        Order::where('order_no',$refund->order_no)->update([
                            'is_refund'=>0
                        ]);
                    }
                }
            },5);
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error('450001',$e->getMessage());
        }
    }
        //获取用户端所有退货订单
    public function getAllRefundOrder(Request $request)
    {
        $user_id=Auth::user()->id;
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
        $refund_no=$request->input('refund_no');
        $data=OrderRefund::with('store:id,name,phone')->where('user_id',$user_id);
        if($refund_no){
            $data->where('refund_no','like','%'.$refund_no.'%');
        }
        $total= $data->count();
        $refunds = $data->orderBy('id','desc')->skip($num)->take($page_size)->get();
        foreach($refunds as $key=>$val){
            $goods=[];
            $goods_ids=OrderDetail::where('order_no',$val->refund_no)->groupBy('goods_id')->pluck('goods_id');
            foreach($goods_ids as $k=>$v){
                $goods[$k]=Goods::where('id',$v)->first();
                $goods[$k]->sku=OrderDetail::where('order_no',$val->refund_no)->where('goods_id',$v)->get();
            }
            $refunds[$key]->goods=$goods;
        }
        return $this->success_list($refunds,'成功',$total);
    }
    //获取用户端退货订单详情
    public function getRefundOrderDetail(Request $request)
    {
        $refund_id = $request->input('refund_id');
        //获取订单信息（id）
        $order = OrderRefund::with(['store:id,name,img,phone'])->where('id', $refund_id)->first();
        $goods_ids = OrderDetail::where('order_no', $order->refund_no)->groupBy('goods_id')->pluck('goods_id');
        $goods = [];
        foreach ($goods_ids as $key => $val) {
            $goods[$key] = Goods::where('id', $val)->first();
            $goods[$key]->sku = OrderDetail::where('order_no', $order->refund_no)->where('goods_id', $val)->get();
        }
        $order->goods = $goods;
        return $this->success($order);
    }
    //删除订单
    public function deleteOriginOrder(Request $request){
        $order_no=$request->input('order_no');
        $res=Order::where('order_no',$order_no)->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //上传图片
    public function uploadRefundOrderImg(Request $request){
        $path_url = 'public/refund';
        $path = $request->file('img')->store($path_url);
        if($path){
            $url = env('APP_URL').Storage::url($path);
            return $this->success($url);
        }
        return $this->error();
    }
}
