<?php

namespace app\system\controller\v1;

use app\BaseController;
use think\Request;
use library\services\UtilService as Util;
use app\model\system\AttachmentCategory as Category;
use app\model\system\Attachment as AttachmentModel;
/**
 * 图片分类管理类
 * Class AttachmentCategory
 * @package app\system\controller\v1
 */
class AttachmentCategory extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index($name='')
    {
        return app('json')->success(Category::getAll($name));
    }


    /**
     * 保存资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = Util::getMore([
            ['id',0],
            ['pid','0'],
            ['name','','empty','分类名称不能为空！']
        ]);
        if(empty($data['id'])){
            $res = Category::create($data);
            if($res)
                return app('json')->success("添加成功");
            else
                return app('json')->fail('添加失败！');
        }else{
            $res = Category::update($data);
            if($res)
                return app('json')->success("编辑成功");
            else
                return app('json')->fail('编辑失败！');
        }
    }

    public function info(Request $request)
    {
        $data = Util::postMore([
            'id'
        ]);
        $info = Category::getinfo($data['id']);
        return app('json')->success($info);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $chdcount = Category::where('pid',$id)->count();
        if($chdcount) return $this->fail('有子栏目不能删除');
        $chdcount = AttachmentModel::where('pid',$id)->count();
        if($chdcount) return $this->fail('栏目内有图片不能删除');
        if(Category::del($id))
            return app('json')->success('删除成功!');
        else
            return app('json')->fail('删除失败');
    }
}
