<?php

/**
 * 玩家邮件操作
 */

namespace Game\Logic;

use Framework\Log\LogMark;
use Framework\MVC\ModelManager;
use Game\Constant\ClientErrorCode;
use Game\Constant\ConstTemplate\TemplateMail;
use Game\Constant\GameConstantDefine;
use Game\Constant\GameErrorCode;
use Game\Constant\ModelTypeDefine;
use Game\Constant\TemplateDefine;
use Game\Data\AccountData;
use Game\Data\MailData;
use Game\Model\AccountModel;
use Game\Model\MailModel;
use Game\Protobuf\ReplaceString;

trait MailLogic
{
    use ItemLogic;

    //$expireTime,过期时间,秒

    /**
     * @param int $mailTplId
     * @param int $receiveTime
     * @param array $enclosure
     * @param int $expireTime
     * @param int $toPlayerId 发送给哪个玩家
     * @param int $fromPlayerId 来源,系统为0
     * @param string $content 替换邮件内容 json 部分邮件使用 部分会读表
     * @param string $replaceString
     * @return bool
     */
    public function createPlayerMail(int $mailTplId, int $receiveTime, array $enclosure = array(),
                                        int $expireTime = 0, int $toPlayerId = 0, int $fromPlayerId = 0,
                                        string $content = "", string $replaceString = "[]"): bool
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        if ($mailModel->createMail($mailTplId, $receiveTime, $enclosure, $expireTime, $toPlayerId, $fromPlayerId, $content, $replaceString)) {
            $mailModel->addPacketMessage($toPlayerId);
            return true;
        }
        return false;
    }

    public function getAllMailByIndex(int $start, int $stop)
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        $mailUidList = $mailModel->getAllMailUid($start, $stop);
        foreach ($mailUidList as $uid => $t) {
            $mail = $mailModel->getSingleMail($uid);
            if (is_null($mail)) {
                LogMark::getInstance()->markWarn(GameErrorCode::MAIL_NOT_EXIST,
                                                  '[MailLogic] mail not exist,but still in index list',
                                                  array(
                                                      "uid" => $uid,
                                                  )
                );
                continue;
            }
            $retCode = $mailModel->checkMailLegal($mail);
            if (ClientErrorCode::CLIENT_SUCCESS != $retCode) {
                continue;
            }
            $mailModel->addSendMailMessage($mail);
        }
        $mailModel->sendMessage();
    }

    /**
     * 设置邮件已读
     * @param int $uid
     * @return int
     */
    public function singleMailRead(int $uid): int
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        /**
         * @var MailData $mail
         */
        $mail = $mailModel->getSingleMail($uid);
        if (is_null($mail)) {
            return ClientErrorCode::MAIL_NOT_EXIT;
        }
        $retCode = $mailModel->checkMailLegal($mail);
        if (ClientErrorCode::CLIENT_SUCCESS != $retCode) {
            return $retCode;
        }
        if ($mail->status == MailData::STATUS_NEW) {
            $mailModel->updateMailStatus($mail, MailData::STATUS_READ);
        }
        return ClientErrorCode::CLIENT_SUCCESS;
    }

    /**
     * 获取单个邮件信息
     * @param int $uid
     * @return MailData
     */
    public function getSingleMailInfo(int $uid): ?MailData
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        return $mailModel->getSingleMail($uid);

    }

    public function singleMailGet(int $uid): int
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        /**
         * @var MailData $mail
         */
        $mail = $mailModel->getSingleMail($uid);
        if (is_null($mail)) {
            return ClientErrorCode::MAIL_NOT_EXIT;
        }
        $retCode = $mailModel->checkMailLegal($mail);
        if (ClientErrorCode::CLIENT_SUCCESS != $retCode) {
            return $retCode;
        }
        if ($mail->status == MailData::STATUS_OVER) {
            return ClientErrorCode::MAIL_HAS_GET;
        }
        $mailModel->formatEnclosure($mail);
        $enclosure = $mailModel->getEnclosure();
        if (empty($enclosure)) {
            return ClientErrorCode::MAIL_NOT_HAVE_ENCLOSURE;
        }
        //加道具
        $this->setLogAddItemSource(GameConstantDefine::ITEM_ADD_SOURCE_MAIL);
        $this->gainItemArr($enclosure);
        $mailModel->updateMailStatus($mail, MailData::STATUS_OVER);
        return ClientErrorCode::CLIENT_SUCCESS;
    }

    public function singleMailDel(int $uid, bool $isCheck = false): int
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        /**
         * @var MailData $mail
         */
        $mail = $mailModel->getSingleMail($uid);
        if (is_null($mail)) {
            return ClientErrorCode::MAIL_NOT_EXIT;
        }
        $retCode = $mailModel->checkMailLegal($mail);
        if (ClientErrorCode::CLIENT_SUCCESS != $retCode) {
            return $retCode;
        }

        //检查附件是否领取 如果没领取 不能删除
        if(!$isCheck) {
            $mailModel->formatEnclosure($mail);
            $enclosure = $mailModel->getEnclosure();
            if (!empty($enclosure) && $mail->status != MailData::STATUS_OVER) {
                return ClientErrorCode::MAIL_ENCLOSURE_NOT_GET;
            }
        }
        //删除邮件
        $mailModel->deleteMail($mail);
        return ClientErrorCode::CLIENT_SUCCESS;
    }

    //一键删除已读邮件 附件未领取的pass
    public function allMailDel(int $mailType): int
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        $mailUidList = $mailModel->getAllMailUid(0, -1);
        if (empty($mailUidList)) {
            return ClientErrorCode::MAIL_EMPTY;
        }
        foreach ($mailUidList as $uid => $t) {
            /**
             * @var MailData $mail
             */
            $mail = $mailModel->getSingleMail($uid);
            if (is_null($mail)) {
                LogMark::getInstance()->markWarn(GameErrorCode::MAIL_NOT_EXIST,
                                                  '[MailLogic] mail not exist,but still in index list',
                                                  array(
                                                      "uid" => $uid,
                                                  )
                );
                continue;
            }
            $mailConfig = $this->getTitle(TemplateDefine::TYPE_MAIL, $mail->mailTplId);
            if ($mailType != $mailConfig[TemplateMail::MailType]) {
                continue;
            }
            $retCode = $mailModel->checkMailLegal($mail);
            if (ClientErrorCode::CLIENT_SUCCESS != $retCode) {
                continue;
            }
            if ($mail->status == MailData::STATUS_NEW) {
                continue;
            }
            //未领取附件的邮件 不能删除
            if ($mailModel->checkHasEnclosure($mail) && $mail->status != MailData::STATUS_OVER) {
                continue;
            }
            $mailModel->deleteMail($mail);
        }
        return ClientErrorCode::CLIENT_SUCCESS;
    }

    //一键领取全部附件
    public function allMailGetEnclosure(int $mailType): int
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        $mailUidList = $mailModel->getAllMailUid(0, -1);
        if (empty($mailUidList)) {
            return ClientErrorCode::MAIL_EMPTY;
        }
        foreach ($mailUidList as $uid => $t) {
            /**
             * @var MailData $mail
             */
            $mail = $mailModel->getSingleMail($uid);
            if (is_null($mail)) {
                LogMark::getInstance()->markWarn(GameErrorCode::MAIL_NOT_EXIST,
                                                  '[MailLogic] mail not exist,but still in index list',
                                                  array(
                                                      "uid" => $uid,
                                                  )
                );
                continue;
            }
            $mailConfig = $this->getTitle(TemplateDefine::TYPE_MAIL, $mail->mailTplId);
            if ($mailType != $mailConfig[TemplateMail::MailType]) {
                continue;
            }
            // 判断邮件类型 处理领取多个战令
            if(in_array($mailConfig[TemplateMail::MailType], TemplateMail::MAIL_ZL_PUSH_MAP)) {
                continue;
            }

            $retCode = $mailModel->checkMailLegal($mail);
            if (ClientErrorCode::CLIENT_SUCCESS != $retCode) {
                continue;
            }
            if ($mail->status == MailData::STATUS_OVER) {
                continue;
            }
            //没有附件的未读邮件 状态不变
            if ($mailModel->checkHasEnclosure($mail)) {
                //整理附件
                $mailModel->formatEnclosure($mail);
                //更新状态
                $mailModel->updateMailStatus($mail, MailData::STATUS_OVER);
            }
        }

        //加道具
        $enclosure = $mailModel->getEnclosure();
        if (empty($enclosure)) {
            return ClientErrorCode::MAIL_NOT_HAVE_ENCLOSURE;
        }
        $this->setLogAddItemSource(GameConstantDefine::ITEM_ADD_SOURCE_MAIL);
        $this->gainItemArr($enclosure);
        return ClientErrorCode::CLIENT_SUCCESS;
    }

    public function sendMailMessage()
    {
        /**
         * @var MailModel $mailModel
         */
        $mailModel = ModelManager::getInstance()->getModel(ModelTypeDefine::MAIL);
        $mailModel->sendMessage();
    }

    //替换邮件内容Key
    //已知邮件内容需要替换的key,替换为[key=>描述,..]
    //返回json
    public function replaceMailContent(int $mailId, array $params): string
    {
        $repString=  new ReplaceString();
        $configReplaceArray = $this->getTerm(TemplateDefine::TYPE_MAIL, $mailId, TemplateMail::ReplaceString);
        if (empty($configReplaceArray)) {
            return $repString->serializeToJsonString();
        }
        foreach ($configReplaceArray as $replaceKey) {
            switch ($replaceKey) {
                case TemplateMail::REPLACE_KEY_OTHER_NAME:
                    $repString->setOtherName($this->getPlayerNickName($params[GameConstantDefine::MAIL_KEY_OTHER_NAME]));
                    break;
                case TemplateMail::REPLACE_KEY_PLAYER_NAME:
                    $repString->setPlayerName($this->getPlayerNickName($params[GameConstantDefine::MAIL_KEY_PLAYER_NAME]));
                    break;
                case TemplateMail::REPLACE_KEY_INTIMACY_TYPE:
                    $repString->setIntimacyType($params[GameConstantDefine::MAIL_KEY_INTIMACY_TYPE]);
                    break;
                case TemplateMail::REPLACE_KEY_ITEM_ID:
                    $repString->setItemID($params[GameConstantDefine::MAIL_KEY_ITEM_ID]);
                    break;
                case TemplateMail::REPLACE_KEY_ACCOUNT:
                    $repString->setAccount($params[GameConstantDefine::MAIL_KEY_ACCOUNT]);
                    break;
                case TemplateMail::REPLACE_KEY_PASSWORD:
                    $repString->setPassword($params[GameConstantDefine::MAIL_KEY_PASSWORD]);
                    break;
            }
        }
        return $repString->serializeToJsonString();
    }

    //查询玩家昵称
    private function getPlayerNickName(int $playerId): ?string
    {
        /**
         * @var AccountModel $accountModel
         */
        $accountModel = ModelManager::getInstance()->getModel(ModelTypeDefine::ACCOUNT);
        $playerInfo = array();
        if ($accountModel->search($playerId, $playerInfo)) {
            return $playerInfo[AccountData::DB_NICK_NAME] ?? null;
        }
        return null;
    }
}

