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

namespace User\Service;

use Doctrine\ORM\EntityManager;
use User\Entity\UserRecharge;

class UserRechargeManager
{
    private $entityManager;

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

    /**
     * 添加充值
     * @param array $data
     * @return UserRecharge
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addUserRecharge(array $data)
    {
        $userRecharge = new UserRecharge();
        $userRecharge->setUserId($data['userId']);
        $userRecharge->setUserName($data['userName']);
        $userRecharge->setRechargeNum($data['rechargeNum']);
        $userRecharge->setCurrencyCode($data['currencyCode']);
        $userRecharge->setCurrencyRate($data['currencyRate']);
        $userRecharge->setBaseRechargeNum($data['baseRechargeNum']);
        $userRecharge->setBaseCurrencyCode($data['baseCurrencyCode']);
        $userRecharge->setPayState(10);
        $userRecharge->setPayCode($data['payCode']);
        $userRecharge->setPayName($data['payName']);
        $userRecharge->setAddRechargeTime(time());
        $userRecharge->setFinishRechargeTime(0);

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

        return $userRecharge;
    }

    /**
     * 编辑充值信息
     * @param array $data
     * @param UserRecharge $userRecharge
     * @return UserRecharge
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editUserRecharge(array $data, UserRecharge $userRecharge)
    {
        $userRecharge->valuesSet($data);
        $this->entityManager->flush();

        return $userRecharge;
    }

    /**
     * 删除充值信息
     * @param UserRecharge $userRecharge
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteUserRecharge(UserRecharge $userRecharge)
    {
        $this->entityManager->remove($userRecharge);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 清除未支付记录
     */
    public function clearNoPayUserRecharge()
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(UserRecharge::class, 'u')->where('u.payState <= :payState')->setParameter('payState', 10);

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