<?php

namespace App\Http\Controllers\Admin;

use App\Events\WithdrawalsCompleteEvent;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\PartnerWallet;
use App\Models\PartnerWithdrawal;
use App\Validators\WithdrawalsValidator;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WithdrawalsController extends Controller
{
    use ResponseJson;
    private WithdrawalsValidator $validator;
    public function __construct(WithdrawalsValidator $offlineOrderValidator)
    {
        $this->validator = $offlineOrderValidator;
    }

    public function index(Request $request)
    {
        $status = $request->get('status',null);
        $keywords = $request->get('keywords',null);
        $list = PartnerWithdrawal::with(['user:id,name,mobile','commissions.main_order:id,name'])
            ->when($status !== null,function($query) use ($status) {
                $query->where('status',$status);
            })
            ->when($keywords !== null,function($query) use ($keywords) {
                $query->whereHas('user',function ($query) use ($keywords) {
                    $query->where('name','like',"%".$keywords."%")->orWhere('mobile','like','%'.$keywords.'%');
                });
            })
            ->orderByDesc('id')
            ->paginate();

        foreach ($list as $withdrawal){
            if ($withdrawal->user) {
                $withdrawal->user->makeVisible('mobile');
            }
        }

        return $this->success('ok',$list);
    }


    public function withdrawalsAct(Request $request,$id)
    {
        try {
            //数据验证
            $data = $request->all();
            $this->validator->scene('act')->validate($data);

            DB::beginTransaction();
            //根据操作变更数据结构
            switch ($data['status']){
                case 1:
                    $data = $request->only(['status','pic']);
//                    $data['check_time'] = date('Y-m-d H:i:s');
                    break;
                case 2:
                    $data = $request->only(['status']);
                    $data['completed_at'] = date('Y-m-d H:i:s');
                    break;
                case 3:
                    $data = $request->only(['status','reason']);
                    break;
            }

            //获取提现数据
            $withdraw = PartnerWithdrawal::with('commissions')->whereIn('status',[0,1])->findOrFail($id);

            //更新用户佣金记录提现状态
            if($data['status'] == 1){
                //通过
                $withdraw->commissions()->update(['status' => 2]);
            }elseif ($data['status'] == 2){
                //通过
                $withdraw->commissions()->update(['status' => 5]);
                //打款金额设为申请金额
                $data['send_amount'] = $withdraw->amount;

            }elseif ($data['status'] == 3 || $data['status'] == 4){
                //拒绝
                $withdraw->commissions()->update(['status' => 4]);

            }
            // 更新用户提现记录
            $withdraw->update($data);



            if ($withdraw->send_amount > $withdraw->amount)throw new \Exception('超出可提现金额');

            //获取并更新用户余额
            $wallet = PartnerWallet::query()
                ->where('user_id',$withdraw->user_id)
                ->first();

            //获取实际打款金额 和 申请金额 差值
            $amount = bcsub($withdraw->amount,$withdraw->send_amount,2);
            if($data['status'] == 3 || $data['status'] == 4){
                //提现中扣除申请金额 钱包增加差值
                $wallet->withdrawn_amount = bcsub($wallet->withdrawn_amount,$withdraw->amount,2);
                $wallet->balance = bcadd($wallet->balance,$amount,2);
            }
//            else{
//                //提现中扣除申请金额 钱包增加差值
//                $wallet->withdrawn_amount = bcadd($wallet->withdrawn_amount,$withdraw->amount,2);
//                $wallet->balance = bcsub($wallet->balance,$amount,2);
//            }

            $wallet->save();

            DB::commit();
            //发放佣金通知
            WithdrawalsCompleteEvent::dispatch($withdraw);

            return $this->success('ok');

        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'提现记录不存在或当前状态不支持审核');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->jsonResponse(1,$e->getMessage());
        }
    }


    public function countWithdrawals()
    {
        $data['today'] = PartnerWithdrawal::query()->whereDate('completed_at',today())->sum('send_amount');

        $data['total'] = PartnerWithdrawal::query()->where('status',2)->sum('send_amount');

        return $this->success('ok',$data);
    }

    public function arrayWithdrawals(Request $request)
    {
        $start = $request->get('start_time',date('Y-m-d 00:00:00'));
        $end = $request->get('end_time',date('Y-m-d 23:59:59'));

        $withdrawals_arr = [];

        PartnerWithdrawal::query()
            ->whereBetween('completed_at',[$start,$end])
            ->groupByRaw(DB::raw("date(completed_at)"))
            ->select(DB::raw("date(completed_at) as date,SUM(send_amount) as amounts"))
            ->get()
            ->map(function ($withdrawal)use (&$withdrawals_arr){
                $withdrawals_arr[$withdrawal->date] = $withdrawal->amounts;
            });

        $data['data'] = array_keys($withdrawals_arr);
        $data['value'] = array_values($withdrawals_arr);

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

    }
}
