<?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\Data\Config;
use Admin\Form\SystemServiceImageForm;
use Cms\Form\CmsImageForm;
use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsImage;
use Goods\Form\GoodsCommonImageForm;
use Goods\Form\GoodsImageForm;
use Goods\Service\GoodsImageManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\Validator\File\IsImage;
use Laminas\View\Model\JsonModel;

class EditorController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $goodsImageManager;

    private $actionArray    = ['config', 'uploadImage', 'listImage'];

    /**
     * goods 商品图片
     * cms 文章和单页文章图片
     * goodsCommon 商品通用内容图片
     */
    private $typeArray      = ['goods', 'cms', 'goodsCommon', 'shopService'];
    private $fieldNameArray = [
        'goods'         => 'goodsImage',//商品图片
        'cms'           => 'cmsImage',  //文章图片
        'goodsCommon'   => 'goodsCommonImage',  //商品通用内容图片
        'shopService'   => 'shopServiceImage'   //系统设置中的内容设置图片
    ];

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

    public function indexAction()
    {
        return $this->redirect()->toRoute('home');
    }

    /**
     * 百度编辑器
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function uEditorUploadAction()
    {
        $action = $this->request->getQuery('action');
        $type   = $this->params()->fromRoute('type');

        if(
            !in_array($type, $this->typeArray)
            ||
            !in_array($action, $this->actionArray)
        )  return new JsonModel(['state' => '非法请求']);;

        $array = [];

        switch ($action) {
            case 'config':
                $array = $this->uEditorConfig($type);
                break;
            case 'uploadImage':
                $array = $this->uEditorUploadImage($type);
                break;
            case 'listImage':
                $array = $this->uEditorListImage($type);
                break;
        }

        return new JsonModel($array);
    }

    private function uEditorConfig($type)
    {
        return [
            'imageActionName'       => 'uploadImage',   //执行上传图片的action名称
            'imageFieldName'        => $this->fieldNameArray[$type],    //提交的图片表单名称
            'imageMaxSize'          => (int)str_replace('MB', '', Common::configValue('upload_image_max')['max']) * 1024 * 1024,         //上传大小限制，单位B
            'imageCompressEnable'   => true,            //是否压缩图片,默认是true
            'imageCompressBorder'   => 1600,            //图片压缩最长边限制
            'imageInsertAlign'      => "none",          //插入的图片浮动方式
            'imageUrlPrefix'        => '',              //图片访问路径前缀
            'imageAllowFiles'       => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],

            'imageManagerActionName'=> 'listImage',     //执行图片管理的action名称
            'imageManagerListPath'  => '',  //指定要列出图片的目录
            'imageManagerListSize'  => 20,              //每次列出文件数量
            'imageManagerUrlPrefix' => '',              //图片访问路径前缀
            'imageManagerInsertAlign' => 'none',        //插入的图片浮动方式
            'imageManagerAllowFiles'=> [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
        ];
    }

    /**
     * 上传商品图片
     * @param $type
     * @return array
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    private function uEditorUploadImage($type)
    {
        $array = [];
        switch ($type) {
            case "goods"://商品
                if($this->getRequest()->isPost()) {
                    $goodsId = (int) $this->params()->fromRoute('id', 0);
                    $data    = $this->getRequest()->getFiles()->toArray();

                    $imageForm = new GoodsImageForm();
                    $data['goodsId']    = $goodsId;
                    $data['imageSlide'] = 0;
                    $data['imageCode']  = $goodsId > 0 ? '' : $this->adminCommon()->admin('session_id');
                    $data['imageSort']  = 255;
                    $imageForm->setData($data);
                    if($imageForm->isValid()) {
                        $data = $imageForm->getData();
                        $imageInfo = $this->goodsImageManager->addGoodsImage($data);
                        if($imageInfo) {
                            $array = [
                                //上传状态，上传成功时必须返回"SUCCESS"
                                'state' => 'SUCCESS',
                                //返回的地址
                                'url'   => $this->request->getBasePath() . '/' . $imageInfo->getGoodsImage()
                            ];
                        }
                    } else $array['error'] = implode(',', $imageForm->getMessages());
                }
                break;

            case "cms"://文章和单页文章
                if($this->getRequest()->isPost()) {
                    $data = $this->getRequest()->getFiles()->toArray();
                    $cmsImageForm = new CmsImageForm();
                    $cmsImageForm->setData($data);
                    if($cmsImageForm->isValid()) {
                        $data   = $cmsImageForm->getData();
                        $array  = [
                            'state' => 'SUCCESS',
                            'url'   => $this->request->getBasePath() . '/' . str_replace(Config::PUBLIC_PATH, '', $data['cmsImage']['tmp_name'])
                        ];
                    } else $array['error'] = implode(',', $cmsImageForm->getMessages());
                }
                break;

            case "goodsCommon":
                if($this->getRequest()->isPost()) {
                    $data = $this->getRequest()->getFiles()->toArray();
                    $goodsCommonImageForm = new GoodsCommonImageForm();
                    $goodsCommonImageForm->setData($data);
                    if($goodsCommonImageForm->isValid()) {
                        $data   = $goodsCommonImageForm->getData();
                        $array  = [
                            'state' => 'SUCCESS',
                            'url'   => $this->request->getBasePath() . '/' . str_replace(Config::PUBLIC_PATH, '', $data['goodsCommonImage']['tmp_name'])
                        ];
                    } else $array['error'] = implode(',', $goodsCommonImageForm->getMessages());
                }
                break;

            case "shopService":
                if($this->getRequest()->isPost()) {
                    $data = $this->getRequest()->getFiles()->toArray();
                    $systemServiceImageForm = new SystemServiceImageForm();
                    $systemServiceImageForm->setData($data);
                    if ($systemServiceImageForm->isValid()) {
                        $data = $systemServiceImageForm->getData();
                        $array  = [
                            'state' => 'SUCCESS',
                            'url'   => $this->request->getBasePath() . '/' . str_replace(Config::PUBLIC_PATH, '', $data['shopServiceImage']['tmp_name'])
                        ];
                    } else  $array['error'] = implode(',', $systemServiceImageForm->getMessages());
                }
                break;
        }

        return $array;
    }

    /**
     * 商品图片列表
     * @param $type
     * @return array
     */
    private function uEditorListImage($type)
    {
        $array = ['state' => 'SUCCESS'];

        $basePath = $this->request->getBasePath() . '/';
        $isImage  = new IsImage();

        switch ($type) {
            case "goods"://商品图片列表
                $goodsId        = (int) $this->params()->fromRoute('id', 0);
                $listGoodsImage = [];
                $goodsImage     = $this->entityManager->getRepository(GoodsImage::class)->editorGoodsImageList($goodsId, $this->adminCommon()->admin('session_id'));
                if($goodsImage) {
                    foreach ($goodsImage as $image) {
                        if($isImage->isValid(Config::PUBLIC_PATH . $image->getGoodsImage())) $listGoodsImage[] = ['url' => $basePath . $image->getGoodsImage()];
                    }
                    $array['list'] = $listGoodsImage;
                    $array['start']= 0;
                    $array['total']= count($listGoodsImage);
                }
                break;

            case "cms"://文章图片列表
                if(!is_dir(Config::CMS_IMAGE_PATH)) return null;
                $cmsImagePath   = str_replace(Config::PUBLIC_PATH, '', Config::CMS_IMAGE_PATH);
                $listCmsImage   = [];
                $handle = scandir(Config::CMS_IMAGE_PATH);
                foreach ($handle as $file) {
                    if(!in_array($file, ['.', '..', '.gitignore'])) {
                        if($isImage->isValid(Config::CMS_IMAGE_PATH . $file)) $listCmsImage[] = ['url' => $basePath . $cmsImagePath . $file];
                    }
                }
                $array['list'] = $listCmsImage;
                $array['start']= 0;
                $array['total']= count($listCmsImage);
                break;

            case "goodsCommon"://商品通用内容图片列表
                if(!is_dir(Config::GOODS_COMMON_IMAGE_PATH)) return null;
                $goodsCommonImagePath   = str_replace(Config::PUBLIC_PATH, '', Config::GOODS_COMMON_IMAGE_PATH);
                $listGoodsCommonImage   = [];
                $handle = scandir(Config::GOODS_COMMON_IMAGE_PATH);
                foreach ($handle as $file) {
                    if(!in_array($file, ['.', '..', '.gitignore'])) {
                        if($isImage->isValid(Config::GOODS_COMMON_IMAGE_PATH . $file)) $listGoodsCommonImage[] = ['url' => $basePath . $goodsCommonImagePath . $file];
                    }
                }
                $array['list'] = $listGoodsCommonImage;
                $array['start']= 0;
                $array['total']= count($listGoodsCommonImage);
                break;

            case "shopService":
                if (!is_dir(Config::SYSTEM_SERVICE_IMAGE_PATH)) return null;
                $systemServiceImagePath = str_replace(Config::PUBLIC_PATH, '', Config::SYSTEM_SERVICE_IMAGE_PATH);
                $listSystemServiceImage = [];
                $handle = scandir(Config::SYSTEM_SERVICE_IMAGE_PATH);
                foreach ($handle as $file) {
                    if(!in_array($file, ['.', '..', '.gitignore'])) {
                        if($isImage->isValid(Config::SYSTEM_SERVICE_IMAGE_PATH . $file)) $listSystemServiceImage[] = ['url' => $basePath . $systemServiceImagePath . $file];
                    }
                    $array['list'] = $listSystemServiceImage;
                    $array['start']= 0;
                    $array['total']= count($listSystemServiceImage);
                }
                break;
        }

        return $array;
    }
}