<?php

namespace App\Http\Controllers\V1;

use App\Auth;
use App\libs\helpers\LogHelper;
use App\libs\helpers\Response;
use App\Models\Config;
use App\Models\Giveaway;
use App\Models\Apply;
use App\libs\wechat\auth\WeChat;
use App\Models\Order;
use App\Models\Share;
use App\Models\TaskList;
use App\Models\User;
use App\Models\UserFeedback;
use App\Models\UserRole;
use App\Models\Withdraw;
use App\Services\Api\SortService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function __construct()
    {
        $this->user   = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;

        // 如果用户被删除，会自动退出登录
        if (!empty($this->user->deleted_at)) {
            $this->user->online = 0;
            $this->user->save();
            auth('api')->logout();
        }
    }
     /**
     * 我的邀请码 。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserRqCode(Request $request)
    {
        try {
            if (empty(Auth::$user->qr_code)){
                $file     = WeChat::Mini()->qrcodeUnlimited(Auth::$userId, ['page' => 'pages/index/index', 'env_version' => 'develop', 'check_path' => false]);
                $fileName = 'images/' . date('Ymd') . '/' . date('YmdHis') . uniqid() . '.png'; // 文件名称
                Storage::disk('admin')->put($fileName, $file);
                $url = 'https://' . $_SERVER['HTTP_HOST'] . '/uploads/' . $fileName;
                Auth::$user->qr_code = $url;
                Auth::$user->save();
            }else{
                $url = Auth::$user->qr_code;
            }
            return Response::success(['url' => $url]);
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);
            return Response::fail($exception->getMessage());
        }
    }
    // 问题反馈
    public function feedback(Request $request)
    {
        $content  = $request->input('content');
        $file_url = $request->input('file_url', '');

        $validator = Validator::make($request->all(), [
            'content' => 'required|min:2|max:200',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $feedback          = new UserFeedback();
        $feedback->user_id = $this->userId;
        $feedback->content = $content;
        $feedback->file    = !empty($file_url) ? json_encode($file_url) : '';
        $feedback->save();

        return $this->success();
    }

    // 按照首字母进行分组排序，类似手机通讯录(注意：get()后面直接 ->toArray()在数据为空的时候导致报错)
    public function groupByInitial(Request $request)
    {
        $keyword = $request->input('keyword', '');

        $list = User::query()
            ->select('id', 'name', 'avatar')
            ->when($keyword, function ($query, $keyword) {
                $query->where('name', 'like', '%' . $keyword . '%');
            })
            ->whereNotNull('name')
            ->whereNull('deleted_at')
            ->get();

        if ($list->isNotEmpty()) {
            $list = $list->toArray();
            $list = SortService::getResultList($list);
        } else {
            $list = [];
        }

        return $this->success($list);
    }

    public function info()
    {
        return $this->success(Auth::$user);
    }

    // 绑定上级
    public function bind($id)
    {
        $user = \user();
        if (is_numeric($id)) {
            $user   = \user();
            $parent = User::find($id);
        } else { // 微信扫场景码
            $parent = User::where('scene_code', $id)->first();
        }
        // 没有绑定上级 且上级存在其实分销商 且不是自己
        if (!$user->parent_id && $parent && $parent->is_share && $parent->id != $user->id) {
            $user->parent_id       = $parent->id;
            $user->become_child_at = Carbon::now()->toDateTimeString();

            // 之前不是分销商 自动成为分销商
            if (!$user->is_share) {
                $user->become_share_at = Carbon::now()->toDateTimeString();
                $user->is_share        = 1;
            }
            $user->save();
        }
        $user = User::with(['info', 'parent'])->where('id', $user->id)->first();

        return $this->success($user);
    }

    public function update(Request $request)
    {
        try {
            $req       = $request->all();
            $validator = Validator::make($req, [
                'name'   => 'required|max:50',
                'avatar' => 'required|url',
                'mobile' => 'required',
            ], [
                'name.required'   => '昵称是必填项',
                'name.max'        => '昵称最多50字',
                'avatar.required' => '头像是必填项',
                'avatar.url'      => '头像格式错误',
                'mobile.required' => '手机号是必填项',
            ]);

            if ($validator->fails()) {
                return Response::fail(implode(',', $validator->errors()->all()));
            }
            User::query()->where('id', Auth::$userId)->update([
                'name'   => $req['name'],
                'avatar' => $req['avatar'],
                'mobile' => $req['mobile'],
            ]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 申请成为推广大使
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function applyShare(Request $request)
    {
                    $name  = $request->input('name');
            $phone = $request->input('phone');
            if (1 == Auth::$user->is_share) {
                return Response::fail('您已经是推广大使');
            }
            Apply::query()->create([
                'user_id'       => Auth::$userId,
                'share_name'    => $name,
                'share_phone'   => $phone
            ]);
            return Response::success();
    }

    /**
     * 我的团队
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function myTeam(Request $request)
    {
        try {
            $team                  = User::query()->select(['id', 'name', 'avatar', 'share_date'])->withCount('order')->withSum('amount', 'amount')->where('share_pid', Auth::$userId)->paginate();
            $team                  = $team->toArray();
            $team['teamUserCount'] = User::query()->where('share_pid', Auth::$userId)->count();

            return Response::success($team);
        } catch (\Exception $exception) {
            //            LogHelper::exceptionLog($exception, $this->code);
            return Response::fail($exception->getMessage());
        }
    }

    /**
     * 我的分佣.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function myGiveaway(Request $request)
    {
        try {
            $giveaway                   = Giveaway::query()->with('user')->where('user_id', Auth::$userId)->orderByDesc('id')->paginate();
            $giveaway                   = $giveaway->toArray();
            $giveaway['totalIncome']    = Giveaway::query()->where('user_id', Auth::$userId)->sum('amount') / 100;
            $giveaway['withdrawIncome'] = Auth::$user->income;

            return Response::success($giveaway);
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }

    /**
     * 用户提现.
     */
    public function userWithdraw(Request $request): \Illuminate\Http\JsonResponse
    {
        $param = $request->all();
        if (Auth::$user->income < (float) $param['amount']) {
            return Response::fail('余额不足');
        }
        (float) $min = Config::query()->where('key', 'withdraw_min')->value('value'); // 最少提现金额
        if ($min > $param['amount']) {
            return Response::fail('提现最小金额：' . $min . '元');
        }
        (float) $service = Config::query()->where('key', 'withdraw')->value('value'); // 提现手续费
        $procedure       = (float) $param['amount'] * ($service / 100);

        $withdraw = Withdraw::query()->create([
            'user_id'          => Auth::$userId,
            'type'             => $param['type'],
            'bank_name'        => $param['bank_name'] ?? '',
            'name'             => $param['name'],
            'number'           => $param['number'],
            'amount'           => (float) $param['amount'],
            'procedure'        => $procedure,
            'practical_amount' => (float) $param['amount'] - $procedure,
        ]);
        if (!$withdraw) {
            return Response::fail('提现失败');
        }
        User::query()->where('id', Auth::$userId)->decrement('income', $param['amount'] * 100);

        return Response::success();
    }

    /**
     * 我的提现记录.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userWithdrawList()
    {
        $result = Withdraw::query()->where('user_id', Auth::$userId)->orderByDesc('id')->paginate(20);

        return $this->success($result);
    }

    /**
     * 我的推荐.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function myShare(Request $request)
    {
        try {
            $result                        = Share::query()->with('user')->where('user_id', Auth::$userId)->orderByDesc('id')->paginate();
            $result                        = $result->toArray();
            $result['currentDiamondCount'] = Auth::$user->diamond;
            $result['shareDiamondCount']   = Share::query()->where('user_id', Auth::$userId)->sum('diamond');

            return Response::success($result);
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }

    /**
     * 我的充值记录.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function myConsumeList(Request $request)
    {
        try {
            $result = TaskList::query()->with('role')->where('user_id', Auth::$userId)->orderByDesc('id')->paginate();

            return Response::success($result);
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }

    /**
     * 我的充值记录.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function myOrderList(Request $request)
    {
        try {
            $order = Order::query()->with('configData')->select(['id', 'amount', 'diamond', 'created_at', 'config_id'])->where('user_id', Auth::$userId)->where('state', 1)->orderByDesc('id')->paginate();

            return Response::success($order);
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }

    /**
     * 获取角色列表.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function myRoleList(Request $request)
    {
        try {
            $order = UserRole::query()->where('user_id', Auth::$userId)->paginate();

            return Response::success($order);
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }
    /**
     * 添加角色
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addRole(Request $request){
        try {
            $role = UserRole::query()->create([
                'user_id' => Auth::$userId,
                'name'    => $request->post('name', ''),
                'sex'     => $request->post('sex', ''),
                'age'     => $request->post('age', ''),
                'star'    => $request->post('star', ''),
                'level'   => $request->post('level', ''),
            ]);
            return Response::success($role);
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }
    /**
     * 更新角色
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateRole(Request $request){
        try {
            $role = UserRole::query()->where('id',$request->post('id'))->where('user_id',Auth::$userId)->first();
            if (!$role){
                return Response::fail('没有该角色');
            }
            UserRole::query()->where('id',$request->post('id'))->where('user_id',Auth::$userId)->update([
                'name'    => $request->post('name', ''),
                'sex'     => $request->post('sex', ''),
                'age'     => $request->post('age', ''),
                'star'    => $request->post('star', ''),
                'level'   => $request->post('level', ''),
            ]);
            return Response::success();
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }

    /**
     * 删除该角色
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteRole(Request $request){
        try {
            $role = UserRole::query()->where('id',$request->post('id'))->where('user_id',Auth::$userId)->first();
            if (!$role){
                return Response::fail('没有该角色');
            }
            $role->delete();
            return Response::success();
        } catch (\Exception $exception) {
            LogHelper::exceptionLog($exception, $this->code);

            return Response::fail($exception->getMessage());
        }
    }
    public function parent()
    {
        if (empty(\user()->parent_id)) {
            return $this->success();
        }
        $parent = User::find(\user()->parent_id);

        return $this->success($parent);
    }

    // h5 绑定
    public function h5Bind()
    {
    }

    // h5 解绑
    public function h5ReBind()
    {
    }

    // 微信小程序 绑定
    public function miniProgramBind()
    {
    }

    // 微信小程序 解绑
    public function miniProgramReBind()
    {
    }

    // 手机号 绑定
    public function smsBind()
    {
    }

    // 手机号 解绑
    public function smsReBind()
    {
    }

    public function upload(Request $request)
    {
        try {
            $file = $request->file('file');
            $path = Storage::putFile('hb/images', $file);
            $path = save2Oss(storage_path("app/{$path}"), 'hb/images');

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