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

namespace Goods\Service;

use Admin\Data\Config;
use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsBrand;

class GoodsBrandManager
{
    private $entityManager;

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

    /**
     * 添加商品品牌
     * @param array $data
     * @return GoodsBrand
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoodsBrand(array $data)
    {
        if(!empty($data['brandLogo']['tmp_name'])) $data['brandLogo'] = str_replace(Config::PUBLIC_PATH, '', $data['brandLogo']['tmp_name']);
        else unset($data['brandLogo']);

        $goodsBrand = new GoodsBrand();
        $goodsBrand->valuesSet($data);

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

        return $goodsBrand;
    }

    /**
     * 编辑商品品牌
     * @param array $data
     * @param GoodsBrand $goodsBrand
     * @return GoodsBrand
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editGoodsBrand(array $data, GoodsBrand $goodsBrand)
    {
        if(!empty($data['brandLogo']['tmp_name'])) $data['brandLogo'] = str_replace(Config::PUBLIC_PATH, '', $data['brandLogo']['tmp_name']);
        else unset($data['brandLogo']);

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

        return $goodsBrand;
    }

    /**
     * 删除商品品牌
     * @param GoodsBrand $goodsBrand
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteGoodsBrand(GoodsBrand $goodsBrand)
    {
        $this->entityManager->remove($goodsBrand);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 批量修改品牌排序
     * @param array $data
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateAllBrandSort(array $data)
    {
        foreach ($data['brandSort'] as $key => $value) {
            $brandInfo = $this->entityManager->getRepository(GoodsBrand::class)->findOneByBrandId($key);
            if($brandInfo) {
                $brandInfo->setBrandSort($value);
            }
        }
        $this->entityManager->flush();
        $this->entityManager->clear(GoodsBrand::class);
    }
}