<?php

namespace App\Http\Controllers\Admin;

use App\Events\BlackUser;
use App\Exceptions\AlertException;
use App\Http\Resources\Admin\User\BlackCollection;
use App\Models\BlackListModel;
use App\Models\PartnerModel;
use App\Models\RiskListModel;
use App\Models\User\UserModel;
use App\Http\Controllers\Controller;
use App\Models\User\AuthKey;
use App\Models\Wxkf\UserInfoModel;
use App\Services\Partner\NoticeService;
use App\Services\User\PartnerService;
use App\Services\User\ProfileService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class UserController extends Controller
{
    /**
     * 搜索用户
     * @param  Request  $request
     * @return array
     */
    public function search(Request $request)
    {
        $this->validate($request, [
            'content' => 'required',
        ]);
        $content = $request->input('content');
        if (is_int(strpos($content, 'uid'))) {
            $uid = substr($content, 4);
            $where = ['uid' => $uid];
        } elseif (is_int(strpos($content, 'phone'))) {
            $phone = substr($content, 6);
            $where = ['phone' => $phone];
        } elseif (is_int(strpos($content, 'weixin'))) {
            $weixin = substr($content, 7);
            $where = ['weixin' => $weixin];
        } elseif (is_int(strpos($content, 'cid'))) {
            $partner_id = substr($content, 4);
            $where = ['partner_id' => $partner_id];
        } else {
            return response([
                'code' => 422,
                'message' => '搜索格式：uid=xxx,phone=xx,weixin=xxx'
            ]);
        }
        $users = UserModel::where($where)->limit(10)->get();
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $users
        ]);
    }

    /**
     * 人工微信认证
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function wxverify(Request $request)
    {
        $this->validate($request, [
            'user_id' => 'required',
            'wx_alias' => 'required',
            'kf' => 'required'
        ]);

        $user_id = $request->post('user_id');
        $wx_alias = $request->post('wx_alias');
        $auth = AuthKey::where([['uid', $user_id], ['auth_type', 'wxid']])->first();
        if (!collect($auth)->isEmpty()) {
            UserInfoModel::where('wxid', $auth->auth_key)->whereNull('wx_alias')->update(['wx_alias' => $wx_alias]);
        } else {
            throw new AlertException("该用户未绑定wxid", 101);
        }

        $user = UserModel::find($user_id);
        $before_auth = 0;
        $after_auth = 0;
        if ($user->identity_auth && $user->wx_auth == 1) {
            $before_auth = 1;
        }

        if ($user->wx_auth == 1) {
            return array(
                'code' => 200,
                'message' => 'success',
            );
        }
        $user->wx_auth = 1;
        $user->weixin = $wx_alias;
        $ps = new PartnerService();
        $ps->updatePartner($user->partner_id, ['weixin' => $wx_alias]);
        // 发送审核通过通知
        $wxkf = $request->post('kf');
        $kfmsg = array(
            'task_type' => 1,
            'task_dict' => array(
                'wxid_to' => $auth->auth_key,
                'at_list' => "",
                'msg_list' => array(
                    [
                        'msg_type' => 1,
                        'msg' => "恭喜你已完成微信认证，现在你可以回到小程序向喜欢的ta发起“心动邀请”啦。补全信息会帮助认识彼此，同时将获得更高的曝光度。\n\n小遇祝你早日脱单哦！加油~\n\n👇👇👇👇👇"
                    ],
                    [
                        'msg_type' => 3,
                        'msg' => "https://oss.pocketuniversity.cn/media/2019-01-09/5c35d017d6771.png"
                    ]
                )
            )
        );
        Redis::sadd("wehub:task:list:{$wxkf}", [json_encode($kfmsg)]);

        if ($user->identity_auth && $user->wx_auth == 1) {
            $after_auth = 1;
        }
        // 发送认证通知
        try {
            if ($before_auth == 0 && $after_auth == 1) {
                $ns = new NoticeService();
                $ns->authenticationSuccess($user->uid);
            }
        } catch (\Exception $e) {
        }
        return response([
            'code' => 200,
            'message' => 'success',
        ]);
    }

    /**
     * 修改用户信息
     * @param  int  $uid
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function update(int $uid, Request $request)
    {
        /** @var UserModel $user */
        $user = UserModel::findOrFail($uid);

        $data = $request->input();

        $psf = new ProfileService();
        $psf->updateUser($user, $data);

        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 获取用户信息
     * @param  int  $uid
     * @return array
     */
    public function show(int $uid)
    {
        $user = UserModel::findOrFail($uid);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $user
        ]);
    }


    /**
     *
     * @param  Request  $request
     * @return BlackCollection
     */
    public function blackList(Request $request)
    {
        $blacks = BlackListModel::when($request->filled('uid'), function ($query) use ($request) {
            /** @var Builder $query */
            return $query->where('account', $request->uid);
        })->when($request->filled('type'), function ($query) use ($request) {
            /** @var Builder $query */
            return $query->where('type', $request->type);
        })->when($request->filled('state'), function ($query) use ($request) {
            /** @var Builder $query */
            return $query->where('state', $request->state);
        })->paginate($request->get('pre_page', 20));
        foreach ($blacks as $black) {
            $black->user;
        }
        return new BlackCollection($blacks);
    }


    /**
     * 拉入黑名单
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function createBlack(Request $request)
    {
        $this->validate($request, [
            'type' => 'required|in:msy,fpdx,all,goodnight,chat,game,home,account',
            'state' => 'required|integer',
        ]);

        switch ($request->state) {
            case "1":
                $end_time = mktime(24, 0, 0) + 7 * 24 * 3600;
                break;
            case "2":
                $end_time = mktime(24, 0, 0) + 30 * 24 * 3600;
                break;
            case "3":
                $end_time = 1893427200;
                break;
        }
        $account_type = $request->input('account_type', 'uid');
        $account = $request->input('account', $request->input('uid'));
        $data = $request->all();
        $data['end_at'] = $end_time;
        $data['account_type'] = $account_type;
        $data['account'] = $account;
        $blacks = BlackListModel::create($data);

        // 永久封禁
        if ($account_type == 'uid' && $request->type == 'all') {
            $user = UserModel::find($account);
            $user->headimgurl = 'https://oss.pocketuniversity.cn/media/2019-08-14/5d53e27a8d81e.png';
            $user->save();

            // 封禁卡片
            if ($user->partner_id) {
                $partner = PartnerModel::find($user->partner_id);
                $partner->is_sell = -1;
                $partner->black_at = $end_time;
                $partner->save();
            }

            // 加入风险帐号列表
            RiskListModel::create([
                'uid' => $user->uid,
                'weixin' => $user->weixin,
                'qq' => $user->qq,
                'phone' => $user->phone,
            ]);


            // 手机号码封禁
            if ($request->state == 3) {
                if ($user->phone) {
                    BlackListModel::create([
                        'type' => 'all',
                        'account_type' => 'phone',
                        'account' => $user->phone,
                        'end_at' => 1893427200,
                        'state' => 3
                    ]);
                }
            }
        }

        if ($account_type == 'uid') {
            // 封禁事件
            event(new BlackUser($account, $end_time, $data['type']));
        }

        return response([
            'code' => 200,
            'message' => 'OK',
            'blacks' => $blacks
        ]);
    }


    public function deleteBlack($id)
    {
        $black = BlackListModel::findOrFail($id);
        $black->delete();
        return response([
            'code' => 200,
            'message' => 'OK',
        ]);
    }
}
