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

namespace Cms\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Cms\Entity\Cms;
use Cms\Form\CmsForm;
use Cms\Form\SearchCmsForm;
use Cms\Service\CmsClassManager;
use Cms\Service\CmsManager;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;

class IndexController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $cmsManager;

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

    /**
     * 文章列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchCmsForm();
        $searchForm->get('cms_class_id')->setValueOptions($this->cmsPlugin()->cmsClassListOptions($this->translator->translate('选择分类')));
        $searchForm->get('cms_state')->setValueOptions(Common::state($this->translator));
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

        $query      = $this->entityManager->getRepository(Cms::class)->findListCms($search);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return ['cmsList' => $paginator, 'searchForm' => $searchForm];
    }

    /**
     * 添加文章
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        $form = new CmsForm();
        $form->get('cmsClassId')->setValueOptions($this->cmsPlugin()->cmsClassListOptions());

        $queryData = $this->params()->fromQuery();

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();
                $this->cmsManager->addCms($data);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('文章 %s 添加成功!'), $data['cmsTitle']), $this->translator->translate('文章管理'));

                return $this->redirect()->toRoute('cms', [], ['query' => $queryData]);
            }
        } else $form->setData(['cmsAddTime' => date("Y-m-d H:i:s", time())]);

        return ['form' => $form, 'queryData' => $queryData];
    }

    /**
     * 编辑文章
     * @return array|\Laminas\Http\Response
     */
    public function editAction()
    {
        $cmsId = (int) $this->params()->fromRoute('id', -1);
        $cmsInfo = $this->entityManager->getRepository(Cms::class)->findOneByCmsId($cmsId);
        if($cmsInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该文章不存在!'));
            return $this->redirect()->toRoute('cms');
        }

        $queryData = $this->params()->fromQuery();

        $form = new CmsForm();
        $form->get('cmsClassId')->setValueOptions($this->cmsPlugin()->cmsClassListOptions());

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();
                $this->cmsManager->editCms($data, $cmsInfo);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('文章 %s 编辑成功!'), $data['cmsTitle']), $this->translator->translate('文章管理'));

                return $this->redirect()->toRoute('cms', [], ['query' => $queryData]);
            }
        } else {
            $valueArray = $cmsInfo->valuesArray();
            if(!empty($valueArray['cmsAddTime'])) $valueArray['cmsAddTime'] = date("Y-m-d H:i:s", $valueArray['cmsAddTime']);
            else $valueArray['cmsAddTime'] = '';
            $form->setData($valueArray);
        }

        return ['form' => $form, 'cmsInfo' => $cmsInfo, 'queryData' => $queryData];
    }

    /**
     * 删除文章
     * @return \Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $cmsId = (int) $this->params()->fromRoute('id', -1);
        $cmsInfo = $this->entityManager->getRepository(Cms::class)->findOneByCmsId($cmsId);
        if($cmsInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该文章不存在!'));
            return $this->redirect()->toRoute('cms');
        }

        $this->cmsManager->deleteCms($cmsInfo);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('文章 %s 删除成功!'), $cmsInfo->getCmsTitle()), $this->translator->translate('文章管理'));

        return $this->adminCommon()->toReferer();
    }
}