<?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\GoodsAttributeGroup;

class GoodsAttributeGroupManager
{
    private $entityManager;

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

    /**
     * 添加商品属性组
     * @param array $data
     * @return GoodsAttributeGroup
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAttributeGroup(array $data)
    {
        $attributeGroup = new GoodsAttributeGroup();
        $attributeGroup->valuesSet($data);

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

        return $attributeGroup;
    }

    /**
     * 编辑商品属性组
     * @param array $data
     * @param GoodsAttributeGroup $goodsAttributeGroup
     * @return GoodsAttributeGroup
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAttributeGroup(array $data, GoodsAttributeGroup $goodsAttributeGroup)
    {
        $goodsAttributeGroup->valuesSet($data);
        $this->entityManager->flush();

        return $goodsAttributeGroup;
    }

    /**
     * 删除商品属性组
     * @param GoodsAttributeGroup $goodsAttributeGroup
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAttributeGroup(GoodsAttributeGroup $goodsAttributeGroup)
    {
        $this->entityManager->remove($goodsAttributeGroup);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 批量修改商品属性组排序
     * @param array $data
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateAllAttributeGroupSort(array $data)
    {
        foreach ($data['attributeGroupSort'] as $key => $value) {
            $GroupInfo = $this->entityManager->getRepository(GoodsAttributeGroup::class)->findOneByAttributeGroupId($key);
            if($GroupInfo) {
                $GroupInfo->setAttributeGroupSort($value);
            }
        }
        $this->entityManager->flush();
        $this->entityManager->clear(GoodsAttributeGroup::class);
    }
}