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

namespace Shop\Controller;

use Doctrine\ORM\EntityManager;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\I18n\Translator;
use Sales\Entity\Order;
use Sales\Service\OrderManager;
use Sales\Service\OrderStatusManager;
use Shop\Common\ShopCommon;
use User\Entity\UserRecharge;
use User\Service\UserRechargeManager;

class NotifyController extends AbstractActionController
{
    private $translator;
    private $writeEntityManager;
    private $orderManager;
    private $orderStatusManager;
    private $userRechargeManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $writeEntityManager,
        OrderManager    $orderManager,
        OrderStatusManager $orderStatusManager,
        UserRechargeManager $userRechargeManager
    )
    {
        $this->translator           = $translator;
        $this->writeEntityManager   = $writeEntityManager;
        $this->orderManager         = $orderManager;
        $this->orderStatusManager   = $orderStatusManager;
        $this->userRechargeManager  = $userRechargeManager;
    }

    /**
     * 默认页面
     * @return \Laminas\View\Model\ViewModel|mixed
     */
    public function indexAction()
    {
        return $this->response->setContent('此页面没有任何内容!');
    }

    /**
     * 订单支付异步通知
     * @return mixed
     */
    public function orderPaymentNotifyAction()
    {
        $orderId    = (int) $this->params()->fromRoute('id', 0);
        $orderInfo  = $this->writeEntityManager->getRepository(Order::class)->findOneBy(['orderId' => $orderId]);
        if($orderInfo == null) return $this->response->setContent('');

        $paymentData = ShopCommon::shopPaymentService($orderInfo->getPaymentCode())->orderPaymentNotify($orderInfo);
        if(isset($paymentData['finishPay']) && $paymentData['finishPay']) return $this->response->setContent($paymentData['sendMessage']);
        if($paymentData['paymentStatus']) {
            $finishPayTime = time();
            $this->writeEntityManager->beginTransaction();
            try {
                $orderUpdate = ['orderStatus' => $this->shopPlugin()->getOrderStatusCode('FINISH_PAYMENT'), 'paymentFinishTime' => $finishPayTime];
                //如果存在商户订单号则进行同步更新
                if (isset($paymentData['outTradeNo']) && !empty($paymentData['outTradeNo'])) $orderUpdate['outTradeNo'] = $paymentData['outTradeNo'];

                $orderInfo = $this->orderManager->editOrder($orderUpdate, $orderInfo);
                $this->orderStatusManager->addOrderStatus(['orderStatus' => $orderInfo->getOrderStatus(), 'operateUser' => $orderInfo->getUserName(), 'orderId' => $orderInfo->getOrderId(), 'statusInfo' => $this->translator->translate('订单支付完成'), 'statusTime' => $finishPayTime]);
                $this->getEventManager()->trigger('shop.order.notifyPayFinish.post', $this, ['orderInfo' => $orderInfo]);
                $this->writeEntityManager->commit();
            } catch (\Exception $e) {
                $this->writeEntityManager->rollback();
                return $this->response->setContent('');
            }
        }
        return $this->response->setContent($paymentData['sendMessage']);
    }

    /**
     * 充值支付异步通知
     * @return mixed
     */
    public function rechargePaymentNotifyAction()
    {
        $rechargeId     = (int) $this->params()->fromRoute('id', 0);
        $rechargeInfo   = $this->writeEntityManager->getRepository(UserRecharge::class)->findOneBy(['rechargeId' => $rechargeId]);
        if($rechargeInfo == null) return $this->response->setContent('');

        $paymentData = ShopCommon::shopPaymentService($rechargeInfo->getPayCode())->paymentNotify(['sn' => $rechargeInfo->getPayCode().$rechargeInfo->getAddRechargeTime(), 'currency' => $rechargeInfo->getCurrencyCode(), 'amount' => $rechargeInfo->getRechargeNum(), 'status' => $rechargeInfo->getPayState()]);
        if(isset($paymentData['finishPay']) && $paymentData['finishPay']) return $this->response->setContent($paymentData['sendMessage']);
        if($paymentData['paymentStatus']) {
            $finishPayTime = time();
            $this->writeEntityManager->beginTransaction();
            try {
                $rechargeInfo = $this->userRechargeManager->editUserRecharge(['payState' => 20, 'finishRechargeTime' => $finishPayTime], $rechargeInfo);
                $this->getEventManager()->trigger('shop.recharge.notifyPayFinish.post', $this, ['rechargeInfo' => $rechargeInfo]);
                $this->writeEntityManager->commit();
            } catch (\Exception $e) {
                $this->writeEntityManager->rollback();
                return $this->response->setContent('');
            }
        }
        return $this->response->setContent($paymentData['sendMessage']);
    }
}