<?php

namespace frontend\modules\api\controllers;

use common\components\AjaxException;
use common\services\MailService;
use frontend\modules\api\components\BaseAdminController;

class MailController extends BaseAdminController
{
    public function actionList(int $current = 1, int $page = 10)
    {
        $query = MailService::getMailAllQuery()
            ->limit($page)
            ->offset(($current - 1) * $page);
        //排序
        $this->initSequence($query);
        $query = $this->addConditionToQuery("receiver", $query, true);
        $query = $this->addConditionToQuery("receiver_name", $query, true);
        $query = $this->addStartEndConditionToQuery("start_time", $query);
        $query = $this->addConditionToQuery("case_type", $query);
        $query = $this->addConditionToQuery("status", $query);
        $data['data'] = $query->all();
        $data['total'] = $query->count();
        return $this->asJson($data);
    }

    public function actionMyList(int $current = 1, int $page = 10)
    {
        $query = MailService::getMailQuery()
            ->limit($page)
            ->offset(($current - 1) * $page);
        //排序
        $this->initSequence($query);
        $query = $query->andWhere(["receiver" => $this->userInfo->username]);
        $query = $this->addStartEndConditionToQuery("start_time", $query);
        $query = $this->addConditionToQuery("case_type", $query);
        $query = $this->addConditionToQuery("status", $query);
        $data['data'] = $query->all();
        $data['total'] = $query->count();
        return $this->asJson($data);
    }

    /**
     * @throws AjaxException
     */
    public function actionReadMessage($id)
    {
        MailService::readMessage($id, $this->userInfo);
        return $this->asJson();
    }

    /**
     * @throws AjaxException
     */
    public function actionDelete($id)
    {
        MailService::delete($id, $this->userInfo);
        return $this->asJson();
    }

    public function actionGetUnreadMessagesNumber()
    {
        $data = MailService::getUnreadMessagesNumber($this->userInfo);
        return $this->asJson($data);
    }
}