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

namespace Shop\Controller;

use Admin\Data\Config;
use Admin\Entity\Region;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use PHPQRCode\QRcode;
use User\Entity\User;

class HomeController extends HomeActionController
{
    private $translator;
    private $entityManager;

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

    /**
     * 会员中心首页
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('会员中心'));

        $userInfo = $this->entityManager->getRepository(User::class)->findOneByUserId(parent::$userId);

        return ['userInfo' => $userInfo];
    }

    /**
     * 邀请好友
     * @return array
     */
    public function invitationAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('邀请好友'));

        $qrCodeFile = $this->shopPlugin()->shopCreateQrCodeFile($this->url()->fromRoute('shop', [], ['query' => ['userId' => parent::$userId], 'force_canonical' => true]), Config::USER_INVITATION_IMAGE_PATH, parent::$userId);

        return ['qrCodeFile' => $qrCodeFile];
    }

    /**
     * 获取地区信息
     * @return JsonModel
     */
    public function ajaxRegionAction()
    {
        $regionTopId    = (int) $this->request->getPost('region_id');
        $regionList     = $this->entityManager->getRepository(Region::class)->findBy(['regionTopId' => $regionTopId], ['regionSort' => 'ASC']);
        $regionArray    = [];
        if($regionList) {
            foreach ($regionList as $value) {
                $regionArray[] = [
                    'region_id' => $value->getRegionId(),
                    'region_name' => $value->getRegionName()
                ];
            }
        }

        return new JsonModel($regionArray);
    }
}