<?php

namespace App\Http\Controllers\api;

use App\Constants\Util;
use App\Constants\HttpStatus;
use App\Services\WalletService;
use App\Services\ConfigService;
use App\Models\Config;
use App\Models\Recharge;
use App\Models\Wallet as WalletModel;
use App\Models\Withdraw;
use App\Models\User;
use App\Models\Bank;
use App\Models\Address;
use App\Models\RechargeChannel;
use App\Models\PaymentOrder;
use App\Services\BalanceLogService;
use App\Services\PaymentOrderService;
use App\Services\Payment\JdPayService;
use App\Services\Payment\NoPayService;
use App\Services\Payment\ZimuPayService;
use App\Services\QianBaoWithdrawService;
use App\Services\WithdrawService;
use Illuminate\Support\Facades\DB;



use Illuminate\Validation\ValidationException;

use Exception;

/**
 * 充值提现接口
 */
class Wallet extends BaseController
{

    //获取三斤充值通道（微信、支付宝、扫码充值）
    public function getChannel()
    {
        $member_id = request()->user->member_id;
        if (empty(request()->user->recharge_channel_group_id)) {
            $recharge_channel_group_id = User::where('member_id', $member_id)->value('recharge_channel_group_id');
        } else {
            $recharge_channel_group_id = request()->user->recharge_channel_group_id;
        }
        $list = RechargeChannel::getFormatChannel(1, $recharge_channel_group_id);
        if (!JdPayService::canUserRecharge(request()->user->id)) {
            $list = array_values(array_filter($list, function ($item) {
                return !JdPayService::isChannel($item['value'] ?? '');
            }));
        }
        if (!NoPayService::canUserRecharge(request()->user->id)) {
            $list = array_values(array_filter($list, function ($item) {
                return !NoPayService::isRechargeChannel($item['value'] ?? '');
            }));
        }
        if (!ZimuPayService::canUserRecharge(request()->user->id)) {
            $list = array_values(array_filter($list, function ($item) {
                return !ZimuPayService::isRechargeChannel($item['value'] ?? '');
            }));
        }
        return $this->success([
            'list' => $list,
        ]);
    }

    /**
     * 创建代收订单（自动扫码充值）
     */
    public function createPay()
    {   
        try {
            $params = request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'payment_type' => ['required', 'string'],
            ]);
            if ($params['payment_type'] == 'rgcz') {
                return $this->error('参数有误');
            }
            
            $member_id = request()->user->member_id;
            $user = User::where('member_id', $member_id)->first();
            if (JdPayService::isChannel($params['payment_type']) && !JdPayService::canUserRecharge($user->id)) {
                throw new Exception(lang("不支持此充值方式"));
            }
            if (NoPayService::isRechargeChannel($params['payment_type']) && !NoPayService::canUserRecharge($user->id)) {
                throw new Exception(lang("不支持此充值方式"));
            }
            if (ZimuPayService::isRechargeChannel($params['payment_type']) && !ZimuPayService::canUserRecharge($user->id)) {
                throw new Exception(lang("不支持此充值方式"));
            }
            //校验是否支持此充值方式
            $check  = RechargeChannel::checkRechargeChannel($params['payment_type'], $user->recharge_channel_group_id);
            if ($check === false) {
                throw new Exception(lang("不支持此充值方式").$user->recharge_channel_group_id);
            }
            
            $res = PaymentOrderService::createPay($member_id, $params['amount'], $params['payment_type']);
            if ($res['code'] == 0) { 
                return $this->success($res);
            }
            return $this->error($res['text']);
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取充值二维码(USDT充值)
     */
    public function scan()
    {
        try {
            $member_id = request()->user->member_id;
            $params = request()->validate([
                'type' => ['required', 'string'],
            ]);

            if (strtolower($params['type']) === "trc20") {
                $address = Config::where('field', 'receiving_address')->first()->val;
            } elseif (strtolower($params['type']) === "erc20") {
                $address = Config::where('field', 'receiving_address_erc20')->first()->val;
            } else {
                return $this->error(lang('充值类型错误'));
            }

            $receivingType = ConfigService::getVal("receiving_type");
            //自动充值
            if ($receivingType == 1) {
                $res = WalletService::getRechargeImageAddress($member_id);
                $address = $res['address'];
                $qrCode = $res['full_path'];
            } else {
                //手动充值
                $res = WalletService::getPlatformImageAddress($address);
                $res['net'] = $params['type'];
                $qrCode = $res['full_path'];
            }
            
            return $this->success([
                'qrcode' => $qrCode,
                'address' => $address,
                // 'photo' => InputFile::create($qrCode),
            ]);
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 提交充值凭证(USDT手动充值)
     */
    public function recharge()
    {
        try {
            $params = request()->validate([
                'net' => ['required', 'string'],
                'amount' => ['required', 'numeric', 'min:0.01'],
                'toAddress' => ['required', 'string'],
                'image' => ['required', 'url'],
            ]);

            $member_id = request()->user->member_id;
            $user = User::where('member_id', $member_id)->first();

            //校验是否支持此充值方式
            $check  = RechargeChannel::checkRechargeChannel('usdt', $user->recharge_channel_group_id);
            if ($check === false) {
                throw new Exception(lang("不支持此充值方式"));
            }
            $recharge = new Recharge();
            $recharge->member_id = $member_id;
            $recharge->net = $params['net'];
            $recharge->coin = "USDT";
            $recharge->amount = $params['amount'];
            $recharge->to_address = $params['toAddress'];
            $recharge->status = 0;
            $recharge->type = 2;
            $recharge->image = Util::replacePartInUrl($params['image']);
            $recharge->save();
            return $this->success($recharge,'提交成功');

        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    //支付宝、微信、银行卡手动充值
    public function paymentOrder()
    {
        try {
            $member_id = request()->user->member_id;
            $params = request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'payment_type' => ['required', 'integer'],
            ]);
            
            $member_id = request()->user->member_id;
            $user = User::where('member_id', $member_id)->first();

            //校验是否支持此充值方式
            $check  = RechargeChannel::checkRechargeChannel('rgcz', $user->recharge_channel_group_id);
            if ($check === false) {
                throw new Exception(lang("不支持此充值方式"));
            }

            $data = [];
            $data['type'] = PaymentOrderService::TYPE_SELF_PAY;
            $data['order_no'] = PaymentOrderService::createOrderNo('rgcz_', $member_id);
            $data['member_id'] = $member_id;
            $data['fee'] = 0;
            $data['amount'] = number_format($params['amount'], 2, '.', '');
            $data['payment_type'] = $params['payment_type'];
            $data['channel'] = 'rgcz';
            $data['status'] = PaymentOrderService::STATUS_STAY;
            $data['remark'] = '';
            // 创建待处理状态的提现记录
            $info = PaymentOrder::create($data);
            return $this->success($info,'提交成功，请等待人工回复');
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    //支付宝、微信、银行卡手动充值提交图片
    public function submitImage()
    {
        try {
            $member_id = request()->user->member_id;
            $params = request()->validate([
                'id' => ['required', 'integer'],
                'image' => ['required', 'url'],
            ]);
            
            // 创建待处理状态的提现记录
            $info = PaymentOrder::where('id', $params['id'])->where('member_id', $member_id)->first();
            if (!$info) {
                return $this->error(lang('找不到此记录'));
            }
            if ($info->status != PaymentOrderService::STATUS_USER) {
                return $this->error(lang('待处理中，请稍后'));
            }
            $info->image = $params['image'];
            $info->status = PaymentOrderService::STATUS_AUDIT;
            $info->save();
            return $this->success($info,'提交成功，请等待人工审核');
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取提现通道
     */
    public function withdrawChannel()
    {
        $member_id = request()->user->member_id;
        if (empty(request()->user->recharge_channel_group_id)) {
            $recharge_channel_group_id = User::where('member_id', $member_id)->value('recharge_channel_group_id');
        } else {
            $recharge_channel_group_id = request()->user->recharge_channel_group_id;
        }
        $list = RechargeChannel::getFormatChannel(2, $recharge_channel_group_id);
        return $this->success($list);
    }

    //USDT提现
    public function withdraw()
    {   
        $error_code = -1;
        try {
            $member_id = request()->user->member_id;
            $params = request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'address' => ['required', 'string'],
                'safe_word' => ['required'],
            ]);
            $user = User::where('member_id', $member_id)->first();
            if ($user->from == 2) {
                throw new Exception(lang("游客不支持提现"));
            }
            if (empty($user->payment_password)) {
                $error_code = 10011;
                throw new Exception(lang("请先设置资金密码"));
            }
            //校验资金密码
            if (!password_verify($params['safe_word'], $user->payment_password)) {
                throw new Exception(lang('资金密码错误'));
            }

            //校验是否支持此提现方式
            $check  = RechargeChannel::checkWithdrawChannel('usdt', $user->recharge_channel_group_id);
            if ($check === false) {
                throw new Exception(lang("不支持此提现方式"));
            }
            
            $amount = $params['amount'];
            $address = $params['address'];
            
            //校验提现金额的限制
            if ($amount < $check->min || $amount > $check->max) {
                throw new Exception(lang("提现金额超出限制"));
            }

            $serviceCharge = (new WithdrawService())->serviceCharge;
            $real = bcsub($amount, $serviceCharge, 10);
            $real = floatval($real);

            if ($amount <= $serviceCharge) {
                throw new Exception(lang("提现不能少于") . "{$serviceCharge} USDT");
            }   

            $wallet = WalletModel::where('member_id', $member_id)->first();
            $temp = floatval($wallet->available_balance);
            // 汇率
            $rate = Config::where('field', 'exchange_rate_rmb')->first()->val ?? 1;
            $exchange_rate_difference = Config::where('field', 'exchange_rate_difference')->first()->val ?? 0;
            $rate = bcadd($rate, $exchange_rate_difference, 2);

            $rate_usdt_amount = bcdiv($temp, $rate, 2);  // 钱包可用余额 折合USDT
            $rate_rmb_amount = bcmul($amount, $rate, 2);  // 提现金额 折合RMB
            if ($amount > $rate_usdt_amount) {
                throw new Exception(lang("余额不足") . "{$serviceCharge} USDT");
            }
            $wallet = WalletModel::where('member_id', $member_id)->first();
            $changeAmount = bcmul(($amount * -1), $rate, 2);
            $beforeBalance = $wallet->available_balance;
            $afterBalance = bcsub($wallet->available_balance, $rate_rmb_amount, 2);
            $wallet->available_balance = $afterBalance;
            $wallet->save();

            $withdraw = Withdraw::create([
                'member_id' => $member_id,
                'amount' => $amount,
                'service_charge' => $serviceCharge,
                'to_account' => $real,
                'address' => $address,
                'exchange_rate' => $rate,
                'status' => 0,
                'after_balance' => $afterBalance
            ]);
            BalanceLogService::addLog($member_id, $changeAmount, $beforeBalance, $afterBalance, '提现', $withdraw->id, '');
            return $this->success($withdraw,'提交成功');
            
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), [], $error_code);
        }

    }
    

    /**
     * 提现(手动到账)： DF001 支付宝转卡; DF002 支付宝转支付宝; DF005数字人民币； JDpay JD钱包； NOwithdraw NO钱包； ZIMUwithdraw 808币钱包地址提现；ZIMUcash 808人民币代付； rgtx(人工提现，手动打款)
     */
    public function payout() {
        $error_code = -1;
        try {
            $params = request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'channel' => ['required', 'string', 'in:DF001,DF002,DF005,JDpay,jdpay,NOwithdraw,ZIMUwithdraw,ZIMUcash,rgtx'],
                'bank_name' => ['nullable', 'string'],
                'account' => ['nullable', 'string'],
                'card_no' => ['required', 'string'],
                'safe_word' => ['required'],
            ]);
            $member_id = request()->user->member_id;
            $user = User::where('member_id', $member_id)->first();
            if ($user->from == 2) {
                throw new Exception(lang("游客不支持提现"));
            }
            //检验是否有待处理的提现订单
            if ($params['channel'] == 'rgtx') {
                $count = PaymentOrder::where('type', PaymentOrderService::TYPE_SELF_PAYOUT)
                            ->where('member_id', $member_id)
                            ->whereIn('status', [0,1,4,5])
                            ->count();
                if ($count > 0) {
                    throw new Exception(lang("您已有1笔提现订单正常处理中！"));
                }
            }
            if (empty($user->payment_password)) {
                $error_code = 10011;
                throw new Exception(lang("请先设置资金密码"));
            }
            //校验资金密码
            if (!password_verify($params['safe_word'], $user->payment_password)) {
                throw new Exception(lang('资金密码错误'));
            }
            
            //校验是否支持此提现方式
            $check  = RechargeChannel::checkWithdrawChannel($params['channel'], $user->recharge_channel_group_id);
            if ($check === false) {
                throw new Exception(lang("不支持此提现方式"));
            }
            if (!ZimuPayService::isWithdrawChannel($params['channel']) && (empty($params['bank_name']) || empty($params['account']))) {
                throw new Exception(lang("提现信息不完整"));
            }

            $amount = $params['amount'];
            //校验提现金额的限制
            if ($amount < $check->min || $amount > $check->max) {
                throw new Exception(lang("提现金额超出限制"));
            }
            
            if ($params['channel'] == 'rgtx') {
                
                DB::beginTransaction();
                try {
                    $wallet = WalletService::findOne(['member_id' => $member_id]);
                    if (!$wallet) throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
                    $balance = $wallet->available_balance;
                    if (bccomp($balance, $amount, 2) < 0) {
                        throw new Exception("您的钱包余额不足！", HttpStatus::CUSTOM_ERROR);
                    }
                    $available_balance = bcsub($balance, $amount, 10);

                    // 先预扣款（锁定资金）
                    $wallet->available_balance = $available_balance;
                    if (!$wallet->save()) throw new Exception('钱包更新失败！', HttpStatus::CUSTOM_ERROR);

                    $rate = RechargeChannel::where('type', 'rgtx')->value('rate');
                    $rate = $rate ?? 1;
                    $data = [];
                    $data['type'] = PaymentOrderService::TYPE_SELF_PAYOUT;
                    $data['order_no'] = PaymentOrderService::createOrderNo('rgtx' . $data['type'] . '_', $member_id);
                    $data['member_id'] = $member_id;
                    $data['fee'] = $amount * $rate;
                    $data['amount'] = number_format($amount, 2, '.', '');
                    $data['channel'] = $params['channel'];
                    $data['bank_name'] = $params['bank_name'];
                    $data['account'] = $params['account'];
                    $data['card_no'] = $params['card_no'];
                    $data['status'] = PaymentOrderService::STATUS_STAY;
                    // 创建待处理状态的提现记录
                    $info = PaymentOrder::create($data);
                    // 记录余额变动日志
                    BalanceLogService::addLog($member_id, $amount * -1, $balance, $available_balance, '人工提现', $info->id, '钱宝提现费率：'.($rate  * 100) . '%');

                    $balance = bcadd($available_balance, 0, 2);
                    DB::commit();
                } catch (Exception $e) {
                    DB::rollBack();
                    if ($e->getCode() === HttpStatus::CUSTOM_ERROR) {
                        return $this->error($e->getMessage());
                    }
                }
                return $this->success($info,'提交成功');
            } else {
                $bankName = $params['bank_name'] ?? '';
                $account = $params['account'] ?? '';
                if (ZimuPayService::isWithdrawChannel($params['channel'])) {
                    $bankName = $bankName ?: '808币提现-钱包地址';
                    $account = '';
                }
                $res = QianBaoWithdrawService::createOrder($member_id, $params['amount'], $params['channel'], $bankName, $account, $params['card_no']);
                if ($res['code'] == 0) { 
                    return $this->success($res,'提交成功');
                }
                return $this->error($res['text']);
            }
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), [], $error_code);
        }
    }

    /**
     * 提现(自动到账)： DF001 支付宝转卡/DF002 支付宝转支付宝
     */
    public function autoPayout()
    {
        try {
            $params = request()->validate([
                'amount' => ['required', 'numeric', 'min:0.01'],
                'channel' => ['required', 'string'],
                'bank_name' => ['required', 'string'],
                'account' => ['required', 'string'],
                'card_no' => ['required', 'string'],
            ]);
            $member_id = request()->user->member_id;
            $res = PaymentOrderService::autoCreatePayout($member_id, $params['amount'], $params['channel'], $params['bank_name'], $params['account'], $params['card_no']);
            if (empty($res['text'])) { 
                return $this->success($res,'提交成功');
            }
            return $this->error($res['text']);
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function addBank()
    {
        try {
            $params = request()->validate([
                'id' => 'nullable|integer',
                'channel' => 'required',
                'account' => 'required',
                'card_no' => 'required',
                'bank_name' => 'required',
                'alias' => 'nullable',
            ]);
            $member_id = request()->user->member_id;
            if (!empty($params['id'])) {
                $info = Bank::where('id', $params['id'])->where('member_id', $member_id)->first();
                if (empty($info)) throw new Exception(lang('找不到此记录'));
                $info->channel = $params['channel'];
                $info->account = $params['account'];
                $info->card_no = $params['card_no'];
                $info->bank_name = $params['bank_name'];
                $info->alias = $params['alias'] ?? '';
                $info->save();
            } else {
                $count = Bank::where('member_id', $member_id)->where('channel', $params['channel'])->count();
                if ($count >= 5) throw new Exception(lang('已达添加上限'));
                Bank::create([
                    'member_id' => $member_id,
                    'channel' => $params['channel'],
                    'account' => $params['account'],
                    'card_no' => $params['card_no'],
                    'bank_name' => $params['bank_name'],
                    'alias' => $params['alias'] ?? '',
                ]);
            }

            return $this->success([],'提交成功');
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function delBank()
    {
        try {
            $params = request()->validate([
                'id' => 'required|integer',
            ]);
            $member_id = request()->user->member_id;
            $info = Bank::where('id', $params['id'])->where('member_id', $member_id)->first();
            if (empty($info)) throw new Exception(lang('找不到此记录'));
               
            $info->delete();
            return $this->success([],'删除成功');
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function bankList()
    {
        try {
            $params = request()->validate([
                'channel' => 'nullable',
            ]);
            $member_id = request()->user->member_id;
            $where = !empty($params['channel']) ? ['channel' => $params['channel']] : [];
            $list = Bank::where('member_id', $member_id)->where($where)->get()->toArray();

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

    public function addAddress()
    {
        try {
            $params = request()->validate([
                'id' => 'nullable|integer',
                'address' => 'required',
                'alias' => 'nullable',
            ]);
            $member_id = request()->user->member_id;
            if (!empty($params['id'])) {
                $info = Address::where('id', $params['id'])->where('member_id', $member_id)->first();
                if (empty($info)) throw new Exception(lang('找不到此记录'));
                $info->address = $params['address'];
                $info->alias = $params['alias'] ?? '';
                $info->save();
            } else {
                $count = Address::where('member_id', $member_id)->where('address', $params['address'])->count();
                if ($count >= 5) throw new Exception(lang('已达添加上限'));
                Address::create([
                    'member_id' => $member_id,
                    'address' => $params['address'],
                    'alias' => $params['alias'] ?? '',
                ]);
            }

            return $this->success([],'提交成功');
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function delAddress()
    {
        try {
            $params = request()->validate([
                'id' => 'required|integer',
            ]);
            $member_id = request()->user->member_id;
            $info = Address::where('id', $params['id'])->where('member_id', $member_id)->first();
            if (empty($info)) throw new Exception(lang('找不到此记录'));
               
            $info->delete();
            return $this->success([],'删除成功');
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function address()
    {
        try {
            $member_id = request()->user->member_id;
            $list = Address::where('member_id', $member_id)->get()->toArray();

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

}
