<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DwbsUser;
use App\Models\DwbsWarea;
use App\Models\Goods;
use App\Models\Store;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class RefundController extends Controller
{
    //获取所有退货订单
    public function getRefundOrder(Request $request)
    {
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $user_search=$request->input('user_search');
        $store_search=$request->input('store_search');
        $refund_no=$request->input('refund_no');
        $order_no=$request->input('order_no');
        $num=$page_size*($page_index-1);
        $status=$request->input('status');
        $admin_id=Auth::user()->id;
        $admin=Admin::where('id',$admin_id)->first();
        if($admin && in_array($admin->role_id,[22,24])){//超级管理员
            $data=OrderRefund::with(['user:id,avatar,nickname,phone','store:id,name,phone,user_id','order:order_no,express_receive_time']);
        }else{
            $warea_ids=DwbsWarea::where('admin_id',$admin_id)->pluck('id');
            $agent_ids=DwbsUser::whereIn('warea_id',$warea_ids)->pluck('id');
            $store_ids=Store::whereIn('user_id',$agent_ids)->pluck('id');
            $data=OrderRefund::withTrashed()->whereIn('store_id',$store_ids)
                ->with(['user:id,avatar,nickname,phone','store:id,name,phone,user_id','order:order_no,express_receive_time']);
        }
        if($status!='all'){
            if($status=='cancel'){
                $data->onlyTrashed();
            }else{
                $data->where('status',$status);
            }
        }else{
            $data->withTrashed();
        }
        if($refund_no){
            $data->where('refund_no','like','%'.$refund_no.'%');
        }
        if($order_no){
            $data->where('order_no','like','%'.$order_no.'%');
        }
        if($user_search){
            $user_ids=User::where('phone','like','%'.$user_search.'%')
                    ->orWhere('nickname','like','%'.$user_search.'%')->pluck('id');
            $data->whereIn('user_id',$user_ids);
        }
        if($store_search){
            $store_ids=Store::where('phone','like','%'.$store_search.'%')
                    ->orWhere('name','like','%'.$store_search.'%')->pluck('id');
            $data->whereIn('store_id',$store_ids);
        }
        $count=$data->count();
        $list=$data->orderBy('id','desc')->skip($num)->take($page_size)->get();

        foreach($list as $key=>$val){
            $store=$val->store;
            $user_id=$store->user_id;
            $warea_id=DwbsUser::withTrashed()->where('id',$user_id)->value('warea_id');
            $warea=DwbsWarea::where('id',$warea_id)->first();
            if($warea){
                $list[$key]->service=$warea->admin_name;
            }else{
                $list[$key]->service=null;
            }
            if (mb_strlen($val->store->phone)>15){
                $list[$key]->store->phone=mb_substr($val->store->phone,0,8).'*****';
            }

        }
        return $this->success_list($list,'成功',$count);
    }
    //同意?退货:驳回
    public function agreeRefund(Request $request)
    {
        $refund_id=$request->input('refund_id');
        $refund=OrderRefund::where('id',$refund_id)->first();
        if(empty($refund)){
            return $this->error('450001','退货单不存在，刷新后重试');
        }
        $order=Order::where('order_no',$refund->order_no)->first();
        if(empty($order) || $order->status < 3){
            return $this->error('450001','该订单未收货，不能进行退货审核');
        }
        $is_agree=$request->input('is_agree');
        try{
            DB::transaction(function()use($request,$refund,$refund_id,$is_agree){
                if($is_agree == 1){
                    OrderRefund::where('id',$refund_id)->update(['status'=>1,'auth_at'=>date("Y-m-d H:i:s")]);
                    $order_refund=OrderRefund::where('id',$refund_id)->first();
                    $refund_total=OrderRefund::where('order_no',$order_refund->order_no)->where('status',1)->sum('total');
                    $order=Order::where('order_no',$order_refund->order_no)->first();
                    $order_total=$order->total;
                    if($refund_total >= $order_total){//全部退货
                        Order::where('order_no',$order_refund->order_no)->update(['is_refund'=>3]);
                    }else{//部分退货
                        Order::where('order_no',$order_refund->order_no)->update(['is_refund'=>2]);
                    }
                    //同意退货通知用户
                    $user=User::where('id',$refund->user_id)->first();
                    if($user->openId){
                        $data['openid']=$user->openId;
                        $data['data']=[
                            'first' => '您的退货订单'.$refund->refund_no.'已审核通过',
                            'keyword1' => $refund->order_no,
                            'keyword2' => '退款金额:'.number_format($refund->account, 2)
                        ];
                        event(new AuthRefundTip($data));
                    }

                    //同意退货通知系统账号
                    $store=Store::where('id',$refund->store_id)->first();
                    $user=DwbsUser::where('id',$store->user_id)->first();
                    if($user->openid){
                        $data['openid']=$user->openid;
                        $data['data']=[
                            'first' => '您的用户【'.$user->nickname.'】的退货订单'.$refund->refund_no.'已由客服审核成功',
                            'keyword1' => $refund->order_no,
                            'keyword2' => '退款金额:'.number_format($refund->account, 2)
                        ];
                        event(new AuthRefundTip($data));
                    }

                }else{
                    $remark=$request->input('remark');
                    Order::where('order_no',$refund->order_no)->update(['is_refund'=>0]);//被驳回
                    OrderRefund::where('id',$refund_id)->update(['status'=>2,'remark'=>$remark,'auth_at'=>date("Y-m-d H:i:s")]);

                    //不同意退货通知用户
                    $user=User::where('id',$refund->user_id)->first();
                    if($user && $user->openId){
                        $data['openid']=$user->openId;
                        $data['data']=[
                            'first' => '您的退货订单'.$refund->refund_no.'审核被驳回',
                            'keyword1' => $refund->order_no,
                            'keyword2' => '退款金额:'.number_format($refund->account,2)
                        ];
                        event(new AuthRefundTip($data));
                    }
                }
            },5);
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error('450001',$e->getMessage());
        }
    }
    //获取退货订单详情
    public function getRefundOrderDetail(Request $request){
        $refund_no=$request->input('refund_no');
        $refund_order = OrderRefund::withTrashed()->with(['store:id,name,img,phone'])->where('refund_no', $refund_no)->first();
        $goods_ids = OrderDetail::where('order_no', $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', $refund_no)->where('goods_id', $val)->get();
        }
        if (mb_strlen($refund_order->store->phone)>15){
            $refund_order->store->phone=mb_substr($refund_order->store->phone,0,8).'*****';
        }
        $refund_order->goods = $goods;
        return $this->success($refund_order);
    }

}
