<?php
namespace app\controller\manager;

use app\model\{LinkProduct as MLinkProduct, System, Log};
use app\validate\LinkProduct as VLinkProduct;
use think\exception\ValidateException;

class LinkProduct extends Base
{
    // 封面图推荐尺寸
    protected $imgSize = '210像素 x 190像素';

    //批量删除
    public function batchDel()
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a');
            if(empty($ids) || !is_array($ids)) {
                return $this->json(2, '参数错误,请核对之后再操作!');
            }
            $items = MLinkProduct::getListByIds($ids);
            if(!empty($items)){
                $delIds = [];
                foreach($items as $item){
                    $delIds[] = $item['id'];
                }
                MLinkProduct::destroy($delIds);
                Log::write('LinkProduct', '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 = MLinkProduct::getById($id);
                if(!empty($item)){
                    MLinkProduct::destroy($id);
                    Log::write('LinkProduct', '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 = MLinkProduct::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 = MLinkProduct::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 MLinkProduct();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('LinkProduct', '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 = MLinkProduct::getById($id);
                if(empty($link)) {
                    return $this->json(2, '该合作伙伴信息不存在！');
                }
                if(!empty($img)){
                    $item['src'] = $img;
                }
                try {
                    validate(VLinkProduct::class)->check($item);
                    MLinkProduct::updateById($id, $item);
                    Log::write('LinkProduct', '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 = MLinkProduct::getById($id);

            $this->data['item'] = $item;
            $this->data['img_size'] = $this->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(VLinkProduct::class)->check($item);
                $link = MLinkProduct::create($item);
                Log::write('LinkProduct', 'add', "合作伙伴新增，ID：{$link->id} ，标题：{$item['title']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
        } else {

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

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