<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BalanceLogService;
use App\Services\PaymentOrderService;
use App\Services\TopUpService;
use App\Services\WalletService;
use App\Services\WithdrawService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;
use App\Models\Withdraw as WithdrawModel;
use App\Models\PaymentOrder;
use App\Models\Config;

class Withdraw extends Controller
{
    function setRmbNote()
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'id' => ['required', 'integer', 'min:1'],
                'admin_note' => ['required', 'string', 'min:1', 'max:120'],
            ]);
            $po = PaymentOrder::where('id', $params['id'])
                ->where('type', 2)->first();
            if (!$po) throw new Exception("记录不存在", HttpStatus::CUSTOM_ERROR);
            $po->admin_note = $params['admin_note'];
            $po->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 rmb()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'type' => ['nullable', 'integer'],
                'member_id' => ['nullable', 'string', 'min:1'],
                'status' => ['nullable', 'integer'],
                'first_name' => ['nullable'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 10);
            $params['type'] = $params['type'] ?? 2;
            
            $query = PaymentOrder::join('users', 'users.member_id', '=', 'payment_orders.member_id')
                        ->select("payment_orders.*", "users.first_name","users.admin_note as user_admin_note");
                        
            $where = PaymentOrderService::getWhere($params);
            $count = $query->where($where)->count();
            $list = $query->where($where)
                ->orderByRaw('CASE WHEN bot_payment_orders.status = 0 THEN 0 ELSE 1 END')
                ->orderByDesc('payment_orders.created_at')
                ->forpage($page, $limit)->get()->toArray();

            $totalAmount = 0;
            $totalSuccess = 0;
            $totalFail = 0;
            foreach ($list as $item) {
                $item['amount'] = floatval($item['amount']);
                $totalAmount += $item['amount'];
                if (in_array($item['status'], [1, 2])) $totalSuccess += $item['amount'];
                if ($item['status'] == 3) $totalFail += $item['amount'];
            }
            $result = [
                'total' => $count,
                'total_amount' => $totalAmount,
                'total_success' => $totalSuccess,
                'total_fail' => $totalFail,
                'data' => $list
            ];
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode(), $e->getmessage());
        }
        return $this->success($result);
    }

    public function setNote()
    {
        try {
            $params = request()->validate([
                'id' => ['required', 'integer', 'min:1'],
                'admin_note' => ['required', 'string', 'min:1', 'max:120'],
            ]);
            $w = WithdrawModel::where('id', $params['id'])->first();
            if (!$w) throw new Exception("记录不存在", HttpStatus::CUSTOM_ERROR);
            $w->admin_note = $params['admin_note'];
            $w->save();
        } 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();
    }


    public function index()
    {
        // try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'member_id' => ['nullable', 'string', 'min:1'],
                'status' => ['nullable', 'integer'],
                'first_name' => ['nullable'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 10);
            $query = WithdrawModel::join('users', 'users.member_id', '=', 'withdraws.member_id')
                        ->select("withdraws.*", "users.first_name","users.admin_note as user_admin_note");
            $where = WithdrawService::getWhere($params);
            $count = $query->where($where)->count();
            $list = $query->where($where)
                ->orderByRaw('CASE WHEN bot_withdraws.status = 0 THEN 0 ELSE 1 END')
                ->orderByDesc('withdraws.created_at')
                ->forpage($page, $limit)->get();
            $totalAmount = 0;
            $totalSuccess = 0;
            $totalFail = 0;
            foreach ($list as &$item) {
                $item['exchange_rate'] = floatval($item['exchange_rate']);
                $item['after_balance'] = floatval($item['after_balance']);
                $item['service_charge'] = floatval($item['service_charge']);
                $item['amount'] = floatval($item['amount']);
                if ($item['status'] == 1) $totalSuccess += $item['amount'];
                if ($item['status'] == 2) $totalFail += $item['amount'];
                $totalAmount += $item['amount'];
                $item['to_account_usdt'] = $item['to_account'] = floatval($item['to_account']);
                $item['exchange_rate'] = $item['exchange_rate'] <= 0 ? 7.3 : $item['exchange_rate'];

            }
            $result = [
                'total' => $count,
                'total_amount' => $totalAmount,
                'total_success' => $totalSuccess,
                'total_fail' => $totalFail,
                'data' => $list,
            ];
        // } catch (ValidationException $e) {
        //     return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        // } catch (Exception $e) {
        //     return $this->error(intval($e->getCode()));
        // }
        return $this->success($result);
    }

    public function setStatus()
    {
        DB::beginTransaction();
        try {
            $validate = [
                'ids' => ['required', 'array', 'min:1', 'max:20'],
                'ids.*' => ['required', 'integer', 'min:1'],
                'status' => ['required', 'integer', 'in:1,2'],
            ];
            $status = request()->input('status');
            if ($status == 2) {
                $validate['remark'] = ['required', 'string', 'min:1', 'max:200'];
            }
            request()->validate($validate);
            $ids = request()->input('ids');
            $remark = request()->input('remark');
            $count = 0;
            foreach ($ids as $id) {
                $count += WithdrawService::setStatus($id, $status, $remark);
            }
            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($e->getCode(), $e->getMessage());
        }
        return $this->success();
    }

    public function batch()
    {
        try {

            WithdrawService::batchReject();

            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();
    }

    //设置提现订单是否加锁
    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'],
            ]);
            WithdrawModel::whereIn('id',$params['ids'])->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();
    }
}