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

namespace Goods\Service;

use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsVirtual;

class GoodsVirtualManager
{
    private $entityManager;

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

    /**
     * 添加虚拟商品
     * @param array $data
     * @param $goodsId
     * @return GoodsVirtual
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addVirtualGoods(array $data, $goodsId)
    {
        if(isset($data['virtualGoodsId']) && $data['virtualGoodsId'] <= 0) unset($data['virtualGoodsId']);

        $data['goodsId']= $goodsId;
        $virtualGoods   = new GoodsVirtual();
        $virtualGoods->valuesSet($data);

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

        return $virtualGoods;
    }

    /**
     * 更新虚拟商品
     * @param array $data
     * @param GoodsVirtual $goodsVirtual
     * @return GoodsVirtual
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editVirtualGoods(array $data, GoodsVirtual $goodsVirtual)
    {
        if(isset($data['virtualGoodsId'])) unset($data['virtualGoodsId']);

        $goodsVirtual->valuesSet($data);
        $this->entityManager->flush();

        return $goodsVirtual;
    }

    /**
     * 删除虚拟商品
     * @param GoodsVirtual $goodsVirtual
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteVirtualGoods(GoodsVirtual $goodsVirtual)
    {
        $this->entityManager->remove($goodsVirtual);
        $this->entityManager->flush();

        return true;
    }
}