<?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;
    }

    /**
     * sql语句形式插入虚拟商品（批量导入）
     * @param $insertSql
     * @throws \Doctrine\DBAL\DBALException
     */
    public function insertVirtualGoods($insertSql)
    {
        $query  = $this->entityManager->getConnection();
        $stmt   = $query->prepare($insertSql);
        $stmt->execute();
    }

    /**
     * 更新虚拟商品
     * @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;
    }

    /**
     * 批量删除某一商品下的未交易虚拟商品
     * @param $goodsId
     */
    public function deleteMoreVirtualGoods($goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(GoodsVirtual::class, 'v')
            ->where('v.goodsId = :goodsId')->setParameter('goodsId', $goodsId)->andWhere('v.userId = 0');
        $qb->getQuery()->execute();
    }
}