<?php

namespace app\adminapi\controller\v1\page;

use app\adminapi\controller\AuthController;
use app\models\page\PageModel;
use crmeb\services\{UtilService as Util};
use think\Request;

class Page extends AuthController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $where = Util::getMore([
            ['page', 1],
            ['limit', 10]
        ], $this->request);
        $list = PageModel::systemPage($where);
        return $this->success($list);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = Util::postMore([
            ['id', 0],
            ['title', ''],
            ['unique', ''],
            ['content', '']
        ]);
        $data['add_time'] = time();
        if ($data['id']) {
            $id = $data['id'];
            unset($data['id']);
            $res = PageModel::edit($data, $id, 'id');
            if($res)
                return $this->success('修改成功!', ['id' => $id]);
            else
                return $this->fail('修改失败!');
        } else {
            $res = PageModel::create($data);
            return $this->success('添加成功!', ['id' => $res->id]);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $info = PageModel::getOne($id);
        return $this->success(compact('info'));
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (!$id) return $this->fail('数据不存在');
        $res = PageModel::get($id);
        if (!$res) return $this->fail('数据不存在!');
        if ($res['is_del']) return $this->fail('已删除!');
        $data['is_del'] = 1;
        if (PageModel::edit($data, $id))
            return $this->success('删除成功!');
        else
            return $this->fail('删除失败,请稍候再试!');
    }

}