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

namespace User\Event;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\I18n\Translator\Translator;
use User\Entity\IntegralType;
use User\Service\CartManager;
use User\Service\IntegralLogManager;
use User\Service\UserManager;
use Laminas\EventManager\Event;
use Laminas\EventManager\EventManagerInterface;
use Laminas\EventManager\ListenerAggregateInterface;

class UserListener implements ListenerAggregateInterface
{
    protected $listeners = [];

    private $translator;
    private $entityManager;
    private $userManager;
    private $integralLogManager;
    private $cartManager;

    public function __construct(
        EntityManager   $entityManager,
        UserManager     $userManager,
        IntegralLogManager $integralLogManager,
        CartManager $cartManager
    )
    {
        $this->translator   = new Translator();
        $this->entityManager= $entityManager;
        $this->userManager  = $userManager;
        $this->integralLogManager = $integralLogManager;
        $this->cartManager  = $cartManager;
    }

    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $shareEvents = $events->getSharedManager();

        //后台会员添加，初始化积分
        $this->listeners[] = $shareEvents->attach(
            'User\Controller\IndexController', 'backstage-user.add.post', [$this, 'onInitializeIntegral']
        );
        //商品删除时，删除处理
        $this->listeners[] = $shareEvents->attach(
            'Goods\Controller\IndexController', 'goods.delete.post', [$this, 'onDeleteUserOther']
        );
    }

    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            $events->detach($listener);
            unset($this->listeners[$index]);
        }
    }

    /**
     * 后台会员添加，初始化积分
     * @param Event $event
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function onInitializeIntegral(Event $event)
    {
        $userInfo = $event->getParam('user');
        $defaultIntegralType1Num = Common::configValue('integral_type_1', 'integral')['integralDefaultNum'];
        $defaultIntegralType2Num = Common::configValue('integral_type_2', 'integral')['integralDefaultNum'];

        $updateIntegralArray = [];
        if($defaultIntegralType1Num > 0) $updateIntegralArray['integralType1Num'] = $userInfo->getIntegralType1Num() + $defaultIntegralType1Num;
        if($defaultIntegralType2Num > 0) $updateIntegralArray['integralType2Num'] = $userInfo->getIntegralType2Num() + $defaultIntegralType2Num;

        if(!empty($updateIntegralArray) && $userInfo) {
            $this->userManager->updateUserIntegral($updateIntegralArray, $userInfo);
            if($defaultIntegralType1Num > 0) {
                $this->integralLogManager->addIntegralLog([
                    'userId'            => $userInfo->getUserId(),
                    'userName'          => $userInfo->getUserName(),
                    'integralLogInfo'   => $this->translator->translate('后台客户添加，默认初始化消费积分').'+'.$defaultIntegralType1Num,
                    'changeIntegralNum' => $defaultIntegralType1Num,
                    'integralNum'       => $updateIntegralArray['integralType1Num'],
                    'integralTypeId'    => 1,
                    'integralLogTime'   => time(),
                    'adminId'           => 0
                ]);
                if($defaultIntegralType2Num > 0) {
                    $this->integralLogManager->addIntegralLog([
                        'userId'            => $userInfo->getUserId(),
                        'userName'          => $userInfo->getUserName(),
                        'integralLogInfo'   => $this->translator->translate('后台客户添加，默认初始化等级积分').'+'.$defaultIntegralType2Num,
                        'changeIntegralNum' => $defaultIntegralType2Num,
                        'integralNum'       => $updateIntegralArray['integralType2Num'],
                        'integralTypeId'    => 2,
                        'integralLogTime'   => time(),
                        'adminId'           => 0
                    ]);
                }
            }
        }

        $integralTypeList = $this->entityManager->getRepository(IntegralType::class)->findBy([], ['integralTypeId' => 'ASC']);
        $data = [];
        if($integralTypeList) foreach ($integralTypeList as $typeValue) {
            if($typeValue->getIntegralDefaultNum() > 0) {
                if($typeValue->getIntegralTypeMark() == 'integral_type_1') $data['integralType1Num'] = $typeValue->getIntegralDefaultNum();
                if($typeValue->getIntegralTypeMark() == 'integral_type_2') $data['integralType2Num'] = $typeValue->getIntegralDefaultNum();
            }
        }

        if(!empty($data) && $userInfo) {
            $this->userManager->updateUserIntegral($data, $userInfo);
        }
    }

    /**
     * 后台删除商品的同时，删除购物车里的商品
     * @param Event $event
     */
    public function onDeleteUserOther(Event $event)
    {
        $goodsId = (int) $event->getParam('goodsId');
        if($goodsId > 0) {
            $this->cartManager->deleteCartGoods($goodsId);
        }
    }
}