<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Models\Recharge;
use App\Services\BalanceLogService;
use App\Services\MenuService;
use App\Services\RechargeService;
use App\Services\TopUpService;
use Exception;
use Illuminate\Support\Facades\Cache;

use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use App\Models\Wallet as WalletModel;
use App\Models\Withdraw;
use App\Models\Config;
use App\Models\PaymentOrder;
use App\Models\Order;
use App\Models\LhcOrder;
use App\Models\Bank;
use App\Models\Address;
use App\Services\Payment\QianBaoService;

class Wallet extends Controller
{

    /**
     * 获取提现通道
     */
    public function withdrawChannel()
    {
        $list = QianBaoService::withdrawChannel();
        $data[] = ['label' => 'USDT', 'value' => 'USDT'];
        foreach ($list as $key => $item) {
            $data[] = ['label' => $item, 'value' => $key];
        }
        return $this->success($data);
    }

    //银行卡/支付宝列表
    public function bankList()
    {
        try {
            $params = request()->validate([
                'channel' => 'nullable',
                'member_id' => 'nullable',
            ]);
            $where = [];
            if (!empty($params['channel'])) {
                $where[] = ['channel', '=', $params['channel']];
            }
            if (!empty($params['member_id'])) {
                $where[] = ['member_id', '=', $params['member_id']];
            }
            $list = Bank::where($where)->get()->toArray();

            return $this->success([
                'list' => $list,
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    //地址列表
    public function address()
    {
        try {
            $params = request()->validate([
                'member_id' => 'nullable',
            ]);
            $where = [];
            if (!empty($params['member_id'])) {
                $where[] = ['member_id', '=', $params['member_id']];
            }
            $list = Address::where($where)->get()->toArray();

            return $this->success([
                'list' => $list,
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function getChangeTypes()
    {
        return $this->success(BalanceLogService::$manualRecharge);
    }

    /**
     * @api {get} /admin/wallet/getPendingTasks 待处理任务
     * @apiDescription 后台每隔10秒，轮询请求这个接口获取待处理的任务数，如果有待处理的任务，则播放音乐
     * @apiGroup 充值管理
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.recharge_task 待处理充值任务
     * @apiSuccess (data) {int} data.withdraw_task 待处理提现任务
     */
    function getPendingTasks()
    {
        $data = [
            'recharge_task' => 0,
            'withdraw_task' => 0,
            'rmb_withdraw_task' => 0,
        ];
        if (MenuService::checkMenu(request()->user->id, 'withdraw/topUp')) {
            $data['recharge_task'] = Recharge::where('type', 2)->where('status', 0)->count();
        }
        if (MenuService::checkMenu(request()->user->id, 'listUSDT')) {
            $data['withdraw_task'] = Withdraw::where('status', 0)->count();
        }
        if (MenuService::checkMenu(request()->user->id, 'listRMB')) {
            $data['rmb_withdraw_task'] = PaymentOrder::where('type', 2)->where('status', 0)->count();
        }
        return $this->success($data);
    }

    //扣款
    public function debiting()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'member_id' => ['required', 'string', 'min:1'],
                'remark' => ['required', 'string', 'min:1'],
            ]);
            $memberId = request()->input('member_id');
            $amount = request()->input('amount');
            $amount = $amount * -1;
            $remark = request()->input('remark');
            $key = 'api_request_' . md5($memberId . json_encode([
                        'amount' => $amount,
                        'remark' => $remark,
                        'action' => "wallet/debiting"
                    ]));
            if (Cache::has($key)) throw new Exception("请求太频繁，请稍后再试。", HttpStatus::CUSTOM_ERROR);
            Cache::put($key, true, 3);
            $wallet = WalletModel::where('member_id', $memberId)->first();
            if (!$wallet) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
            $availableBalance = bcadd($wallet->available_balance, $amount, 10);
            if ($availableBalance < 0) throw new Exception('可用余额不足', HttpStatus::CUSTOM_ERROR);
            BalanceLogService::addLog($memberId, $amount, $wallet->available_balance, $availableBalance, "人工扣款", 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(intval($e->getCode()), $e->getMessage());
        }
        $availableBalance = floatval($availableBalance);
        // 去除多余0后，再用 sprintf 补足两位
        $availableBalance = sprintf('%.2f', $availableBalance);
        TopUpService::notifyTransferSuccess($memberId, "您的账户余额更新：" . ($amount > 0 ? '+' : '') . "{$amount} \n总余额为：{$availableBalance}");
        return $this->success();
    }

    //会员账号充值
    public function topUp()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'member_id' => ['required', 'string', 'min:1'],
                'remark' => ['required', 'string', 'min:1'],
                'change_type' => ['required', 'string', 'in:' . implode(',', BalanceLogService::$manualRecharge)],
            ]);
            $memberId = request()->input('member_id');
            $amount = request()->input('amount');
            $remark = request()->input('remark');
            $changeType = request()->input('change_type');
            $key = 'api_request_' . md5($memberId . json_encode([
                        'amount' => $amount,
                        'remark' => $remark,
                        'action' => "wallet/topUp"
                    ]));
            if (Cache::has($key)) throw new Exception("请求太频繁，请稍后再试。", HttpStatus::CUSTOM_ERROR);
            Cache::put($key, true, 3);
            $wallet = WalletModel::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(intval($e->getCode()), $e->getMessage());
        }

        $availableBalance = floatval($availableBalance);
        // 去除多余0后，再用 sprintf 补足两位
        $availableBalance = sprintf('%.2f', $availableBalance);
        TopUpService::notifyTransferSuccess($memberId, "您的账户余额更新：" . ($amount > 0 ? '+' : '') . "{$amount} \n总余额为：{$availableBalance}");
        return $this->success();
    }

    //订单充值
    public function orderTopUp()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'remark' => ['required', 'string', 'min:1'],
                'order_type' => ['nullable'],
                'order_id' => ['nullable'],
            ]);
            $order_type = request()->input('order_type');
            $order_id = request()->input('order_id');
            $amount = request()->input('amount');
            $remark = request()->input('remark');
            $changeType = "人工充值";
            $key = 'api_request_' . md5($order_id . json_encode([
                        'amount' => $amount,
                        'remark' => $remark,
                        'action' => "wallet/orderTopUp"
                    ]));
            if (Cache::has($key)) throw new Exception("请求太频繁，请稍后再试。", HttpStatus::CUSTOM_ERROR);
            Cache::put($key, true, 3);

            if ($order_type == 'sport') {
                $info = Order::where('id', $order_id)->first();
            } elseif ($order_type == 'lhc') {
                $info = LhcOrder::where('id', $order_id)->first();
            }
            if (!$info) {
                throw new \Exception('订单不存在');
            } else {
                $info->remark = $info->remark ? $info->remark. '|' . $remark : $remark;
                $info->save();
            }
            $memberId = $order_type == 'sport' ? $info->user_id : $info->member_id;

            $wallet = WalletModel::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(intval($e->getCode()), $e->getMessage());
        }

        return $this->success();
    }

    //订单扣款
    public function orderDebiting()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'remark' => ['required', 'string', 'min:1'],
                'order_type' => ['required'],
                'order_id' => ['required'],
            ]);
            $order_type = request()->input('order_type');
            $order_id = request()->input('order_id');
            $amount = request()->input('amount');
            $amount = $amount * -1;
            $remark = request()->input('remark');
            $key = 'api_request_' . md5($order_id . json_encode([
                        'amount' => $amount,
                        'remark' => $remark,
                        'action' => "wallet/orderDebiting"
                    ]));
            if (Cache::has($key)) throw new Exception("请求太频繁，请稍后再试。", HttpStatus::CUSTOM_ERROR);
            Cache::put($key, true, 3);

            if ($order_type == 'sport') {
                $info = Order::where('id', $order_id)->first();
            } elseif ($order_type == 'lhc') {
                $info = LhcOrder::where('id', $order_id)->first();
            }
            if (!$info) {
                throw new \Exception('订单不存在');
            } else {
                $info->remark = $info->remark ? $info->remark. '|' . $remark : $remark;
                $info->save();
            }
            $memberId = $order_type == 'sport' ? $info->user_id : $info->member_id;

            $wallet = WalletModel::where('member_id', $memberId)->first();
            if (!$wallet) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
            $availableBalance = bcadd($wallet->available_balance, $amount, 10);
            if ($availableBalance < 0) throw new Exception('可用余额不足', HttpStatus::CUSTOM_ERROR);
            BalanceLogService::addLog($memberId, $amount, $wallet->available_balance, $availableBalance, "人工扣款", 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(intval($e->getCode()), $e->getMessage());
        }
        return $this->success();
    }

    /**
     * @api {post} /admin/wallet/verifyRecharge 审核
     * @apiGroup 充值管理
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     * @apiParam {int} id 充值表的ID
     * @apiParam {int} status 状态
     * - 1 通过
     * - 2 拒绝
     * @apiParam {string} [remark] 说明
     * - 当status =2 时，此参数必填
     */
    public
    function verifyRecharge()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'id' => ['required', 'integer', 'min:1'],
                'status' => ['required', 'integer', 'in:1,2'],
                'remark' => ['required_if:status,2', 'string', 'min:1']
            ]);
            $id = request()->input('id');
            $status = request()->input('status');
            $remark = request()->input('remark', '');
            $recharge = Recharge::where('id', $id)
                ->where('type', 2)
                ->where('status', 0)->first();
            if (!$recharge) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
            $amount = floatval($recharge->amount);
            if ($status == 2) {
                $recharge->status = 2;
                $recharge->save();
                $text = "充值结果通知\n";
                $text .= "充值数量：{$amount} USDT\n";
                $text .= "充值地址：{$recharge->to_address}\n";
                $text .= "状态：失败\n";
                $text .= "原因：{$remark}\n";
                TopUpService::notifyTransferSuccess($recharge->member_id, $text);
            } else {
                // 汇率
                $rate = Config::where('field', 'exchange_rate_rmb')->first()->val ?? 1;
                $recharge->status = 1;
                $recharge->exchange_rate = $rate;
                $recharge->save();
                $wallet = WalletModel::where('member_id', $recharge->member_id)
                    ->first();
                $rate_amount = bcmul($amount, $rate, 10); // 汇率转换后分数
                $available_balance = bcadd($wallet->available_balance, $rate_amount, 10);

                BalanceLogService::addLog($recharge->member_id, $rate_amount, $wallet->available_balance, $available_balance, "充值", $recharge->id, "用户充值后台审核到账");
                $wallet->available_balance = $available_balance;
                $wallet->save();

                $text = "充值结果通知\n";
                $text .= "充值数量：{$amount} USDT\n";
                $text .= "充值地址：{$recharge->to_address}\n";
                $text .= "汇率：1 USDT = {$rate} RMB\n";
                $text .= "折合金额：" . number_format($rate_amount, 2) . " RMB\n";
                $text .= "状态：成功\n";
                TopUpService::notifyTransferSuccess($recharge->member_id, $text);
            }
            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(intval($e->getCode()), $e->getMessage());
        }
        return $this->success();
    }

    /**
     * @api {get} /admin/wallet 充值列表
     * @apiGroup 充值管理
     * @apiDescription 如果列表的type=2 并且 status = 0 <br/>那么代表这条数据是需要后台手动审核的
     * 需要有审核按钮，审核通过或者拒绝，其它情况则不需要审核按钮
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     * @apiParam {string} [member_id] 房主 tg会员ID
     * @apiParam {int} [status] 状态
     * - 0 待确认
     * - 1 已确认
     * - 2 失败
     * - 3 已忽略
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.total 数量
     * @apiSuccess (data) {Object[]} data.data 列表
     * @apiSuccess (data) {int} data.data.id
     * @apiSuccess (data) {int} data.data.member_id tg会员id
     * @apiSuccess (data) {string} data.data.net 链接类型
     * @apiSuccess (data) {string} data.data.coin 币种
     * @apiSuccess (data) {string} data.data.amount 充值数量
     * @apiSuccess (data) {string} data.data.to_address 充值地址（平台地址）
     * @apiSuccess (data) {string} data.data.from_address 转出地址（用户发起地址）
     * @apiSuccess (data) {string} data.data.txid 链上交易哈希
     * @apiSuccess (data) {string} data.data.block_time 区块时间
     * @apiSuccess (data) {string} data.data.block_height
     * @apiSuccess (data) {int} data.data.confirmations 确认数
     * @apiSuccess (data) {string} data.data.updated_at
     * @apiSuccess (data) {string} data.data.created_at
     * @apiSuccess (data) {int} data.data.status 状态
     * - 0 待确认
     * - 1 已确认
     * - 2 失败
     * - 3 已忽略
     * @apiSuccess (data) {int} data.data.type 充值类型
     * - 1 自动
     * - 2 手动
     * @apiSuccess (data) {string} data.data.image 充值转账凭证图片
     */
    public
    function index()
    {
        try {
            request()->validate([
                'member_id' => ['nullable', 'string', 'min:1'],
                'status' => ['nullable', 'string', 'min:0', 'max:3'],
                'type' => ['nullable', 'integer', 'in:1,2'],
                'first_name' => ['nullable'],
            ]);
            $search = request()->all();
            $result = RechargeService::paginate($search);
            foreach($result['data'] as &$item) {
                if ($item['from'] == 2) {
                    $item['image'] = str_replace(env('APP_URL'), env('FOOTBALL_APP_URL').'/', $item['image']);
                }
            }
        } 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 test()
    {

        // $url = "https://ydpc28.co/api/pc28/list";
        // $result = file_get_contents($url);
        // $result = json_decode($result, true);

        $input = request()->get('input', '');
        // var_dump($input);
        // $contractAddress = TronHelper::getContractAddress('USDT');
        // $result = TronHelper::getTrc20Balance('TTJ1vH18Q4K3seDcjD4912KDHHzm327rtL',$contractAddress);
        // $result = TronHelper::getBalance('TDeGNiweUm86JBJHQ7kXwQ8XQKtrKorHad','USDT');
        // dump($result);

        // echo WalletService::createRechargeQrCode('TDeGNiweUm86JBJHQ7kXwQ8XQKtrKorHad');
        // $result = TronHelper::getTrc20UsdtRecharges('TGQaMxtyWeGowy8xqwh98JNNLtc77nzZ8M');
        // $result = TronHelper::getTransactionConfirmations('06407fa9a2ba51c88f1ed01c2296f0069bf305477d3847d41bc3f35cf9190f74');
        // var_dump($result);
        $memberId = '6325700519';
        // $result = BetService::bet($memberId,$input);

        // $info = IssueService::findOne(['issue_no'=>'202508271120']);

        // $winning_numbers = explode(',',$info['winning_numbers']);

        // $result = IssueService::award($winning_numbers);
        // var_dump($result);
        // RechargeService::handleRechargeConfirmation('45f313ccc3a2f4113f6cc9a7511e8b5096daa1de76cb57397e152a491c17249f');
        // WalletService::getUserWallet('1777');

        // $result = GameplayRuleService::validateInput('大100');
        // $result = IssueService::currentLotteryResults($memberId);
        // var_dump($result);
        // $result = IssueService::getLatestIssue();
        // $result = ConfigService::syncExchangeRate();
        // $url = "https://ydpc28.co/api/pc28/list";
        // $result = file_get_contents($url);
        // $result = json_decode($result, true);
        // $awards = IssueService::award([7,7,7]);
        // $result = BetService::betSettled2('3356003',$awards);
        // $result = IssueService::sendLotteryImage($memberId, 3356000);
        // $order_no = QianBaoService::createOrderNo();
        // echo $order_no;
        // $result = QianBaoService::pay(100,$order_no);
        // $result = QianBaoService::payout(100,$order_no,'厦门银行','张三',1245679451259741541,QianBaoService::ALIPAY_TO_ALIPAY);
        // $result = PaymentOrderService::createPayout($memberId,100,QianBaoService::ALIPAY_TO_ALIPAY,'支付宝','张三','17605957777');
        // PaymentOrderService::sendMessage($result['chat_id'],$result['text']);
        // $result = PaymentOrderService::createPay($memberId,100,QianBaoService::PAY_ZFB1,'张三');
        // $result = mb_strlen('哈哈哈123ABC');
        // $order_no = SanJinService::createOrderNo();
        // $result = SanJinService::pay(10000,$order_no);
        // $result = PaymentOrderService::createPay($memberId,200,'test');
        // PaymentOrderService::sendMessage($result['chat_id'],$result['text'],[],$result['image']??'');
        // $result = KeyboardService::checkStart($memberId,'Select Language');

        // $awards = IssueService::award([7,2,1]);
        // $result = BetService::betSettled('3367329', $awards);
        echo "<pre>";
        // $result = PaymentOrderService::syncPayOrder();

        // $result = WalletService::violationWallet();
        $result = '';
        $result = RechargeService::syncUsdtRechargeRecords($memberId);
        var_dump($result);
    }
}