<?php
namespace app\controller\manager;

use app\model\{Category as MCategory, Model as MCModel, Log};
use app\validate\Category as VCategory;
use think\exception\ValidateException;
use think\facade\Cache;

class Category extends Base
{
    //栏目列表
    public function index()
    {
        $auth = session('auth');
        $authCates = array_filter(explode(',', $auth['cates']));
        if ($auth['groupId'] == 1) {
            $cates = MCategory::getList();
        } else {
            $cates = MCategory::getList(true, $authCates);
        }
        $items = MCategory::getCates($cates);

        $powerAdd  = false;
        $ruleNames = Cache::get('rule_names_'.$auth['groupId']);
        if (is_array($ruleNames) && in_array('category/add', $ruleNames, true)) {
            $powerAdd = true;
        }

        $this->data['items'] = $items;
        $this->data['power_add'] = $powerAdd;
        return $this->view();
    }

    //批量删除
    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, '无效请求,参数错误!');
            }
            if (MCategory::hasChildren($idsArr)) {
                return $this->json(2, '需删除的栏目下存在下级栏目,不可删除。请检查核实后再操作!');
            }
            $categories = MCategory::getListByIds($idsArr);
            if(!empty($categories)){
                $hasIds = [];
                foreach($categories as $cate){
                    $hasIds[] = $cate['id'];
                }
                MCategory::destroy($hasIds);
                Log::write('category', 'betchDel', '批量删除了栏目,涉及到的ID为:' . implode(',', $hasIds));
                return $this->json();
            }
            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) {
                if(MCategory::hasChildren($id)){
                    return $this->json(4, '此栏目有下级栏目,不可删除。请检查核实后再操作!');
                }
                $cate = MCategory::getById($id);
                if(!empty($cate)){
                    MCategory::destroy($id);
                    Log::write('category', 'del', '删除栏目,ID:' . $id . ',标题:' . $cate['title']);
                    return $this->json();
                }
                return $this->json(3, '删除失败!栏目不存在,请刷新页面后再试!');
            } else {
                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 = MCategory::getById($id);
            if(empty($item)) {
                return $this->json(3, '无此栏目!');
            }
            if($sort == 'up'){
                $where = "parent_id='{$item['parent_id']}' and sort < {$item['sort']}";
                $order = "sort desc";
            }else{
                $where = "parent_id='{$item['parent_id']}' and sort > {$item['sort']}";
                $order = "sort asc";
            }
            $forSortItems = MCategory::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 MCategory();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('category', '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');
            $img = input('post.img');
            if (count($item) > 0 && (is_numeric($id) === true && $id > 0)) {
                try {
                    validate(VCategory::class)->check($item);
                    if(!empty($img)){
                        $item['src'] = $img;
                    }
                    MCategory::updateById($id, $item);
                    Log::write('category', 'edit', "栏目编辑,ID:{$id} ,标题:{$item['title']}");
                    return $this->json();
                } catch (ValidateException $e) {
                    return $this->json(2, $e->getError());
                }
            }
            return $this->json(1,'传入参数错误,请核对之后再操作!');
        } else {
            $id = input('param.id');
            if (is_numeric($id) === true && $id > 0) {
                $item = MCategory::getById($id);
                if(empty($item)){
                    return $this->json(1,'参数错误,无此栏目!');
                }

                $this->data['item'] = $item;
                $this->data['parent'] = MCategory::getById($item['parent_id']);
                $this->data['models'] = MCModel::getList();
                return $this->view();
            }
            return $this->json(1,'参数错误,请核对之后再操作!');
        }
    }

    /**
     * 栏目添加
     */
    public function add()
    {
        if($this->request->isPost()){
            $item = input('post.item/a');
            $img = input('post.img');
            if (is_array($item) === true && count($item) > 0) {
                if (!empty($img)) {
                    $item['src'] = $img;
                }
                try {
                    validate(VCategory::class)->check($item);
                    if(!isset($item['number']) || $item['number'] <= 0){
                        $item['number'] = 20;
                    }
                    if($item['parent_id'] == 0){
                        $item['path'] = ',0,';
                    }else{
                        $parent = MCategory::getById($item['parent_id']);
                        if(empty($parent)){
                            $item['path'] = ',0,';
                        }else{
                            $item['path'] = $parent['path'] . $parent['id'] . ',';
                        }
                    }
                    $category = MCategory::create($item);
                    Log::write('category', 'add', "栏目新增,ID:{$category->id} ,标题:{$item['title']}");
                    return $this->json();
                } catch (ValidateException $e) {
                    return $this->json(2,$e->getError());
                }
            }
            return $this->json(1, '传入值错误,请核对之后再操作!');
        } else {
            $parentId = input('param.id')??input('param.parent_id');
            if(empty($parentId)){
                $parent = [];
            }else{
                $parent = MCategory::getById($parentId);
            }
            $this->data['parent'] = $parent;
            $this->data['models'] = MCModel::getList();
            return $this->view();
        }
    }
}