<?php

namespace common\services;

use common\components\AjaxException;
use common\models\AccidentCases;
use common\models\BaseUser;
use common\models\Mail;
use Yii;
use yii\db\ActiveQuery;

class MailService
{
    /**
     * @return ActiveQuery
     */
    public static function getMailQuery(): ActiveQuery
    {
        return Mail::find()->where([">=", "status", 0]);
    }

    public static function getMailAllQuery(): ActiveQuery
    {
        return Mail::find()->where([">=", "status", 0]);
    }


    public static function sendCommitMail($model, $remark): void
    {
        self::sendMail($model, "提交审核", $remark);
    }

    public static function sendRefuseMail($model, $remark): void
    {
        self::sendMail($model, "退回", $remark);
    }

    public static function getUnreadMessagesNumber($userInfo): int
    {
        /** @var  $userInfo BaseUser */
        $redis = Yii::$app->redis;
        $redisKey = "unreadMessagesNumber_" . $userInfo->username;
        $number = $redis->get($redisKey);
        if (!$number) {
            $query = MailService::getMailQuery();
            $number = $query->andWhere(["receiver" => $userInfo->username, "status" => 0])->count();
            $redis->set($redisKey, $number);
            $redis->expire($redisKey, 86400); //  86400
        }
        return (int)$number;
    }

    /**
     * @throws AjaxException
     */
    public static function readMessage($id, $userInfo): void
    {
        $mail = Mail::findOne(["id" => $id, "receiver" => $userInfo->username]);
        if (!$mail) {
            throw new AjaxException("消息不存在！");
        }
        $mail->status = 1;
        $mail->save();
        //删除键值
        $redis = Yii::$app->redis;
        $redisKey = "unreadMessagesNumber_" . $userInfo->username;
        $redis->del($redisKey);
    }

    /**
     * @throws AjaxException
     */
    public static function delete($id, $userInfo): void
    {
        $mail = Mail::findOne(["id" => $id, "receiver" => $userInfo->username]);
        if (!$mail) {
            throw new AjaxException("消息不存在！");
        }
        $mail->status = -1;
        $mail->save();
        $redis = Yii::$app->redis;
        $redisKey = "unreadMessagesNumber_" . $userInfo->username;
        $redis->del($redisKey);
    }

    protected static function sendMail($caseModel, $caseType, $remark): void
    {
        /** @var $caseModel AccidentCases */
        if ($caseType == "提交审核" || $caseType == "退回") {
            $param = [
                "accident_id",
                "title",
                "content",
                "status",
                "start_time",
                "update_time",
                "sender",
                "sender_name",
                "receiver",
                "receiver_name",
                "case_type",
            ];
            $time = date("Y-m-d H:i:s");
            $receiverList = [];
            $receiverNameList = [];
            if ($caseType == "提交审核") {
                $sender = $caseModel->create_by != "" ? $caseModel->create_by : "admin";
                $senderName = $caseModel->create_name != "" ? $caseModel->create_name : "超级管理员";
                $checkList = json_decode($caseModel->check_list);
                $checkNameList = json_decode($caseModel->check_name_list);
                if ($checkList == []) {
                    //发送给所有符合条件的
                    $userList = UserService::getCanCheckList();
                    foreach ($userList as $user) {
                        /** @var $user BaseUser */
                        $receiverList[] = $user->username;
                        $receiverNameList[] = $user->name;
                    }
                } else {
                    $receiverList = $checkList;
                    $receiverNameList = $checkNameList;
                }
            } else {
                $sender = $caseModel->check_by != "" ? $caseModel->check_by : "admin";
                $senderName = $caseModel->check_name != "" ? $caseModel->check_name : "超级管理员";
                $receiverList[] = $caseModel->create_by != "" ? $caseModel->create_by : "admin";;
                $receiverNameList[] = $caseModel->create_name != "" ? $caseModel->create_name : "超级管理员";;
            }
            //填写数据
            $paramData = [];
            foreach ($receiverList as $key => $value) {
                $paramData[] = [
                    "accident_id" => $caseModel->id,
                    "title" => $caseModel->title,
                    "content" => $remark,
                    "status" => 0,
                    "start_time" => $time,
                    "update_time" => $time,
                    "sender" => $sender,
                    "sender_name" => $senderName,
                    "receiver" => $value,
                    "receiver_name" => $receiverNameList[$key],
                    "case_type" => $caseType,
                ];
            }
            //保存数据
            if ($paramData != []) {
                Yii::$app->db->createCommand()->batchInsert(Mail::tableName(), $param, $paramData)->execute();
            }
        }
    }
}