<?php
namespace app\controller\manager;

use app\model\{Article as MArticle, Category, System, Log};
use app\validate\Article as VArticle;
use think\exception\ValidateException;

/**
 * 内容管理 - 文章管理
 */
class Article extends Base
{
    //批量修改属性
    public function attribute()
    {
        if($this->request->isPost()){
            $ids = input('post.id/a');
            if(empty($ids) || !is_array($ids)) {
                return $this->json(2, '参数错误,请核对之后再操作!');
            }
            $data = [];
            foreach(['top', 'hot', 'recommend'] as $key){
                $val = input('post.'.$key, 0);
                if(in_array($val, [1, 2])){
                    if($val == 1){
                        $data[$key] = 1;
                    }else{
                        $data[$key] = 0;
                    }
                }
            }
            if(!empty($data)){
                MArticle::whereIn('id', $ids)->update($data);
                Log::write('article', 'attribute', '批量修改了文章属性,涉及到的文章ID为:' . implode(',', $ids));
            }
            return $this->json();
        }
        return $this->json(1, '非法请求!');
    }
    //批量删除
    public function batchDel()
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a');
            if(empty($ids) || !is_array($ids)) {
                return $this->json(2, '参数错误,请核对之后再操作!');
            }
            $items = MArticle::getListByIds($ids);
            if(!empty($items)){
                $delIds = [];
                foreach($items as $item){
                    $delIds[] = $item['id'];
                }
                MArticle::destroy($delIds);
                Log::write('article', '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 = MArticle::getById($id);
                if(!empty($item)){
                    MArticle::destroy($id);
                    Log::write('article', '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 = MArticle::getById($id);
            if(empty($item)){
                return $this->json(3, '该文章信息不存在');
            }
            if($sort == 'up'){
                $where = "category_id='{$item['category_id']}' and sort > {$item['sort']}";
                $order = "sort asc";
            }else{
                $where = "category_id='{$item['category_id']}' and sort < {$item['sort']}";
                $order = "sort desc";
            }
            $forSortItems = MArticle::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 MArticle();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('article', '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');
            $img = input('post.img');
            $id = input('post.id/d');
            $article = MArticle::getById($id);
            if (empty($article)) {
                return $this->json(1, '该文章不存在!');
            }
            if(!empty($img)){
                $item['src'] = $img;
            }
            try {
                validate(VArticle::class)->check($item);
                $auth = session('auth');
                $item['update_time'] = time();
                $item['updated'] = $auth['userName'];
                MArticle::updateById($id, $item);
                Log::write('article', 'edit', "文章编辑,ID:{$id} ,标题:{$item['title']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
        }else{
            $id = input('param.id');
            $article = MArticle::getById($id);
            $category = Category::getById($article['category_id']);
            if($category['img_width'] && $category['img_height']){
                $imgSize = $category['img_width'] . '像素 X ' . $category['img_height'] . '像素';
            }else{
                $imgSize = System::getArticleImageSize();
            }
            $this->data['item'] = $article;
            $this->data['category'] = $category;
            $this->data['imgSize'] = $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(VArticle::class)->check($item);
                $content = $item['content'] ?? '';
                if(isset($item['content'])){
                    unset($item['content']);
                }
                $item['content'] = $content;
                $article = MArticle::create($item);
                Log::write('article', 'add', "文章新增,ID:{$article->id} ,标题:{$item['title']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
        }else{
            $categoryId = input('param.category_id');
            $category = Category::getById($categoryId);
            if(count($category) > 0 && $category['img_width'] && $category['img_height']){
                $imgSize = $category['img_width'] . '像素 X ' . $category['img_height'] . '像素';
            }else{
                $imgSize = System::getArticleImageSize();
            }

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