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

namespace User\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use User\Entity\Cart;
use User\Entity\User;
use User\Entity\UserAddress;
use User\Entity\UserGoodsFavorites;
use User\Entity\UserOtherLogin;
use User\Form\ChangePayPasswordForm;
use User\Form\ChangeUserPasswordForm;
use User\Form\SearchUserForm;
use User\Form\UserForm;
use User\Service\UserManager;
use Laminas\Mvc\I18n\Translator;

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

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

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

        $search = [];
        $searchForm = new SearchUserForm();
        $searchForm->get('user_group_id')->setValueOptions($this->userPlugin()->userGroupOptions($this->translator->translate('选择')));
        $searchForm->get('user_status')->setValueOptions(Common::userStatus($this->translator));
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

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

        return [
            'userList'      => $paginator,
            'phoneAreaCode' => Common::configValue('list', 'phoneArea'),
            'searchForm'    => $searchForm
        ];
    }

    /**
     * 添加客户
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        $phoneArea  = Common::getPhoneArea();
        $form = new UserForm($phoneArea, $this->entityManager);
        $form->get('userGroupId')->setValueOptions($this->userPlugin()->userGroupOptions());
        $form->get('userSex')->setValueOptions(Common::userSex($this->translator));
        $form->get('userStatus')->setValueOptions(Common::userStatus($this->translator));

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

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $user = $this->userManager->addUser($data);

                $this->getEventManager()->trigger('backstage-user.add.post', $this, ['user' => $user]);

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

                return $this->redirect()->toRoute('user', [], ['query' => $queryData]);
            }
        }

        $form->get('userAvatar')->setValue(Common::configValue('default_user_avatar', 'customer'));

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

    /**
     * 编辑客户
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $userId = (int) $this->params()->fromRoute('id', -1);

        $userInfo = $this->entityManager->getRepository(User::class)->findOneByUserId($userId);
        if($userInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该客户不存在!'));
            return $this->redirect()->toRoute('user');
        }

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

        $phoneArea  = Common::getPhoneArea();
        $form = new UserForm($phoneArea, $this->entityManager, $userInfo);
        $form->get('userGroupId')->setValueOptions($this->userPlugin()->userGroupOptions());
        $form->get('userSex')->setValueOptions(Common::userSex($this->translator));
        $form->get('userStatus')->setValueOptions(Common::userStatus($this->translator));

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $userInfo = $this->userManager->editUser($data, $userInfo);

                $this->getEventManager()->trigger('backstage-user.edit.post', $this, ['user' => $userInfo]);

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

                return $this->redirect()->toRoute('user', ['action' => 'edit', 'id' => $userId], ['query' => $queryData]);
            }
        } else {
            $form->setData($userInfo->valuesArray());
        }
        $form->setData(['userAvatar' => !empty($userInfo->getUserAvatar()) ? $userInfo->getUserAvatar() : Common::configValue('default_user_avatar', 'customer')]);

        $queryData['page'] = $queryData['sPage'];
        unset($queryData['sPage']);

        //收货地址信息
        $userAddress = $this->entityManager->getRepository(UserAddress::class)->findBy(['userId' => $userId]);
        //商品收藏
        $userGoodsFavorites = $this->entityManager->getRepository(UserGoodsFavorites::class)->findGoodsFavorites($userId);
        //客户购物车
        $userCart = $this->entityManager->getRepository(Cart::class)->findUserCartGoods($userInfo->getUserId(), $userInfo->getUserGroupId());
        //第三方登录
        $otherLoginList = $this->entityManager->getRepository(UserOtherLogin::class)->findBy(['userId' => $userId]);
        //第三方绑定名称
        $otherLoginTextName = Common::otherLoginTextName($this->translator);

        return [
            'form'          => $form,
            'userInfo'      => $userInfo,
            'phoneArea'     => $phoneArea,
            'userAddress'   => $userAddress,
            'phoneAreaCode' => Common::configValue('list', 'phoneArea'),
            'userGoodsFavorites' => $userGoodsFavorites,
            'userCart'      => $userCart,
            'queryData'     => $queryData,

            'otherLoginList'    => $otherLoginList,
            'otherLoginTextName'=> $otherLoginTextName
        ];
    }

    /**
     * 删除客户
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $userId = (int) $this->params()->fromRoute('id', -1);

        $userInfo = $this->entityManager->getRepository(User::class)->findOneByUserId($userId);
        if($userInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该客户不存在!'));
            return $this->adminCommon()->toReferer();
        }

        $this->userManager->deleteUser($userInfo);
        $this->adminCommon()->deleteImage($userInfo->getUserAvatar());

        $this->getEventManager()->trigger('backstage-user.delete.post', $this, ['user' => $userInfo]);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('客户 %s 删除成功!'), $userInfo->getUserName()), $this->translator->translate('客户管理'));

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

    /**
     * 客户登录密码修改
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function changeUserPasswordAction()
    {
        $userId     = (int) $this->params()->fromRoute('id', -1);
        $userInfo   = $this->entityManager->getRepository(User::class)->findOneByUserId($userId);
        if($userInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该客户不存在!'));
            return $this->redirect()->toRoute('user');
        }

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

        $form = new ChangeUserPasswordForm();

        if ($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();
                $this->userManager->changeUserPassword($data['userPassword'], $userInfo);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('客户 %s 登录密码修改成功!'), $userInfo->getUserName()), $this->translator->translate('客户管理'));

                return $this->redirect()->toRoute('user', [], ['query' => $queryData]);
            }
        }

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

    /**
     * 客户余额支付密码修改
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function changePayPasswordAction()
    {
        $userId     = (int) $this->params()->fromRoute('id', -1);
        $userInfo   = $this->entityManager->getRepository(User::class)->findOneByUserId($userId);
        if($userInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该客户不存在!'));
            return $this->redirect()->toRoute('user');
        }

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

        $form = new ChangePayPasswordForm();

        if ($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $this->userManager->changePayPassword($data['payPassword'], $userInfo);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('客户 %s 余额支付密码修改成功!'), $userInfo->getUserName()), $this->translator->translate('客户管理'));

                return $this->redirect()->toRoute('user', [], ['query' => $queryData]);
            }
        }

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