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

namespace Admin\Controller;

use Admin\Data\Common;
use Admin\Entity\DeliveryIndividuation;
use Admin\Entity\Region;
use Admin\Entity\SelfLocation;
use Admin\Form\DeliveryIndividuationForm;
use Admin\Form\ShopDeliveryForm;
use Admin\Service\DeliveryIndividuationManager;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;

class DeliverySetController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $deliveryIndividuationManager;

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

    public function indexAction()
    {
        $form = new ShopDeliveryForm();
        $form->get('cashOnDelivery')->setValueOptions(Common::cashOnDeliveryState($this->translator));
        $form->get('deliverySet')->setValueOptions(Common::deliverySet($this->translator));
        $form->get('deliveryApiType')->setValueOptions(Common::deliveryApiType());

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                if($data['deliveryState'] == '0') {
                    $selfLocation = $this->entityManager->getRepository(SelfLocation::class)->findOneBy(['locationState' => 1]);
                    if($selfLocation == null) {
                        $this->flashMessenger()->addWarningMessage($this->translator->translate('自提点管理中如没有启用的自提点信息，商家配送设置不能关闭启用!'));
                        return $this->redirect()->toRoute('delivery-set');
                    }
                }

                $this->createConfig()->createShopDelivery($data);

                $this->adminCommon()->addOperLog($this->translator->translate('商品配送设置 修改成功!'), $this->translator->translate('配送方式'));

                return $this->redirect()->toRoute('delivery-set');
            }
        }

        $shopDelivery = Common::readConfigFile('delivery');
        $form->setData([
            'cashOnDelivery'    => $shopDelivery['cashOnDelivery'],
            'deliveryState'     => $shopDelivery['deliveryState'],
            'deliverySet'       => $shopDelivery['deliverySet'],
            'deliveryPrice'     => $shopDelivery['deliveryPrice'],
            'deliveryApiType'   => $shopDelivery['deliveryApiType'],
            'deliveryApiSecret' => $shopDelivery['deliveryApiSecret'],
            'deliveryApiKey'    => $shopDelivery['deliveryApiKey'],
            'deliveryApiState'  => $shopDelivery['deliveryApiState']
        ]);

        $deliveryIndividuationList = $this->entityManager->getRepository(DeliveryIndividuation::class)->findBy([], ['indivId' => 'DESC']);
        $areaArray = [];
        if($deliveryIndividuationList) {
            foreach ($deliveryIndividuationList as $listValue) {
                $areaIdArray = unserialize($listValue->getDeliveryArea());
                if(!empty($areaIdArray)) $areaArray[$listValue->getIndivId()] = $this->entityManager->getRepository(Region::class)->findBy(['regionId' => $areaIdArray]);
            }
        }

        $regionArray = $this->entityManager->getRepository(Region::class)->findBy([], ['regionPath' => 'ASC']);

        return [
            'form'          => $form,
            'shopDelivery'  => $shopDelivery,
            'areaArray'     => $areaArray,
            'regionArray'   => $regionArray,
            'deliveryIndividuationList' => $deliveryIndividuationList
        ];
    }

    /**
     * 添加个性化地区
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addSingleAreaAction()
    {
        $form = new DeliveryIndividuationForm();
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                if(!empty($data['deliveryArea'])) $regionList = $this->entityManager->getRepository(Region::class)->findBy(['regionId' => $data['deliveryArea']]);
                $areaStr    = '';
                if(isset($regionList) && $regionList != null) {
                    foreach ($regionList as $regionValue) {
                        $areaStr .= $regionValue->getRegionName() . ',';
                    }
                    $areaStr = rtrim($areaStr, ',');
                }
                if(empty($areaStr)) return new JsonModel(['state' => 'areaNull']);

                $editType   = 'false';
                if($data['indivId'] <= 0) {
                    $deliveryIndividuationInfo = $this->deliveryIndividuationManager->addDeliveryIndividuation($data);
                } else {
                    $editType = 'true';
                    $deliveryIndividuationInfo = $this->entityManager->getRepository(DeliveryIndividuation::class)->findOneBy(['indivId' => $data['indivId']]);
                    if($deliveryIndividuationInfo) {
                        $this->deliveryIndividuationManager->editDeliveryIndividuation($data, $deliveryIndividuationInfo);
                    }
                }

                return new JsonModel([
                    'state'         => 'true',
                    'editType'      => $editType,
                    'indivId'       => $deliveryIndividuationInfo->getIndivId(),
                    'deliveryPrice' => $data['deliveryPrice'],
                    'deliveryArea'  => $areaStr
                ]);
            } else {
                if($form->getMessages('deliveryArea')) return new JsonModel(['state' => 'areaNull']);
            }
        }
        return new JsonModel(['state' => 'error']);
    }

    /**
     * 获取个性地区信息
     * @return JsonModel
     */
    public function infoSingleAreaAction()
    {
        $indivId = (int) $this->request->getPost('indivId', 0);
        $indivInfo = $this->entityManager->getRepository(DeliveryIndividuation::class)->findOneByIndivId($indivId);
        if(!$indivInfo) return new JsonModel([]);

        return new JsonModel([
            'state'     => 'true',
            'indivId'   => $indivId,
            'deliveryPrice' => $indivInfo->getDeliveryPrice(),
            'areaId'    => unserialize($indivInfo->getDeliveryArea())
        ]);
    }

    /**
     * 删除个性地区
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delSingleAreaAction()
    {
        $indivId = (int) $this->request->getPost('indivId', 0);
        $indivInfo = $this->entityManager->getRepository(DeliveryIndividuation::class)->findOneByIndivId($indivId);
        if(!$indivInfo) return new JsonModel(['state' => 'false']);

        $this->deliveryIndividuationManager->deleteDeliveryIndividuation($indivInfo);

        return new JsonModel(['state' => 'true']);
    }

    /**
     * 测试检查
     * @return JsonModel
     */
    public function checkDeliveryPriceAction()
    {
        $data = $this->params()->fromPost();
        $testPrice = $this->deliveryPlugin()->calculateCost(trim($data['deliveryPrice']), trim($data['testWeight']), trim($data['testTotal']));

        return new JsonModel(['testPrice' => $testPrice]);
    }
}