<?php
namespace app\controller\manager;

use app\model\{Slide as MSlide, System, Log};
use app\validate\Slide as VSlide;
use think\exception\ValidateException;

class Slide extends Base
{
    //批量删除
    public function batchDel()
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a');
            if(empty($ids) || !is_array($ids)) {
                return $this->json(2, '参数错误,请核对之后再操作!');
            }
            $items = MSlide::getListByIds($ids);
            if(!empty($items)){
                $delIds = [];
                foreach($items as $item){
                    $delIds[] = $item['id'];
                }
                MSlide::destroy($delIds);
                Log::write('link', 'betchDel', '批量删除了友情链接,涉及到的ID为:' . implode(',', $delIds));
                return $this->json();
            }else{
                return $this->json(3, '待删除友情链接为空');
            }
        }
        return $this->json(1, '非法请求!');
    }
    //可以删除一个,可以批量删除,TODO 需要调整
    public function del()
    {
        if ($this->request->isPost()) {
            $id = input('post.id/d');
            if(is_numeric($id) && $id > 0) {
                $item = MSlide::getById($id);
                if(!empty($item)){
                    MSlide::destroy($id);
                    Log::write('link', 'del', '删除轮播图,ID:' . $id . ',标题:' . $item['title']);
                    return $this->json();
                }
                return $this->json(3, '待删除轮播图不存在');
            }
            return $this->json(2, '参数错误,请核对之后再操作!');
        }
        return $this->json(1, '非法请求!');
    }
    //排序
    public function sort()
    {
        if($this->request->isPost()){
            $id = input('post.id/d');
            $sort = input('post.sort');
            $num = input('post.num/d', 1);
            if($num <= 0){
                $num = 1;
            }
            if(!in_array($sort, ['up', 'down'], true)){
                return $this->json(2, '参数错误');
            }
            $item = MSlide::getById($id);
            if(empty($item)){
                return $this->json(3, '无此轮播图');
            }
            if($sort == 'up'){
                $where = "sort < {$item['sort']}";
                $order = "sort desc";
            }else{
                $where = "sort > {$item['sort']}";
                $order = "sort asc";
            }
            $forSortItems = MSlide::getListByWhereAndOrder($where, $order, $num);
            if(!empty($forSortItems)){
                $updateData = [];
                $forSortCount = count($forSortItems);
                for($i = 0; $i < $forSortCount; $i++){
                    if($i == 0){
                        $updateData[] = [
                            'id' => $forSortItems[$i]['id'],
                            'sort' => $item['sort']
                        ];
                    }else{
                        $updateData[] = [
                            'id' => $forSortItems[$i]['id'],
                            'sort' => $forSortItems[$i - 1]['sort']
                        ];
                    }
                }
                $updateData[] = [
                    'id' => $item['id'],
                    'sort' => $forSortItems[$i - 1]['sort']
                ];
                if(!empty($updateData)){
                    $model = new MSlide();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('slide', 'sort', "轮播图排序,ID:{$id} ,标题:{$item['title']},{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '非法请求!');
    }

    //编辑
    public function edit()
    {
        if($this->request->isPost()){
            $item           = input('post.item');
            $img            = input('post.img_pc');
            $imgMobile      = input('post.img_mobile');
            $id             = input('post.id/d');

            if(is_numeric($id) && $id > 0) {
                $slide = MSlide::getById($id);
                if(empty($slide)) {
                    return $this->json(2, 'id参数错误,没有相关轮播图信息记录!');
                }
                if(!empty($imgMobile)){
                    $item['src_mobile'] = $imgMobile;
                }
                if(!empty($img)){
                    $item['src'] = $img;
                }
                try {
                    validate(VSlide::class)->check($item);
                    MSlide::updateById($id, $item);
                    Log::write('slide', 'edit', "轮播图编辑,ID:{$id} ,标题:{$item['title']}");
                    return $this->json();
                } catch (ValidateException $e) {
                    return $this->json(3, $e->getError());
                }
            } 
            return $this->json(1, '参数错误,请核对之后再操作!');
        }else{
            $id = input('param.id/d');
            $item = MSlide::getById($id);
            $imgSize = System::getSlideImageSize();
            $this->data['item'] = $item;
            $this->data['img_size'] = $imgSize;
            return $this->view();
        }
    }

    //添加
    public function add()
    {   
        if($this->request->isPost()){
            $item = input('post.item');
            $img = input('post.img_pc');
            $imgMobile = input('post.img_mobile');

            if (empty($item)) {
                return $this->json(1, '参数错误,请核对之后再操作!');
            }
            if(!empty($img)){
                $item['src'] = $img;
            }
            if(!empty($imgMobile)){
                $item['src_mobile'] = $imgMobile;
            }
            try {
                validate(VSlide::class)->check($item);
                $slide = MSlide::create($item);
                Log::write('slide', 'add', "轮播图新增,ID:{$slide->id} ,标题:{$item['title']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(2,$e->getError());
            }
        }else{
            $this->data['img_size'] = System::getSlideImageSize();
            return $this->view();
        }
    }

    /**
     * 列表
     * 暂定只有首页轮播图,后期可以根据需求进行分组管理
     * @return Slide
     */
    public function index()
    {   
        $items = MSlide::getList();
        $this->data['items'] = $items;
        return $this->view();
    }
}