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

namespace Sales\Repository;

use Admin\Data\Common;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Sales\Entity\Order;
use Sales\Entity\OrderGoods;
use Sales\Entity\OrderGoodsReturn;
use User\Entity\User;

class OrderGoodsRepository extends EntityRepository
{
    /**
     * 获取订单商品，及订单信息
     * @param $orderGoodsId
     * @return int|mixed|string|null
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findOrderGoodsAndOrder($orderGoodsId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('g', 'o.currencySymbol', 'o.currencyCode')
            ->from(OrderGoods::class, 'g')
            ->innerJoin(Order::class, 'o', Join::WITH, 'g.orderId = o.orderId')
            ->where('g.orderGoodsId = :orderGoodsId')->setParameter('orderGoodsId', $orderGoodsId);

        return $query->getQuery()->getOneOrNullResult();
    }

    /**
     * 商品销售排行
     * @param $startTime
     * @param $endTime
     * @param int $userGroupId
     * @return \Doctrine\ORM\Query
     */
    public function findSalesOrderGoodsRanking($startTime, $endTime, $userGroupId = 0)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('g')
            ->addSelect('SUM(g.baseGoodsAmount) AS goodsTotal')
            ->addSelect('SUM(g.buyNum) AS goodsNumTotal')
            ->from(OrderGoods::class, 'g')
            ->leftJoin(Order::class, 'o', Join::WITH, 'g.orderId=o.orderId')
            ->leftJoin(User::class, 'u', Join::WITH, 'g.userId=u.userId')
            ->orderBy('goodsTotal', 'DESC')->groupBy('g.goodsItem');

        $query->where(
            $query->expr()->orX(
                $query->expr()->andX()->add($query->expr()->eq('o.paymentType', ':onlinePaymentType'))->add($query->expr()->gte('o.orderStatus', ':finishPayState')),
                $query->expr()->andX()->add($query->expr()->eq('o.paymentType', ':paymentType'))->add($query->expr()->gte('o.orderStatus', ':finishState'))
            )
        )
            ->setParameter('onlinePaymentType', 'OnlinePay')->setParameter('finishPayState', Common::orderStatusCode('WAIT_GOODS_ARRIVE'))
            ->setParameter('paymentType', 'CashOnDelivery')->setParameter('finishState', Common::orderStatusCode('GOODS_RECEIVED'));

        if (!empty($startTime)) $query->andWhere($query->expr()->gte('o.orderAddTime', ':startTime'))->setParameter('startTime', $startTime);
        if (!empty($endTime))   $query->andWhere($query->expr()->lte('o.orderAddTime', ':endTime'))->setParameter('endTime', $endTime);

        if ($userGroupId > 0) $query->andWhere('u.userGroupId = :userGroupId')->setParameter('userGroupId', $userGroupId);

        return $query->getQuery();
    }

    /*=======================================下面为前台使用=======================================*/
    /**
     * 前台虚拟商品列表
     * @param $userId
     * @return \Doctrine\ORM\Query
     */
    public function shopVirtualGoodsList($userId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('g')->addSelect('(SELECT o.orderSn FROM '.Order::class.' AS o WHERE o.orderId = g.orderId) AS orderSn')
            ->from(OrderGoods::class, 'g')
            ->where('g.userId = :userId')->setParameter('userId', $userId)
            ->andWhere('g.goodsType = 2')
            ->orderBy('g.orderId', 'DESC');

        return $query->getQuery();
    }

    /**
     * 获取退款退货的商品信息
     * @param $orderId
     * @return int|mixed|string
     */
    public function orderGoodsAndReturn($orderId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('g', 'r.returnAmount', 'r.returnState', 'r.returnType')
            ->from(OrderGoods::class, 'g')
            ->leftJoin(OrderGoodsReturn::class, 'r', Join::WITH, 'g.orderGoodsId = r.orderGoodsId')
            ->where('g.orderId = :orderId')->setParameter('orderId', $orderId);

        return $query->getQuery()->getResult();
    }
}