<?php

namespace App\Http\Controllers\User;

use App\Exceptions\AlertException;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Core\Auth;
use App\Models\Fpdx\ActivityModel;
use App\Models\Deed\FriendsModel;
use App\Models\Fpdx\PairModel;
use App\Models\User\InviteConfigModel;
use App\Models\User\SuperLikeModel;
use App\Services\Home\FeedService;
use App\Services\User\NoticeService;
use App\Services\User\PartnerService;
use App\Models\Deed\InvitationCardModel;
use App\Models\PartnerModel;
use App\Models\PraiseModel;
use App\Models\User\UserModel;
use App\Models\BuyInviteListModel;
use App\Models\BuyInviteModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Exceptions\JWTException;

/**
 * 卡片
 * Class PartnerController
 * @package App\Http\Controllers\User
 */
class PartnerController extends Controller
{
    /**
     * 上传一张卖室友卡片
     * @param  Request  $request
     * @throws \Exception
     */
    public function store(Request $request)
    {
    }

    /**
     * 更新卡片信息
     * @param  int  $partner_id
     * @param  array  $data
     */
    public function updatePartner(int $partner_id, array $data)
    {
        $partner = PartnerModel::findOrFail($partner_id);

        if (isset($data['voice'])) {
            $data['voice_check'] = 0;
            $data['is_commit_check'] = 1;
        }
        if (isset($data['photo_src'])) {
            $data['check_photo'] = 0;
            $data['is_commit_check'] = 1;
        }
        if (isset($data['photo_1'])) {
            $data['photo_1_check'] = 0;
            $data['is_commit_check'] = 1;
        }
        if (isset($data['photo_2'])) {
            $data['photo_2_check'] = 0;
            $data['is_commit_check'] = 1;
        }
        if (isset($data['photo_3'])) {
            $data['photo_3_check'] = 0;
            $data['is_commit_check'] = 1;
        }
        if (isset($data['photo_4'])) {
            $data['photo_4_check'] = 0;
            $data['is_commit_check'] = 1;
        }
        if (isset($data['is_commit_check']) && 1 == $data['is_commit_check']) {
            $ings = ActivityModel::getActivitys();
            $exists = PairModel::where([
                'uid' => $partner->uid,
                'stage_id' => $ings['ing'] ?: 0
            ])->exists();
            if ($exists) {
                $data['is_fpdx'] = 1;
            } else {
                $data['is_fpdx'] = 0;
            }
        }
        $data['update_at'] = time();
        $partner->fill($data);
        if (isset($data['sex']) && 1 == $partner->is_sell) {
            $user = UserModel::findOrFail($partner->uid);
            if ($partner->sex == 1) {
                Redis::zrem("fpdx:user:locations:sell:girl", $partner->uid);
                Redis::geoAdd("fpdx:user:locations:sell:boy", $user->lng, $user->lat, $partner->uid);
            } else {
                Redis::zrem("fpdx:user:locations:sell:boy", $partner->uid);
                Redis::geoAdd("fpdx:user:locations:sell:girl", $user->lng, $user->lat, $partner->uid);
            }
        }
        if (1 == $partner->is_sell && empty($partner->qq) && empty($partner->weixin)) {
            $partner->is_sell = 0;
            Redis::zrem("fpdx:user:locations:sell:boy", $partner->uid);
            Redis::zrem("fpdx:user:locations:sell:girl", $partner->uid);
        }
        if (-1 == $partner->is_sell && 1 == $partner->is_commit_check) {
            $partner->is_sell = 0;
            Redis::zrem("fpdx:user:locations:sell:boy", $partner->uid);
            Redis::zrem("fpdx:user:locations:sell:girl", $partner->uid);
        }
        $partner->save();
    }

    /**
     * 更新卡片信息接口
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function update(int $partner_id, Request $request)
    {
        $data = $request->only([
            'home',
            'address',
            'sex',
            'photo_src',
            'photo_1',
            'photo_2',
            'photo_3',
            'photo_4',
            'voice',
            'school',
            'qq',
            'weixin',
            'subject',
            'grade',
            'education',
            'height',
            'age',
            'star',
            'introduce',
            'expect',
            'allow',
            'auto_sell',
            'is_hide',
            'is_fpdx'
        ]);
        $ps = new PartnerService();
        $ps->updatePartner($partner_id, $data);
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 获取卡片信息
     * @param  int  $partner_id
     * @return array
     */
    public function getPartner(int $partner_id)
    {
        $uid = Auth::auth();

        /** @var PartnerModel $partner */
        $partner = PartnerModel::findOrFail($partner_id);
        $partner->black_at = $partner->black_at < time() ? 0 : $partner->black_at;

        try {
            /** @var PartnerModel $user */
            $user = UserModel::findOrfail($partner->uid, [
                'uid',
                'headimgurl',
                'nickname',
                'age',
                'star',
                'last_life',
                'why',
                'pair_voice',
                'identity_auth',
                'wx_auth',
                'qq',
                'weixin',
                'introduce',
                'expect',
                'height',
                'sex',
                'school',
                'address',
                'home',
                'tag_1',
                'tag_2',
                'tag_3',
                'tag_4',
                'login_at',
                'claim_tag',
                'work_state',
                'be_vip_at',
                'supvip_endat',
                'logoff_at',
                'bgcolor'
            ]);

            if ($inviteConf = InviteConfigModel::find($partner->uid)) {
                $user->task_photo = $inviteConf->task_photo;
                $user->task_question = $inviteConf->task_question;
                $user->task_sing = $inviteConf->task_sing;
                $user->task_question_data = $inviteConf->task_question_data ? true : false;
                $user->task_sing_data = $inviteConf->task_sing_data ? true : false;
            } else {
                $user->task_photo = false;
                $user->task_question = false;
                $user->task_sing = false;
                $user->task_question_data = false;
                $user->task_sing_data = false;
            }

            $user->invite_cnt = InvitationCardModel::where('invite_uid', $user->uid)->count();
            $partner->headimgurl = $user->headimgurl;
            $partner->nickname = $user->nickname;
        } catch (\Exception $e) {
            $user = null;
            $partner->headimgurl = null;
            $partner->nickname = null;
        }

        if ($uid != $partner->uid) {
            if (1 != $partner->check_photo) {
                unset($partner->photo_src);
            }
            if (1 != $partner->photo_1_check) {
                unset($partner->photo_1);
            }
            if (1 != $partner->photo_2_check) {
                unset($partner->photo_2);
            }
            if (1 != $partner->photo_3_check) {
                unset($partner->photo_3);
            }
            if (1 != $partner->photo_4_check) {
                unset($partner->photo_4);
            }
            if (1 != $partner->voice_check) {
                unset($partner->voice);
            }
            if (1 != $partner->introduce_check) {
                unset($partner->introduce);
                unset($partner->expect);
            }
            unset($partner->check_photo);
            unset($partner->photo_1_check);
            unset($partner->photo_2_check);
            unset($partner->photo_3_check);
            unset($partner->photo_4_check);
            unset($partner->voice_check);
            unset($partner->check_contact);
            unset($partner->introduce_check);
            unset($partner->qq);
            unset($partner->weixin);

            // 与self的关系处理
            $self = array(
                'friend' => false,
                'praise' => false,
                'invite' => false,
                'superlike' => false
            );
            $friend = FriendsModel::where([['uid', $uid], ['friend_uid', $partner->uid]])->first();
            if (collect($friend)->isEmpty()) {
                !empty($user->weixin) && $user->weixin = substr($user->weixin, 0, 1) . "****" . substr(
                    $user->weixin,
                    -1,
                    1
                );
                !empty($user->qq) && $user->qq = substr($user->qq, 0, 1) . "****" . substr($user->qq, -1, 1);
            }
            $self['friend'] = $friend;
            if (PraiseModel::where([['uid', $uid], ['partner_id', $partner->id], ['type', 1]])->exists()) {
                $self['praise'] = true;
            }
            if (
                InvitationCardModel::where([
                ['uid', $uid],
                ['invite_uid', $partner->uid],
                ['expired_at', '>', time()]
                ])->exists()
            ) {
                $self['invite'] = true;
            }
            if (SuperLikeModel::where([['uid', $uid], ['partner_id', $partner->id]])->exists()) {
                $self['superlike'] = true;
            }
            $partner->self = $self;
        }

        $partner->setAttribute('user', $user);

        $praise = PraiseModel::where([['partner_id', $partner->id], ['uid', $uid]])->first();

        $partner->praise = isset($praise->type) ? $praise->type : 0;

        $buyInviteListModel = new BuyInviteListModel();
        $inviteList = $buyInviteListModel->where([['partner_id', $partner->id], ['uid', $uid]])->first();

        if (!collect($inviteList)->isEmpty()) {
            $partner->invite_id = $inviteList->id;
            $buyInviteModel = new BuyInviteModel();
            $partner->invite_percent = $buyInviteModel->effectiveInvite($uid, $partner_id);
        }
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $partner
        ]);
    }

    /**
     * 上下架卡片
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function sell(int $partner_id, Request $request)
    {
        $this->validate($request, ['is_sell' => 'in:-1,0,1']);
        $is_sell = $request->input('is_sell');
        $ups = new PartnerService();
        $ups->sell($partner_id, $is_sell);
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 判断是否可上架
     */
    public function isCanSell()
    {
        $uid = Auth::auth();
        /** @var UserModel $user */
        $user = UserModel::findOrFail($uid);
        $isCanSell = false;
        if ($user->partner_id) {
            /** @var PartnerModel $partner */
            $partner = PartnerModel::findOrFail($user->partner_id);
            $ps = new PartnerService();
            if ($partner->black_at < time() && $ps->isCanSell($partner)) {
                $isCanSell = true;
            }
        }

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => array(
                'is_can_sell' => $isCanSell
            )
        );
    }


    /**
     * 通过用户获取卡片交友卡片信息
     * @param  int  $user_id
     * @return array
     */
    public function getPartnerByUser(int $user_id)
    {
        $uid = Auth::auth();
        /** @var PartnerModel $partner */
        $partner = PartnerModel::where('uid', $user_id)->firstOrFail();
        $partner->black_at = $partner->black_at < time() ? 0 : $partner->black_at;
        if ($uid == $user_id) {
            return $this->getPartner($partner->id);
        }
        $ps = new PartnerService();
        $partner = $ps->getUserSelf($user_id);

        // 与self的关系处理
        $self = array(
            'friend' => false,
            'praise' => false,
            'invite' => false,
            'superlike' => false
        );
        $friend = FriendsModel::where([['uid', $uid], ['friend_uid', $partner->uid]])->first();
        if (collect($friend)->isEmpty()) {
            !empty($partner->weixin) && $partner->weixin = substr(
                $partner->weixin,
                0,
                1
            ) . "****" . substr($partner->weixin, -1, 1);
            !empty($partner->qq) && $partner->qq = substr($partner->qq, 0, 1) . "****" . substr($partner->qq, -1, 1);
        }
        $self['friend'] = $friend;
        if (PraiseModel::where([['uid', $uid], ['partner_id', $partner->id], ['type', 1]])->exists()) {
            $self['praise'] = true;
        }
        if (
            InvitationCardModel::where([
            ['uid', $uid],
            ['invite_uid', $partner->uid],
            ['expired_at', '>', time()]
            ])->exists()
        ) {
            $self['invite'] = true;
        }
        if (SuperLikeModel::where([['uid', $uid], ['partner_id', $partner->id]])->exists()) {
            $self['superlike'] = true;
        }

        if (PraiseModel::where([['uid', $uid], ['partner_id', $partner->id], ['type', 1]])->exists()) {
            $praise = true;
        } else {
            $praise = false;
        }

        $partner->setAttribute("self", $self);
        $partner->setAttribute("praise", $praise);

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

    /**
     * 点赞／无感 对象卡片
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function thumb(int $partner_id, Request $request)
    {
        $uid = Auth::auth();

        $thumb = $request->get('thumb', null);

        $ps = new PartnerService();
        $data = $ps->thumb($uid, $partner_id, $thumb);

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

    /**
     * 超级喜欢某人
     * @param  int  $partner_id
     * @return array
     */
    public function superLike(int $partner_id)
    {
        $uid = Auth::auth();

        $ps = new PartnerService();
        $ps->superLike($uid, $partner_id);

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

    /**
     * 阅读超级喜欢信息
     * @param  int  $like_uid
     * @return array
     */
    public function readSuperlike(int $like_uid)
    {
        $uid = Auth::auth();
        $ns = new NoticeService();
        $ns->readSuperlike($uid, $like_uid);
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 阅读相互心动信息
     * @param  int  $eachlike_id
     * @return array
     * @throws AlertException
     */
    public function readEachlike(int $eachlike_id)
    {
        $uid = Auth::auth();
        $ns = new NoticeService();
        $ns->readEachLikeList($uid, $eachlike_id);
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 解锁喜欢我的卡片
     * @param  Request  $request
     * @param  int  $partner_id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws AlertException
     * @deprecated Partner/LockLikeMe
     */
    public function lockLikeme(Request $request, int $partner_id)
    {
        $uid = Auth::auth();
        $origin = $request->input('origin', 'supvip');
        if ($origin == 'app_sign') {
            $ps = new PartnerService();
            $ps->appLockLikeMe($uid, $partner_id);
        } else {
            $ps = new PartnerService();
            $ps->lockLikeme($uid, $partner_id);
        }
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 通过卡片id获取卡片信息
     * @param  int  $partner_id
     * @return array
     */
    public function getPartnerById(int $partner_id)
    {
        try {
            $uid = Auth::auth();
        } catch (JWTException $exception) {
            $uid = 0;
        }

        $fs = new FeedService();
        $data = $fs->getPartner($partner_id, $uid);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $data->toArray()
        ]);
    }

    /**
     * 通过卡片ids获取卡片信息
     * @param  Request  $request
     * @return array
     */
    public function getPartnerByIds(Request $request)
    {
        try {
            $uid = Auth::auth();
        } catch (JWTException $exception) {
            $uid = 0;
        }

        $ids = $request->post('ids', []);

        $fs = new FeedService();

        $datas = array();
        foreach ($ids as $partner_id) {
            $datas[] = $fs->getPartner($partner_id, $uid)->toArray();
        }
        return response(array(
            'code' => 200,
            'message' => 'success',
            'data' => $datas
        ));
    }

    /**
     * 通过uid获取卡片信息
     * @param  int  $user_id
     * @return array
     * @throws AlertException
     */
    public function getPartnerByUid(int $user_id)
    {
        $uid = Auth::auth();

        /** @var UserModel $user */
        $user = UserModel::findOrFail($user_id);
        if (0 == $user->partner_id) {
            throw new AlertException("未生成卡片", 401);
        }

        $fs = new FeedService();
        $data = $fs->getPartner($user->partner_id, $uid);

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $data
        );
    }
}
