<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BalanceLogService;
use App\Services\TopUpService;
use App\Services\WalletService;
use App\Services\WithdrawService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;

class Withdraw extends Controller
{


    /**
     * @api {get} /admin/withdraw 提现列表
     * @apiGroup 提现管理
     *
     * @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 拒绝
     * @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.amount 提现金额
     * @apiSuccess (data) {string} data.data.service_charge 手续费
     * @apiSuccess (data) {string} data.data.to_account 到账金额
     * @apiSuccess (data) {string} data.data.after_balance 提现后余额
     * @apiSuccess (data) {string} data.data.address 钱包地址
     * @apiSuccess (data) {string} data.data.updated_at
     * @apiSuccess (data) {string} data.data.created_at
     * @apiSuccess (data) {int} data.data.status 状态
     * - 0 申请中
     * - 1 通过
     * - 2 拒绝
     * @apiSuccess (data) {string} data.data.remark
     *
     *
     */
    public function index()
    {
        try {
            request()->validate([
                'member_id' => ['nullable', 'string', 'min:1'],
                'status' => ['nullable', 'integer', 'min:0', 'max:2']
            ]);
            $search = request()->all();
            $result = WithdrawService::paginate($search);
        } 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);
    }

    /**
     * @api {post} /admin/withdraw/setStatus 通过|拒绝
     * @apiGroup 提现管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {string} id 提现表ID
     * @apiParam {int} status 状态
     * - 1 通过
     * - 2 拒绝
     */
    public function setStatus()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'id' => ['required', 'string', 'min:1'],
                'status' => ['required', 'integer', 'min:1', 'max:2']
            ]);
            $id = request()->input('id');
            $status = request()->input('status');


            $w = WithdrawService::findOne(['id' => $id, 'status' => 0]);
            if (!$w) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
            if ($status == 1) {
                $w->status = 1;
                $w->save();


            } else if ($status == 2) {
                $w->status = 2;
                $w->save();
                $wallet = WalletService::findOne(['member_id' => $w->member_id]);
                $afterBalance = bcadd($wallet->available_balance, $w->amount, 10);
                BalanceLogService::addLog(
                    $w->member_id,
                    $w->amount,
                    $wallet->available_balance,
                    $afterBalance,
                    '提现',
                    $w->id,
                    ''
                );
                $wallet->available_balance = $afterBalance;
                $wallet->save();
            }

            $arr = ['⏳️申请中', '✅️成功', '❌️失败'];
            $text = "📢 提现结果通知\n\n";

            $temp = floatval($w->service_charge);
            $text .= "手续费：{$temp} USDT\n";
            $temp = floatval($w->amount);
            $text .= "提现金额：{$temp} USDT\n";
            $temp = floatval($w->to_account);
            $text .= "到账金额：{$temp} USDT\n";
            $text .= "提现地址：{$w->address}\n\n";
            $text .= "状态：{$arr[$w->status]}\n";
            if ($w->remark) $text .= "说明：{$w->remark}";
            $res = WithdrawService::notify([
                'chat_id' => $w->member_id,
                'text' => $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($res);
    }
}