<?php

namespace App\Services\Notice;

use App\Exceptions\AlertException;
use App\Exceptions\ApiException;
use App\Models\Common\NoticeManageModel;
use App\Models\Deed\InvitationCardModel;
use App\Models\Deed\NoticeReadModel;
use App\Services\App\ProfileService;
use App\Services\Service;

class ManageService extends Service
{
    /**
     * 获取某人某项配置
     * @param  int  $uid
     * @param  string  $key
     * @return int
     * @throws AlertException
     * @throws ApiException
     */
    public function getNoticeByKey2Int(int $uid, string $key): int
    {
        $profile = NoticeManageModel::where([
            ['uid', $uid],
            ['key', $key],
        ])->first();
        if (collect($profile)->isEmpty()) {
            $this->getNoticeByUser($uid);
            $profile = NoticeManageModel::where([
                ['uid', $uid],
                ['key', $key],
            ])->first();
            if (collect($profile)->isEmpty()) {
                throw new AlertException("错误的配置", 400);
            }

            return $profile->isopen;
        }

        return $profile->isopen;
    }

    /**
     * 获取某人的通知配置
     * @param  int  $uid
     * @return array
     * @throws \App\Exceptions\ApiException
     */
    public function getNoticeByUser(int $uid)
    {
        $pfs = new ProfileService();
        $manages = json_decode($pfs->get('notice_manage'), true) ?? [];
        foreach ($manages as $key => &$manage) {
            $profile = NoticeManageModel::firstOrCreate([
                'uid' => $uid,
                'key' => $manage['key'],
            ], [
                'created_at' => time(),
                'updated_at' => time(),
                'group' => $manage['group'],
                'isopen' => $manage['isopen'] ?? 0,
            ]);
            if ('app' == $manage['group']) {
                unset($manages[$key]);
            } else {
                $manage["isopen"] = $profile->isopen;
            }
        }

        return $manages;
    }

    /**
     * 获取某人某项配置
     * @param  int  $uid
     * @param  string  $key
     * @return bool
     * @throws AlertException
     * @throws ApiException
     */
    public function getNoticeByKey(int $uid, string $key): bool
    {
        $profile = NoticeManageModel::where([
            ['uid', $uid],
            ['key', $key],
        ])->first();
        if (collect($profile)->isEmpty()) {
            $this->getNoticeByUser($uid);
            $profile = NoticeManageModel::where([
                ['uid', $uid],
                ['key', $key],
            ])->first();
            if (collect($profile)->isEmpty()) {
                throw new AlertException("错误的配置", 400);
            }
            if ($profile->isopen == 1) {
                return true;
            }

            return false;
        }
        if ($profile->isopen == 1) {
            return true;
        }

        return false;
    }

    /**
     * 更新某人配置
     * @param  int  $uid
     * @param  string  $key
     * @param  null  $open  0|1 无论当前值为什么，都修改为该值
     * @return bool
     * @throws AlertException
     * @throws ApiException
     */
    public function updateNoticeByKey(int $uid, string $key, $open = null)
    {
        $profiles = $this->getNoticeByUser($uid);
        $nm = new NoticeManageModel();
        $profile = $nm->where([
            ['uid', $uid],
            ['key', $key],
        ])->first();
        if (collect($profile)->isEmpty()) {
            throw new AlertException("错误的配置", 400);
        }
        $profile->isopen = abs($profile->isopen - 1);
        if (!is_null($open)) {
            $profile->isopen = $open;
        }
        $profile->save();

        return true;
    }

    /**
     * 更新某人配置
     * @param  int  $uid
     * @param  string  $group
     * @param  int  $open
     * @return bool
     * @throws AlertException
     * @throws \App\Exceptions\ApiException
     */
    public function updateNoticeByGroup(int $uid, string $group, int $open)
    {
        $profiles = $this->getNoticeByUser($uid);
        $nm = new NoticeManageModel();
        if (
            !$profile = $nm->where([
            ['uid', $uid],
            ['group', $group],
            ])->exists()
        ) {
            throw new AlertException("错误的配置", 400);
        }
        $nm->where([
            ['uid', $uid],
            ['group', $group],
        ])->update(['isopen' => $open]);

        return true;
    }


    public function inviteNoticeLog($invite_id, $notice_type)
    {
        $invate = InvitationCardModel::find($invite_id);
        $invate->notice_type = $notice_type;
        $invate->save();
    }


    public function noticeIncrRead($to_uid)
    {
        if (NoticeReadModel::where('uid', $to_uid)->first()) {
            NoticeReadModel::where('uid', $to_uid)->increment('unread_cnt');
        } else {
            NoticeReadModel::create([
                'uid' => $to_uid,
                'unread_cnt' => 1,
            ]);
        }
    }
}
