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

namespace Operation\Service;

use Doctrine\ORM\EntityManager;
use Laminas\Math\Rand;
use Operation\Entity\RechargeCode;
use Operation\Entity\RechargeCodeRule;

class RechargeCodeManager
{
    private $entityManager;

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

    /**
     * 生成充值码
     * @param RechargeCodeRule $rechargeCodeRule
     * @param int $codeNum
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addRechargeCode(RechargeCodeRule $rechargeCodeRule, $codeNum = 0)
    {
        $codeNum = $codeNum > 0 ? $codeNum : $rechargeCodeRule->getCodeNum();

        for ($i = 1; $i <= $codeNum; $i++) {
            $rechargeCode = new RechargeCode();
            $rechargeCode->valuesSet([
                'codeRuleId'    => $rechargeCodeRule->getCodeRuleId(),
                'codeMoney'     => $rechargeCodeRule->getCodeOneMoney(),
                'codeStr'       => strtoupper(Rand::getString(12, 'abcdefghijklmnopqrstuvwxyz0123456789')),
                'codeCreateTime'=> time()
            ]);
            $this->entityManager->persist($rechargeCode);
        }
        $this->entityManager->flush();
    }

    /**
     * 更新充值码
     * @param array $data
     * @param RechargeCode $rechargeCode
     * @return RechargeCode
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editRechargeCode(array $data, RechargeCode $rechargeCode)
    {
        $rechargeCode->valuesSet($data);
        $this->entityManager->flush();

        return $rechargeCode;
    }

    /**
     * 删除整个规则内的充值码
     * @param $ruleId
     */
    public function deleteRechargeRuleAllCode($ruleId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(RechargeCode::class, 'c')->where('c.codeRuleId = :codeRuleId')->setParameter('codeRuleId', $ruleId);

        $qb->getQuery()->execute();
    }
}