<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Extend\Service;

use Doctrine\ORM\EntityManager;
use Extend\Entity\SystemNotice;
use function Doctrine\ORM\QueryBuilder;

class SystemNoticeManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加通知信息
     * @param array $data
     * @return SystemNotice
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addSystemNotice(array $data)
    {
        $systemNotice = new SystemNotice();
        $systemNotice->valuesSet($data);

        $this->entityManager->persist($systemNotice);
        $this->entityManager->flush();

        return $systemNotice;
    }

    /**
     * 编辑通知信息
     * @param array $data
     * @param SystemNotice $systemNotice
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editSystemNotice(array $data, SystemNotice $systemNotice)
    {
        $systemNotice->valuesSet($data);
        $this->entityManager->flush();
    }

    /**
     * 修改通知状态为已读
     * @param array $noticeIdArray
     */
    public function updateMoreSystemNoticeRead(array $noticeIdArray = [])
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(SystemNotice::class, 'n')->set('n.noticeReadState', ':noticeReadState')->setParameter('noticeReadState', 1)
            ->where('n.noticeReadState = :noticeNotReadState')->setParameter('noticeNotReadState', 0);

        if (!empty($noticeIdArray)) $qb->andWhere($qb->expr()->in('n.noticeId', $noticeIdArray));

        $qb->getQuery()->execute();
    }

    /**
     * 删除系统通知
     * @param SystemNotice $systemNotice
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteSystemNotice(SystemNotice $systemNotice)
    {
        $this->entityManager->remove($systemNotice);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 批量删除系统通知
     * @param array $noticeIdArray
     */
    public function deleteMoreSystemNotice(array $noticeIdArray)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(SystemNotice::class, 'n')->where($qb->expr()->in('n.noticeId', $noticeIdArray));

        $qb->getQuery()->execute();
    }
}