<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\AttachmentCategoryModel;
use app\admin\validate\v1\AttachmentCategoryValidate;

/**
 * 附件（下载管理）分类管理控制器
 */
class AttachmentCategory
{
    /**
     * 列表树形结构
     */
    public function tree()
    {
        $params = request()->param([
            'name',
            'is_show'
        ]);

        $categorys = AttachmentCategoryModel::field([
                'id',
                'pid',
                'name'
            ])
            ->withSearch(['name'], [
                'name' => $params['name']??null
            ])
            ->where(function($query) use($params) {
                if (isset($params['is_show'])) {
                    $query->where('is_show', '=', $params['is_show']);
                }
            })
            ->language(request()->lang_id)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();

        return success('获取成功', array_to_tree($categorys->toArray(), 0, 'pid', 1, false));
    }

    /**
     * 分页数据
     */
    public function index()
    {
        $params = request()->param([
            'name'
        ]);

        $categorys = AttachmentCategoryModel::field([
                'id',
                'pid',
                'name',
                'sort',
                'is_show'
            ])
            ->withSearch(['name'], [
                'name' => $params['name']??null
            ])
            ->language(request()->lang_id)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();

        return success('获取成功', array_to_tree($categorys->toArray(), 0, 'pid', 1, false));
    }

    /**
     * 附件分类详情
     */
    public function read()
    {
        $id = request()->param('id');

        $category = AttachmentCategoryModel::withoutField([
                'language_id',
                'created_at',
                'updated_at',
                'deleted_at'
            ])
            ->bypk($id)
            ->find();
        if (empty($category)) {
            return error('分类不存在');
        }

        return success('获取成功', $category);
    }

    /**
     * 附件分类添加
     */
    public function save()
    {
        $post = request()->post([
            'pid' => 0,
            'name',
            'sort',
            'is_show'
        ]);
        $data = array_merge($post, ['language_id' => request()->lang_id]);

        $validate = new AttachmentCategoryValidate;
        if (!$validate->scene('create')->check($data)) {
            return error($validate->getError());
        }

        $category = AttachmentCategoryModel::create($data);
        if ($category->isEmpty()) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    /**
     * 附件分类更新
     */
    public function update()
    {
        $id  = request()->param('id');
        $put = request()->put([
            'pid' => 0,
            'name',
            'sort',
            'is_show'
        ]);

        $validate = new AttachmentCategoryValidate;
        if (!$validate->scene('update')->check(array_merge($put, ['id' => $id]))) {
            return error($validate->getError());
        }

        $category = AttachmentCategoryModel::bypk($id)->find();
        if (empty($category)) {
            return error('请确认操作对象是否存在');
        }

        if (!$category->save($put)) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    /**
     * 设置排序值
     */
    public function sort()
    {
        $id   = request()->param('id');
        $sort = request()->param('sort');

        $validate = new AttachmentCategoryValidate;
        if (!$validate->scene('sort')->check(['sort' => $sort])) {
            return error($validate->getError());
        }

        $category = AttachmentCategoryModel::bypk($id)->find();
        if (empty($category)) {
            return error('请确认操作对象是否存在');
        }

        $category->sort = $sort;
        if (!$category->save()) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    /**
     * 附件分类删除
     */
    public function delete()
    {
        $id = request()->param('id');

        $category = AttachmentCategoryModel::bypk($id)->find();
        if (empty($category)) {
            return error('请确认操作对象是否存在');
        }

        // 检查分类下是否存在附件
        if (!$category->attachment()->count()) {
            return error('分类下存在附件，请先删除附件');
        }

        if (!$category->delete()) {
            return error('操作失败');
        }
        return success('操作成功');
    }
}
