<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\OperationNotice;
use app\common\model\UserNoticeRead;
use Webman\Http\Request;
use support\Response;

class Notice extends MobileBase
{
    /** 公告列表：公开接口，无需 auth-token / user-token */
    protected array $noNeedLogin = ['noticeList'];

    protected array $noNeedAuthToken = ['noticeList'];

    public function noticeList(Request $request): Response
    {
        $response = $this->initializeMobile($request);
        if ($response !== null) {
            return $response;
        }
        $page = $this->intValue($request->input('page', 1), 1);
        $pageSize = $this->intValue($request->input('page_size', 20), 20);

        $paginate = OperationNotice::where('status', 1)->order('id', 'desc')->paginate([
            'page' => $page,
            'list_rows' => $pageSize,
        ]);

        $popoutNoticeIds = [];
        foreach ($paginate->items() as $row) {
            if ($this->intValue($row->notice_type, 0) === 1) {
                $popoutNoticeIds[] = $row->id;
            }
        }
        $readMap = [];
        $userId = ($this->auth && $this->auth->isLogin()) ? $this->auth->id : 0;
        if ($userId > 0 && $popoutNoticeIds !== []) {
            $readRows = UserNoticeRead::where('user_id', $userId)->whereIn('notice_id', $popoutNoticeIds)->column('notice_id');
            $readMap = array_flip($readRows);
        }

        $list = [];
        foreach ($paginate->items() as $row) {
            $isPopout = $this->intValue($row->notice_type, 0) === 1;
            $list[] = [
                'notice_id' => $row->id,
                'title' => $row->title,
                'content' => $row->content,
                'notice_type' => $isPopout ? 'popout' : 'silent',
                'must_confirm' => $isPopout,
                'is_read' => $isPopout && isset($readMap[$row->id]),
                'publish_time' => $row->publish_at,
            ];
        }

        return $this->mobileSuccess(['list' => $list]);
    }

    public function noticeConfirm(Request $request): Response
    {
        $response = $this->initializeMobile($request);
        if ($response !== null) {
            return $response;
        }
        $noticeId = $this->intValue($request->input('notice_id', 0), 0);
        if ($noticeId < 1) {
            return $this->mobileError(1001, 'Missing parameters');
        }
        $notice = OperationNotice::where('id', $noticeId)->where('status', 1)->find();
        if (!$notice) {
            return $this->mobileError(2004, 'Notice does not exist');
        }
        if ($this->intValue($notice->notice_type, 0) !== 1) {
            return $this->mobileError(2004, 'Notice does not require confirmation');
        }

        $readRow = UserNoticeRead::where('user_id', $this->auth->id)->where('notice_id', $noticeId)->find();
        $now = time();
        if ($readRow) {
            $readRow->read_at = $now;
            if ($this->intValue($readRow->confirmed, 0) !== 1) {
                $readRow->confirmed = 1;
            }
            $readRow->save();
        } else {
            UserNoticeRead::create([
                'user_id' => $this->auth->id,
                'notice_id' => $noticeId,
                'confirmed' => 1,
                'read_at' => $now,
                'create_time' => $now,
            ]);
        }
        return $this->mobileSuccess([
            'notice_id' => $noticeId,
            'confirmed' => true,
            'confirm_time' => $now,
        ]);
    }

    private function intValue($value, int $default): int
    {
        $result = filter_var($value, FILTER_VALIDATE_INT);
        if ($result === false) {
            return $default;
        }
        return $result;
    }
}

