<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\common\api\NoticeApi;
use app\admin\validate\Notice as NoticeValidate;

/**
 * Description of Notice
 *
 * @author sgq
 */
class Notice extends AdminController {

    public function index() {
        return view();
    }

    public function list() {
        $res = NoticeApi::getList($this->request->param());
        return json($res);
    }

    /**
     * @auth {{/notice/add}}
     * @return type
     */
    public function add() {
        if ($this->request->isPost()) {
            try {
                $params = $this->request->param();
                validate(NoticeValidate::class)->check($params);
                if (NoticeApi::edit($params))
                    return json(["msg" => "文章发布成功"]);
                throw new \think\exception("文章发布失败");
            } catch (\think\exception $e) {
                return json(["msg" => $e->getMessage()]);
            }
        }
        return view();
    }

    /**
     * @auth {{/notice/update}}
     * @return type
     */
    public function edit() {
        $params = $this->request->param();
        if ($this->request->isPost()) {
            try {
                validate(NoticeValidate::class)->check($params);
                if (NoticeApi::edit($params))
                    return json(["msg" => "文章编辑成功"]);
                throw new \think\exception("文章编辑失败");
            } catch (\think\exception $e) {
                return json(["msg" => $e->getMessage()]);
            }
        }
        $row = NoticeApi::getOne($params["id"]);
        return view("", ["row" => $row]);
    }

    /**
     * @auth {{/notice/delete}}
     * @return type
     */
    public function delete() {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $id = $params["id"];
            if (NoticeApi::delete($id))
                return json(["msg" => "删除成功"]);
            return json(["msg" => "删除失败"]);
        }
    }

    /**
     * @auth {{/notice/delete}}
     * @return type
     */
    public function top() {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $id = $params["id"];
            if (NoticeApi::setTop($id))
                return json(["msg" => "置顶成功"]);
            return json(["msg" => "置顶失败"]);
        }
    }

}
