<?php

namespace app\controller\manager;

use app\model\Log;
use app\repository\CmsRepository;
use app\repository\OperationRepository;
use app\validate\Slide as VSlide;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

class Slide extends Base
{
    /**
     * 编辑
     *
     * @return Json|View
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit()
    {
        $id = $this->request->param('id/d', 0);

        if (!$slide = OperationRepository::getInstance()->findSlideById($id)) {
            return $this->json(4001, '数据不存在');
        }

        if ($this->request->isPost()) {
            $item     = input('post.item/a');
            $validate = new VSlide();
            if (!$validate->scene('slide')->check($item)) {
                return $this->json(4002, $validate->getError());
            }

            unset($item['id']);
            OperationRepository::getInstance()->updateSlide($item, $id);
            return $this->json();
        }

        $this->data['item'] = $slide;
        $this->data['positionsJson']    = $this->xmSelectPositionsJson([$slide['position']]);
        $this->data['id']   = $id;

        return $this->view();
    }

    /**
     * 添加
     *
     * @return View|Json
     */
    public function add()
    {
        $repo = OperationRepository::getInstance();

        if ($this->request->isPost()) {
            $item     = input('post.item/a');
            $validate = new VSlide();
            if (!$validate->scene('slide')->check($item)) {
                return $this->json(4002, $validate->getError());
            }

            $item['type']       = $item['type'] ?? 'img';
            $repo->createSlide($item);
            return $this->json();
        }

        $this->data['positionsJson']    = $this->xmSelectPositionsJson();
        return $this->view();
    }

    /**
     * 轮播图列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function index()
    {
        $repo = OperationRepository::getInstance();
        if ($this->request->isPost()) {
            $position   = $this->request->param('position/s', '');
            $page       = $this->request->param('page/d', 1);
            $size       = $this->request->param('size/d', 30);

            $whereMap   = [];
            $orders     = ['sort'=>'asc'];
            if (!empty($position)) {
                $whereMap[] = ['position', '=', $position];
            }

            $list = $repo->slideList($whereMap, [], $page, $size, null, $orders);

            return $this->json(0, 'success', $list);
        }

        $this->data['positions'] = $repo->slidePositions();
        return $this->view();
    }

    /**
     * 排序
     * @return Json
     */
    public function sort()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }
        try {
            $id     = $this->request->param('id/d', 0);
            $sort   = $this->request->param('sort/d', 0);
            OperationRepository::getInstance()->updateSlide(['sort'=>$sort], $id);
        } catch (Exception $e) {
            return $this->json(4001, '排序失败');
        }
        return $this->json();
    }

    /**
     * 删除
     * @return Json
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $ids = $this->request->param('ids/a', []);
        if (empty($ids)) {
            $ids[] = $this->request->param('id/d', 0);
            $ids = array_filter($ids);
        }

        if (count($ids)) {
            OperationRepository::getInstance()->deleteSlides($ids);
            Log::write(get_class(), 'del', '删除了轮播图,涉及到的ID为:'.implode(',', $ids));
        }
        return $this->json();
    }

    /**
     * 显示位置下拉选项数据
     *
     * @param array $selected
     * @param array $disabled
     * @return false|string
     */
    private function xmSelectPositionsJson(array $selected = [], array $disabled = [])
    {
        $positionList = OperationRepository::getInstance()->slidePositions();
        foreach ($positionList as $k => $item) {
            $positionList[$k]['selected'] = in_array($item['key'], $selected);
            $positionList[$k]['disabled'] = in_array($item['key'], $disabled);
        }
        $positionList = CmsRepository::getInstance()->handleSelectedList($positionList);
        return json_encode($positionList, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 轮播图显示位置管理
     *
     */
    public function position()
    {
        $repo = OperationRepository::getInstance();

        if ($this->request->isPost()) {
            $list = $repo->slidePositionList([], [], 1, 0);

            return $this->json(0, 'success', $list);
        }
        return $this->view();
    }

    /**
     * 添加显示位置信息
     *
     * @return Json|View
     */
    public function addPosition()
    {
        $repo = OperationRepository::getInstance();

        if ($this->request->isPost()) {
            $item     = input('post.item/a');
            try {
                $this->validate($item, [
                    'title|标题' => 'max:250',
                    'key|位置标识' => 'require|max:100|alphaDash'
                ]);
            } catch (ValidateException $e) {
                return $this->json(4002, $e->getError());
            }

            if ($repo->slidePositionExists($item['key'])) {
                return $this->json(4003, '当前位置标识已存在!');
            }

            $repo->createSlidePosition($item);
            return $this->json();
        }

        return $this->view();
    }

    /**
     * 编辑显示位置信息
     *
     * @return Json|View
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function editPosition()
    {
        $id = $this->request->param('id/d', 0);

        if (!$position = OperationRepository::getInstance()->findSlidePositionById($id)) {
            return $this->json(4001, '数据不存在');
        }

        if ($this->request->isPost()) {
            $item     = input('post.item/a');
            try {
                $this->validate($item, [
                    'title|标题' => 'max:250'
                ]);
            } catch (ValidateException $e) {
                return $this->json(4002, $e->getError());
            }

            unset($item['id']);
            unset($item['key']);
            OperationRepository::getInstance()->updateSlidePosition($item, $id);
            return $this->json();
        }

        $this->data['item'] = $position;
        $this->data['id']   = $id;

        return $this->view();
    }

    /**
     * 删除显示位置信息
     * @return Json
     */
    public function delPosition()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $ids = $this->request->param('ids/a', []);
        if (empty($ids)) {
            $ids[] = $this->request->param('id/d', 0);
            $ids = array_filter($ids);
        }

        if (count($ids)) {
            OperationRepository::getInstance()->deleteSlidePositions($ids);
            Log::write(get_class(), 'delPosition', '删除了轮播显示位置,涉及到的ID为:'.implode(',', $ids));
        }

        return $this->json();
    }


}