<?php

namespace App\Http\Controllers\H5;

use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\PartnerAccount;
use App\Models\PartnerCommission;
use App\Validators\AccountsValidator;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class PartnerWalletsController extends Controller
{
    use ResponseJson;

    private AccountsValidator $validator;

    private $user;

    public function __construct(AccountsValidator $validator)
    {
        $this->validator = $validator;
        $user = auth('api')->user();
        if (!$user)return $this->jsonResponse(2,'未登录');
        $this->user = $user;
    }

    //
    public function show()
    {
        try {
            $user = $this->user->with(['wallets','accounts'=>function($accounts){
                $accounts->where('is_default',1);
            }])->findOrFail($this->user->id);

            if (!$user->wallets){
                $wallet = [
                    'balance' => config('app.env') == 'production'?0:10000,
                    'frozen_amount' => 0,
                    'withdrawn_amount' => 0,
                ];
                $user->wallets()->create($wallet);
                $user->wallets = $wallet;
            }
            return $this->success('ok',$user);
        }catch (ModelNotFoundException){
            return $this->jsonResponse(0,'未找到用户信息');
        }

    }

    public function accounts(Request $request) {
        $accounts = PartnerAccount::where('user_id', $this->user->id)->paginate();
        if ($accounts->isEmpty()) {
            return $this->jsonResponse(0, '未找到银行卡信息');
        }
        return $this->success('ok', $accounts);
    }

    public function addAccounts(Request $request)
    {
        try {
            //数据验证
            $data = $request->only(['bank_of_deposit','name','bank_no','mobile','type','id_card','address','mail_address']);
            $this->validator->scene('add')->validate($data);

            //添加
            $data['user_id'] = $this->user->id;
            $accounts = PartnerAccount::query()->create($data);

            return $this->success('ok',$accounts);
        }catch (\Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    public function editAccounts(Request $request,$id)
    {
        try {
            //数据验证
            $data = $request->only(['bank_of_deposit','name','bank_no','mobile','type','id_card','address','mail_address']);
            $this->validator->scene('update')->validate($data);

            //编辑
            $data['user_id'] = $this->user->id;
            $accounts = PartnerAccount::query()->where('user_id',$this->user->id)->findOrFail($id);
            $accounts->update($data);

            return $this->success('ok',$accounts);
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'未找到对应的银行卡');
        }catch (\Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }


    public function getAccountDetail($id){
        $detail = PartnerAccount::find($id);
        return $this->success('ok',$detail);
    }

    public function deleteAccounts($id)
    {
        try {
            //删除
            PartnerAccount::query()->where('user_id',$this->user->id)->findOrFail($id)->delete();

            return $this->success('ok');
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'未找到对应的银行卡');
        }catch (\Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }


    public function setDefault($id)
    {
        try {
            //设为默认
            $accounts = PartnerAccount::query()->where('user_id',$this->user->id)->findOrFail($id);
            $accounts->update(['is_default'=>1]);
            //将其他取消默认
            PartnerAccount::query()
                ->where('user_id',$this->user->id)
                ->where('id','!=',$id)
                ->update(['is_default'=>0]);

            return $this->success('ok',$accounts);
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'未找到对应的银行卡');
        }catch (\Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    public function commissionRecord(Request $request)
    {
        $page_size = $request->get('page_size',15);
        $is_paginate = $request->get('is_paginate',1);
        $commissions = PartnerCommission::query()
            ->where('user_id',$this->user->id);

        if ($is_paginate){
            $commissions = $commissions
//                ->orderByRaw('CASE WHEN status = 5 THEN 2 ELSE 0 END')
                ->whereIn('status',[2,4,5])
                ->orderByDesc('id')
                ->paginate(perPage:$page_size);
        }else{
            $commissions = $commissions->whereIn('status',[1,3])->orderByDesc('id')->get();
        }

        $commissions->each(function ($commission) {
            $commission->reason = $commission->withdrawal->reason ?? '';
            if($commission->type == 1){
                $commission->type = "介绍人收益";
            }else{
                $commission->type = "服务收益";
            }
        });

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