<?php
namespace app\controller\manager;

use app\model\{Model as MModel, Log};
use app\validate\Model as VModel;
use think\exception\ValidateException;

class Model extends Base 
{
    //批量删除模型
    public function batchDel()
    {
        if($this->request->isPost()){
            $ids = input('post.ids/a');
            if(is_array($ids)) {
                $idsArr = $ids;
            } else {
                $idsArr = array_filter(explode(',', $ids));
            }
            if(count($idsArr) == 0) {
                return $this->json(1, '无效请求，参数错误！');
            }
            $items = MModel::getListByIds($idsArr);
            if(!empty($items)){
                $delIds = [];
                foreach($items as $item){
                    $delIds[] = $item['id'];
                }
                MModel::destroy($delIds);
                Log::write('model', 'batchDel', "模型批量删除，ID：" . implode(',', $ids));
                return $this->json();
            }
            return $this->json(2, '无效请求，参数错误！');
        }
        return $this->json(1, '非法请求！');
    }

    //删除单个模型
    public function del()
    {
        if($this->request->isPost()){
            $id = input('post.id/d');
            if(is_numeric($id) && $id > 0) {
                $item = MModel::getById($id);
                if(!empty($item)) {
                    MModel::destroy($id);
                    Log::write('model', 'del', "模型删除，ID：{$id}, 标题：{$item['name']}");
                    return $this->json();
                }
                return $this->json(3, '删除失败！该模型不存在，请刷新页面后再试！');
            }
            return $this->json(2, '无效请求，参数错误！');
        }
        return $this->json(1, '非法请求！');
    }

    //编辑模型
    public function edit()
    {
        if($this->request->isPost()){
            $item = [];
            $item['name'] = input('post.name');
            $item['template'] = input('post.template');
            $item['manager'] = input('post.manager');
            $id = input('post.id/d');
            if(is_numeric($id) && $id > 0) {
                $model = MModel::getById($id);
                if(empty($model)){
                    return $this->json(2, '无此模型数据!');
                }
                try {
                    validate(VModel::class)->check($item);
                    MModel::updateById($id, $item);
                    Log::write('model', 'edit', "模型编辑，ID：{$id}, 标题：{$item['name']}");
                    return $this->json();
                } catch (ValidateException $e) {
                    return $this->json(3, $e->getError());
                }
            }
            return $this->json(1, '无效请求，参数错误！');
        }else{
            $id = input('param.id/d');
            if (is_numeric($id) && $id > 0) {
                $item = MModel::getById($id);
                $this->data['item'] = $item;
                return $this->view();
            }
            return $this->json(1,'传入参数错误，请核对之后再操作!');
        }
    }

    /**
     * 添加模型
     */
    public function add()
    {
        if($this->request->isPost()){
            $item = [];
            $item['name'] = input('post.name');
            $item['template'] = input('post.template');
            $item['manager'] = input('post.manager');
            try {
                validate(VModel::class)->check($item);
                $model = MModel::create($item);
                Log::write('model', 'add', "模型新增，ID：{$model->id}, 标题：{$item['name']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
        }else {
            return $this->view();
        }
    }

    /**
     * 模型列表
     */
    public function index()
    {
        $items = MModel::getList();
        $this->data['items'] = $items;
        return $this->view();
    }

    /**
     * 排序
     */
    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 = MModel::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 = MModel::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 MModel();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('model', 'sort', "模型排序，ID：{$id} ，标题：{$item['name']}，{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '非法请求!');
    }
}