<?php

namespace App\Services\Share;

use App\Exceptions\AlertException;
use App\Models\Share\PopularitySharehelpModel;
use App\Models\User\UserModel;
use App\Models\User\UserSysTagModel;
use App\Services\Service;
use Illuminate\Support\Facades\DB;

class PopularitySharehelpService extends Service
{
    /**
     * 人气值分享助力
     * 一天能为别人助力2次，一天内不能重复对同一好友助力一天被助力上限为50次。一个老用户+2h，新用户+10h
     * @param  int  $share_uid
     * @param  int  $help_uid
     * @return array
     * @throws AlertException
     */
    public function check(int $share_uid, int $help_uid)
    {
        $shareUser = UserModel::findOrFail($share_uid);
        if ($share_uid == $help_uid) {
            throw new AlertException("不能为自己助力", 103);
        }
        $isnew = 0;
        $cnt = PopularitySharehelpModel::where([
            ['help_uid', $help_uid],
            ['created_at', '>', mktime(0, 0, 0)],
        ])->count();
        if ($cnt > 0) {
            $isnew = 1;
        }
        if (2 <= $cnt) {
            throw new AlertException("今日助力次数已用完", 101);
        }
        if (
            PopularitySharehelpModel::where([
            ['share_uid', $share_uid],
            ['help_uid', $help_uid],
            ['created_at', '>', mktime(0, 0, 0)],
            ])->exists()
        ) {
            throw new AlertException("你今日已经帮TA助力了", 102);
        }
        if (
            50 <= PopularitySharehelpModel::where([
                ['share_uid', $share_uid],
                ['created_at', '>', mktime(0, 0, 0)],
            ])->count()
        ) {
            throw new AlertException("今日被助力次数到上限", 104);
        }

        $user = UserModel::findOrFail($help_uid);
        if ($user->created_at->timestamp > time() - 300) {
            $isnew = 1;
        }
        $add_at = (10 + 2 * $isnew) * 3600;
        DB::beginTransaction();
        try {
            $systag = UserSysTagModel::firstOrCreate(['uid' => $shareUser->uid], ['popularity_share_end_at' => 0]);
            if ($systag->popularity_share_end_at < time()) {
                $systag->popularity_share_end_at = time() + $add_at;
            } else {
                $systag->popularity_share_end_at += $add_at;
            }
            $systag->save();
            DB::table('kdgx_fpdx_popularity_sharehelp')->insert([
                'created_at' => time(),
                'share_uid' => $share_uid,
                'help_uid' => $help_uid,
                'end_at' => $systag->popularity_share_end_at,
                'helpuid_type' => $isnew,
            ]);
            DB::commit();
            try {
                $ns = new NoticeService();
                $ns->popularitySharehelp2ShareUser($share_uid, ['help_uid' => $help_uid, 'isnew' => $isnew]);
                $ns->popularitySharehelp2HelpUser($help_uid, ['share_uid' => $share_uid, 'isnew' => $isnew]);
            } catch (\Exception $exception) {
            }

            return array(
                'user' => [
                    'nickname' => $shareUser->nickname,
                ],
            );
        } catch (\Exception $exception) {
            DB::rollBack();
            throw $exception;
        }
    }

    /**
     * 助力页概览
     * @param  int  $uid
     * @return array
     */
    public function helpOverView(int $uid)
    {
        $systag = UserSysTagModel::firstOrCreate(['uid' => $uid], ['popularity_share_end_at' => 0]);
        $help_cnt = PopularitySharehelpModel::where('share_uid', $uid)->count();
        $new_cnt = PopularitySharehelpModel::where([['share_uid', $uid], ['helpuid_type', 1]])->count();

        return array(
            'end_at' => $systag->popularity_share_end_at,
            'help_cnt' => $help_cnt,
            'new_cnt' => $new_cnt,
        );
    }

    /**
     * 加持中的助力
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function inglist(int $uid, array $pages): array
    {
        $datas = PopularitySharehelpModel::where([
            ['share_uid', $uid],
            ['end_at', ">", time()],
        ])->orderBy('id', 'asc')->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $users = UserModel::whereIn('uid', $datas->pluck('help_uid'))->get(['uid', 'nickname', 'headimgurl']);
        $users = array_column($users->toArray(), null, 'uid');
        foreach ($datas as &$data) {
            $data->end_at = min($data->end_at - time(), (2 + 8 * $data->helpuid_type) * 3600);
            $data->total_time = (2 + 8 * $data->isnew) * 3600;
            $data->user = $users[$data->help_uid];
        }
        if ($datas->count() < $pages['limit']) {
            $total = (($pages['page'] - 1) * $pages['limit']) + $datas->count();
        } else {
            $total = PopularitySharehelpModel::where([['share_uid', $uid], ['end_at', '>', time()]])->count();
        }

        return [
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas,
        ];
    }

    /**
     * 失效的助力
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function historylist(int $uid, array $pages): array
    {
        $datas = PopularitySharehelpModel::where([['share_uid', $uid], ['end_at', '<=', time()]])
            ->orderBy('id', 'desc')->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $users = UserModel::whereIn('uid', $datas->pluck('help_uid'))->get(['uid', 'nickname', 'headimgurl']);
        $users = array_column($users->toArray(), null, 'uid');
        foreach ($datas as &$data) {
            $data->total_time = (2 + 8 * $data->helpuid_type) * 3600;
            $data->user = null;
            isset($users[$data->help_uid]) && $data->user = $users[$data->help_uid];
        }
        if ($datas->count() < $pages['limit']) {
            $total = (($pages['page'] - 1) * $pages['limit']) + $datas->count();
        } else {
            $total = PopularitySharehelpModel::where([['share_uid', $uid], ['end_at', '>', time()]])->count();
        }

        return [
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas,
        ];
    }
}
