<?php


namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\PaymentOrderService;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use App\Models\PaymentOrder as PaymentOrderModel;
use App\Models\Wallet;
use App\Models\Recharge;
use App\Models\Withdraw;
use App\Services\BalanceLogService;

class PaymentOrder extends Controller
{

    //统计后台待处理订单总数（在线平台人数见 GET /admin/online/platformCount）
    public function unProcessed()
    {
        //USDT充值订单
        $data['usdtRecharge'] = (int)Recharge::where('status', 0)->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-1 day')))->count();
        //人工充值订单
        $data['rgRecharge'] = (int)PaymentOrderModel::whereIn('status', [0,1,5])->where('type', 3)->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-1 day')))->count();
        //人民币充值订单
        $data['rmbRecharge'] = (int)PaymentOrderModel::whereIn('status', [0,1])->where('type', 1)->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-1 day')))->count();
        
        //USDT提现订单
        $data['usdtWithdraw'] = (int)Withdraw::where('status', 0)->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-1 day')))->count();
        //人工提现订单
        $data['rgWithdraw'] = (int)PaymentOrderModel::where('status', 0)->where('type', 4)->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-1 day')))->count();
        //人民币提现订单
        $data['rmbWithdraw'] = (int)PaymentOrderModel::where('status', 0)->where('type', 2)->where('created_at', '>', date('Y-m-d H:i:s', strtotime('-1 day')))->count();
        return $this->success($data);
    }

    //人工充值，配置充值信息
    public function setPayData()
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'ids' => ['required', 'array', 'min:1'],
                'ids.*' => ['required', 'integer', 'min:1'],
                'payment_type' => ['required', 'integer'],
                'pay_data' => ['required', 'string'],
            ]);

            // $count = PaymentOrderModel::whereIn('id', $params['ids'])->where('payment_type', $params['payment_type'])->where('status', 0)->count();
            // if ($count != count($params['ids'])) throw new Exception('数据匹配异常，请刷新页面重试！', HttpStatus::CUSTOM_ERROR);
            
            PaymentOrderModel::whereIn('id', $params['ids'])
                ->where('payment_type', $params['payment_type'])
                ->where('status', 0)
                ->update(['pay_data' => $params['pay_data'], 'status' => 4, 'is_send' => 0]);

            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success();
    }

    //人工充值审核
    public function manualAudit()
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'id' => ['required', 'integer', 'min:1'],
                'status' => ['required', 'integer', 'in:2,3'],
                'remark' => ['nullable', 'string'],
            ]);
            $remark = $params['remark'] ?? '';
            $info = PaymentOrderModel::find($params['id']);
            if (!$info) throw new Exception('数据不存在', HttpStatus::CUSTOM_ERROR);
            if ($params['status'] == 2 && $info->status != 5) throw new Exception('用户未提交充值凭证', HttpStatus::CUSTOM_ERROR);
            if ($params['status'] == 3 && !in_array($info->status, [0,1,4,5])) throw new Exception('订单已完成，不可驳回', HttpStatus::CUSTOM_ERROR);
            if ($params['status'] == 3) {
                //驳回
                if (empty($remark)) {
                    throw new Exception('请填写原因', HttpStatus::CUSTOM_ERROR);
                }
                $info->status = $params['status'];
                $info->remark = $remark;
                $info->save();
            } else {
                //充值成功
                $info->status = $params['status'];
                $info->remark = $remark;
                $info->state = 1;
                $info->save();

                $memberId = $info->member_id;
                $amount = $info->amount;
                $changeType = '人工充值';
                $wallet = Wallet::where('member_id', $memberId)->first();
                if (!$wallet) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
                $availableBalance = bcadd($wallet->available_balance, $amount, 10);
                BalanceLogService::addLog($memberId, $amount, $wallet->available_balance, $availableBalance, $changeType, null, $remark);
                $wallet->available_balance = $availableBalance;
                $wallet->save();
            }
            
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success();
    }

    //提现审核
    public function audit()
    {
        DB::beginTransaction();
        try {
            
            $validate = [
                'ids' => ['required', 'array', 'min:1', 'max:20'],
                'ids.*' => ['required', 'integer', 'min:1'],
                'status' => ['required', 'integer', 'in:1,3'],
                'is_rgtx' => ['nullable', 'integer', 'in:0,1'],
            ];
            $status = request()->input('status', null);
            if ($status != 1) {
                $validate['remark'] = ['required', 'string', 'min:1', 'max:120'];
            }
            $params = request()->validate($validate);
            $remark = request()->input('remark', '');

            $count = 0;
            foreach ($params['ids'] as $id) {
                if ($params['status'] == 1) {
                    if (!empty($params['is_rgtx'])) {
                        $order = PaymentOrderModel::where('id', $id)
                            ->where('type', 4)
                            ->where('status', PaymentOrderService::STATUS_STAY)
                            ->first();
                        if (!$order) throw new Exception("订单不存在_{$id}", HttpStatus::CUSTOM_ERROR);
                        $order->status = PaymentOrderService::STATUS_SUCCESS;
                        $order->save();
                    } else {
                        $ret = PaymentOrderService::createPayout($id);
                        if ($ret['code'] !== 0) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
                    }
                } else {
                    $ret = PaymentOrderService::withdrawalFailed($id, $remark);
                    if ($ret['code'] !== 0) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
                }
                $count++;
            }
            if ($count < 1) throw new Exception('操作失败', HttpStatus::CUSTOM_ERROR);
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success();
    }


    /**
     * @apiParam {int} [page]
     * @apiParam {int} [limit]
     * @apiParam {int=0,1,2} type 类型 0全部 1=代收，2=代付
     * @apiParam {String} order_no 订单号
     * @apiPaaram {String} member_id 会员ID
     * @apiParam {int=0,1,2,3} [status] 状态：0待处理 1处理中 2成功 3失败
     *
     */
    public function index()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'order_no' => ['nullable', 'string'],
                'status' => ['nullable', 'integer'],
                'member_id' => ['nullable', 'integer'],
                'first_name' => ['nullable'],
                'payment_type' => ['nullable', 'integer'],
                'channel' => ['nullable', 'string'],
            ]);

            $params['type'] = 1;
            $result = PaymentOrderService::paginate($params);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success($result);
    }

    /**
     * @description: 查询订单的支付情况
     * @return {*}
     */
    public function check()
    {
        $id = request()->input('id');
        if (empty($id)) {
            return $this->error(HttpStatus::CUSTOM_ERROR, '参数错误');

        }
        try {
            $result = PaymentOrderService::singlePayOrder($id);
            $this->success([], $result['msg'] ?? '操作成功');
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        return $this->success([], $result['msg'] ?? '操作成功');
    }

    //设置提现订单是否加锁
    public function setIsLocked()
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'ids' => ['required', 'array', 'min:1', 'max:20'],
                'ids.*' => ['required', 'integer', 'min:1'],
                'is_locked' => ['required', 'integer', 'in:1,0'],
            ]);
            PaymentOrderModel::whereIn('id',$params['ids'])->whereIn('type',[2,4])->update(['is_locked' => $params['is_locked']]);
            
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getCode(), $e->getMessage());
        }
        return $this->success();
    }
}
