<?php

namespace app\controller\manager;

use app\validate\NoticeValidate;
use app\model\{NoticeModel, Category as MCategory, Log as MLog};
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 公示公告
 * Class Notice
 * @package app\controller\manager
 */
class Notice extends Base
{
    /**
     * @return Json|View
     */
    public function add()
    {
        if (request()->isPost()) {
            $params                = input('post.item/a', []);
            $params['create_time'] = time();
            try {
                validate(NoticeValidate::class)->check($params);
                $newItem = NoticeModel::create($params);
                MLog::write(get_class(), 'add', '新增，ID:'.$newItem->id);
            } catch (ValidateException $e) {
                return $this->json(1, $e->getError());
            }
            return $this->json();
        } else {
            $categoryId = input('param.category_id/d', 0);
            $category   = MCategory::getById($categoryId);

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

    /**
     * @return Json|View
     */
    public function edit()
    {
        $id   = input('param.id/d', 0);
        $item = NoticeModel::getById($id);
        if (count($item) == 0) {
            return $this->json(1, '记录不存在');
        }
        if (request()->isPost()) {
            $params = input('post.item/a', []);
            try {
                validate(NoticeValidate::class)->check($params);
                NoticeModel::updateById($id, $params);
                MLog::write(get_class(), 'edit', '修改，ID:'.$id);
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
            return $this->json();
        } else {
            $category   = MCategory::getById($item['category_id']);

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

    public function sort()
    {
        if (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 = NoticeModel::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 = NoticeModel::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 NoticeModel();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    MLog::write(get_class(), 'sort', "排序，ID：{$id} ，{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '无此操作');
    }

    // 删除
    public function del()
    {
        if (request()->isPost()) {
            $historyId = input('param.id/d', 0);
            $item      = NoticeModel::getById($historyId);
            if (count($item) == 0) {
                return $this->json(2, '该记录不存在');
            }
            try {
                NoticeModel::destroy($historyId);
                MLog::write(get_class(), 'del', '删除，ID:'.$historyId);
            } catch (\Exception $e) {
                return $this->json(3, '删除失败，'.$e->getMessage());
            }
            return $this->json();
        }
        return $this->json(1, '无此操作');
    }
}