<?php

namespace App\Http\Controllers\User;

use App\Exceptions\AlertException;
use App\Http\Controllers\Core\Auth;
use App\Http\Requests\UserRequest;
use App\Jobs\StoreSelfPartnerJob;
use App\Managers\UserManager;
use App\Models\Fpdx\WxkfModel;
use App\Models\Log\AppSignModel;
use App\Models\NoticeModel;
use App\Models\User\AuthKey;
use App\Services\Auth\AuthKeyService;
use App\Services\Goodnight\UserService;
use App\Services\User\PartnerService;
use App\Services\User\ProfileService;
use App\Services\User\SignService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;
use App\Models\User\UserModel;
use App\Models\PartnerModel;
use App\Models\TagModel;

/**
 * 用户基础设置
 * Class ProfileController
 * @package App\Http\Controllers\User
 */
class ProfileController extends Controller
{
    /**
     * 修改某人的用户信息
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws \AlicFeng\IdentityCard\Exception\BirthdayException
     * @deprecated User/UpdateProfile
     */
    public function update(UserRequest $request)
    {
        $uid = Auth::auth();
        /** @var UserModel $user */
        $user = UserModel::findOrFail($uid);
        // 更新基础数据
        $extData = $request->only(['nickname', 'headimgurl', 'sex']);
        if (!empty($extData)) {
            $pService = new ProfileService();
            $pService->updateUser($user, $extData);
        }

        $app = $request->get('model') ?? "fpdx";
        switch ($app) {
            case 'goodnight': # 互道晚安
                $extData = $request->only(['cover', 'like_sex', 'like_tone_1', 'like_tone_2', 'like_tone_3', 'voice']);
                if (!empty($extData)) {
                    $guService = new UserService();
                    $guService->updateUser($user, $extData);
                }
                break;
            case 'fpdx': # 72小时恋爱体验
            default:     # 基础信息
                $extData = $request->except(array(
                    'nickname',
                    'headimgurl',
                    'sex',
                    'gold_flower',
                    'red_flower',
                    'task_type',
                    'wx_auth',
                    'identity_auth',
                    'wxkf',
                    'login_at',
                    'created_at',
                    'phone',
                ));
                if (!empty($extData)) {
                    $pService = new ProfileService();
                    $pService->updateUser($user, $extData);
                }
                break;
        }

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

    /**
     * 修改标签
     * @param  Request  $request
     * @return array
     * @deprecated User/ToggleTag
     */
    public function toggleTag(Request $request)
    {
        $this->validate($request, ['tag_id' => 'required', 'group' => 'required']);
        $tag_id = $request->post('tag_id');
        $group = $request->post('group');
        $uid = Auth::auth();
        $ps = new ProfileService();
        $ps->toggleTag($uid, $tag_id, $group);
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 获取用户标签
     * @return array
     */
    public function getTags()
    {
        $uid = Auth::auth();
        $user = UserModel::find($uid);
        $tagModel = new TagModel();
        $tags = $tagModel->getAllTagByUser($user);
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $tags
        );
    }

    /**
     * 选择封面
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @deprecated User/SelectCover
     */
    public function selectCover(Request $request)
    {
        $uid = Auth::auth();
        $this->validate($request, [
            'field' => 'required|in:photo_1,photo_2,photo_3,photo_4'
        ]);
        $user = UserModel::findOrFail($uid);
        /** @var UserModel $user */

        $field = $request->input('field');
        if (empty($user->{$field})) {
            throw new AlertException("参数错误", 101);
        }

        $identity_auth = $user->identity_auth;
        if (!empty($identity_auth)) {
            $identity_auths = explode(",", $identity_auth);
            array_walk($identity_auths, function (&$value) use ($field) {
                if ($value == "photo_src") {
                    $value = $field;
                } elseif ($value == $field) {
                    $value = "photo_src";
                }
            });
            $identity_auth = implode(",", $identity_auths);
            $user->identity_auth = $identity_auth;
        }

        $tmp = $user->photo_src;
        $user->photo_src = $user->{$field};
        $user->{$field} = $tmp;
        $user->save();
        $ps = new PartnerService();
        $ps->selectCover($user->partner_id, $field);
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 删除照片
     * @param  Request  $request
     * @return array
     * @throws Exception
     * @deprecated User/DeletePhotos
     */
    public function deletePhotos(Request $request)
    {
        $this->validate($request, [
            'field' => 'required|in:photo_src,photo_1,photo_2,photo_3,photo_4'
        ]);
        $uid = Auth::auth();
        $pfs = new ProfileService();
        $pfs->deletePhoto($uid, $request->post('field'));
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 获取用户信息
     * @param  Request  $request
     * @return array
     * @deprecated User/Profile
     */
    public function user(Request $request)
    {
        $uid = Auth::auth();
        $app = $request->get('model') ?? "fpdx";
        $manager = new UserManager();
        $user = $manager->profile($uid, $app);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $user,
        ]);
    }

    /**
     * 通过uid获取某人信息
     * @param  int  $uid
     * @return array
     */
    public function userByUid(int $uid)
    {
        /** @var UserModel $user */
        $user = UserModel::findOrFail($uid);
        try {
            /** @var PartnerModel $partner */
            $partner = PartnerModel::findOrFail($user->partner_id);
            if (1 != $partner->check_photo) {
                unset($user->photo_src);
            }
            if (1 != $partner->photo_1_check) {
                unset($user->photo_1);
            }
            if (1 != $partner->photo_2_check) {
                unset($user->photo_2);
            }
            if (1 != $partner->photo_3_check) {
                unset($user->photo_3);
            }
            if (1 != $partner->photo_4_check) {
                unset($user->photo_4);
            }
            if (1 != $partner->voice_check) {
                unset($user->voice);
            }
            $user->black_at = $partner->black_at < time() ? 0 : $partner->black_at;
            $user->is_sell = $partner->is_sell;
        } catch (Exception $exception) {
        }

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

    /**
     * 创建交友卡片
     * @param  Request  $request
     * @return array
     * @throws Exception
     * @deprecated User/StoreSelfPartner
     */
    public function storeSelfPartner(Request $request)
    {
        $uid = Auth::auth();
        try {
            $user = UserModel::findOrFail($uid);
            if ($user->partner_id > 0) {
                return array(
                    'code' => 200,
                    'message' => 'success',
                    'data' => $user
                );
            }
            $partnerModel = new PartnerModel();
            $data = $user->toArray();
            $data['media_id'] = $request->get('media_id', "");
            $data['secret'] = bin2hex(openssl_random_pseudo_bytes(4));
            $partner = $partnerModel->fill($data);
            $partner->created_at = time();
            if (!empty($partner->qq) || !empty($partner->weixin)) {
                $partner->is_sell = 1;
            }

            if (!empty($partner->photo_src)) {
                $partner->check_photo = 0;
                $partner->is_commit_check = 1;
            }
            if (!empty($partner->voice)) {
                $partner->voice_check = 0;
                $partner->is_commit_check = 1;
            }
            if (!empty($partner->photo_1)) {
                $partner->photo_1_check = 0;
                $partner->is_commit_check = 1;
            }
            if (!empty($partner->photo_2)) {
                $partner->photo_2_check = 0;
                $partner->is_commit_check = 1;
            }
            if (!empty($partner->photo_3)) {
                $partner->photo_3_check = 0;
                $partner->is_commit_check = 1;
            }
            if (!empty($partner->photo_4)) {
                $partner->photo_4_check = 0;
                $partner->is_commit_check = 1;
            }
            if (Redis::exists("storeselfpartner:{$uid}")) {
                throw new AlertException("请求频繁", 104);
            }
            Redis::setex("storeselfpartner:{$uid}", 5, true);
            if ($partner->save()) {
                $user->partner_id = $partner->id;
                $user->save();
                // 系统通知
                $sex = 1 == $partner->sex ? "小姐姐" : "小哥哥";
                NoticeModel::create([
                    'uid' => $uid,
                    'title' => '交友卡片上传完成',
                    'content' => "你的交友卡片已经完成啦！现在可以去交友大厅邀请你心动的{$sex}啦~ ",
                    'type' => 5,
                    'type_id' => 0,
                    'create_at' => time(),
                    'update_at' => time(),
                    'tab_content' => '进入大厅',
                    'tab_url' => '/pages/index/index',
                ]);
            }
            Redis::del(["storeselfpartner:{$uid}"]);
            StoreSelfPartnerJob::dispatch($uid);
        } catch (Exception $e) {
            if (Redis::exists("storeselfpartner:{$uid}")) {
                Redis::del(["storeselfpartner:{$uid}"]);
            }
            throw $e;
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $user
        );
    }

    /**
     * 照片活体验证对比
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function facematch(Request $request)
    {
        $uid = Auth::auth();
        $this->validate($request, [
            'field' => "required",
            'face_url' => 'required'
        ]);
        $pfs = new ProfileService();
        $pfs->fatchmatch($uid, $request->post('face_url'), $request->post('field'));
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => array(
                'is_pass' => true
            )
        ]);
    }

    /**
     * 微信验证
     * @param  Request  $request
     * @return array
     * @throws Exception
     */
    public function wxverify(Request $request)
    {
        $this->validate($request, [
            'wxid' => 'required',
            'kf' => 'required'
        ]);
        $wxid = $request->post('wxid');
        $kf = $request->post('kf');
        $uid = Auth::auth();
        try {
            $aks = new AuthKeyService();
            $aks->bindKey($uid, $wxid, 'wxid');
        } catch (Exception $exception) {
            $auth = AuthKey::where([
                ['uid', $uid],
                ['auth_type', 'wxid']
            ])->firstOrFail();
            $wxid = $auth->auth_key;
        }

        $psf = new ProfileService();
        return $psf->wxverify($uid, $wxid, $kf);
    }

    /**
     * 微信验证申请人工审核
     * @param  Request  $request
     * @return array
     * @throws Exception
     */
    public function wxverifyByArtifical(Request $request)
    {
        Auth::auth();
        $this->validate($request, [
            'wxid' => 'required',
            'kf' => 'required'
        ]);
        $wxid = $request->get('wxid');
        $kf = $request->get('kf');
        $auth = AuthKey::where('auth_key', $wxid)->firstOrFail();
        $user = UserModel::findOrFail($auth->uid);
        if ($user->wx_auth == 1) {
            return array(
                'code' => 200,
                'message' => 'success'
            );
        }

        $wxkf = WxkfModel::where('wxid', $kf)->firstOrFail();
        $url = "https://m.fenpeiduixiang.com/fpdx-wxauth/wxverify.html?uid={$user->uid}&wxid={$wxid}&kf={$kf}";
        $content = [
            'first' => [
                'value' => "用户微信认证失败:\n 原因: 未能获得微信号",
            ],
            'keyword1' => [
                'value' => "\nUID:{$user->uid}\n用户昵称:{$user->nickname}\n审核客服:{$wxkf->nickname}",
            ],
            'keyword2' => [
                'value' => "\n微信id:{$wxid}\n 点此人工认证：\n{$url}",
            ],
            'remark' => [
                'value' => "点此人工认证",
                "color" => "#FF7E98",
            ],
        ];
        $psf = new ProfileService();
        $psf->wxverifyWarn($content, $url);
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }


    /**
     * app签到
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws Exception
     */
    public function appSigns(Request $request)
    {
        $uid = Auth::auth();
        try {
            $platform = $request->header('platform');
            $signService = new SignService();
            $signService->sign($uid, $platform);
            $flower = $signService->rewardFlower($uid);
        } catch (Exception $e) {
            $flower = 0;
        }

        if (AppSignModel::where('uid', $uid)->where('date', date('Y-m-d'))->first()) {
            return response([
                'code' => 410001,
                'message' => '今天已经签到，请明天再来'
            ]);
        }
        \DB::beginTransaction();
        try {
            AppSignModel::create([
                'uid' => $uid,
                'created_at' => time(),
                'date' => date('Y-m-d')
            ]);
            UserModel::where('uid', $uid)->increment('app_like_unlock_count');
            \DB::commit();
            return response([
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'app_sign_at' => mktime(0, 0, 0) + 86400,
                    'flower' => $flower,
                ]
            ]);
        } catch (Exception $e) {
            \DB::rollBack();
            return response([
                'code' => 40910,
                'message' => '您点的太快啦'
            ]);
        }
    }
}
