<?php
namespace app\controller\manager;

use app\model\{Link as MLink, System, Log};
use app\validate\Link as VLink;
use think\exception\ValidateException;

class Link 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 = MLink::getListByIds($ids);
            if(!empty($items)){
                $delIds = [];
                foreach($items as $item){
                    $delIds[] = $item['id'];
                }
                MLink::destroy($delIds);
                Log::write('link', 'betchDel', '批量删除了友情链接,涉及到的ID为:' . implode(',', $delIds));
                return $this->json();
            }else{
                return $this->json(3, '待删除友情链接为空');
            }
        }
        return $this->json(1, '非法请求!');
    }
    //删除
    public function del()
    {
        if ($this->request->isPost()) {
            $id = input('post.id/d');
            if(is_numeric($id) && $id > 0) {
                $item = MLink::getById($id);
                if(!empty($item)){
                    MLink::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 = MLink::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 = MLink::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 MLink();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('link', '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/a');
            $id = input('post.id/d');
            $img = input('post.img');
            if(is_numeric($id) && $id > 0) {
                $link = MLink::getById($id);
                if(empty($link)) {
                    return $this->json(2, '该友情链接信息不存在!');
                }
                if(!empty($img)){
                    $item['src'] = $img;
                }
                try {
                    validate(VLink::class)->check($item);
                    MLink::updateById($id, $item);
                    Log::write('link', '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 = MLink::getById($id);
            $imgSize = System::getLinkImageSize();

            $this->data['item'] = $item;
            $this->data['img_size'] = $imgSize;
            return $this->view();
        }
    }

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

            if(!empty($img)){
                $item['src'] = $img;
            }
            try {
                validate(VLink::class)->check($item);
                $link = MLink::create($item);
                Log::write('link', 'add', "友情链接新增,ID:{$link->id} ,标题:{$item['title']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
        } else {
            $imgSize = System::getLinkImageSize();
            $this->data['img_size'] = $imgSize;
            return $this->view();
        }
    }

    public function index()
    {
        $items = MLink::getList();
        $this->data['items'] = $items;
        return $this->view();
    }
}