<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\AttachmentModel;
use app\admin\validate\v1\AttachmentValidate;

/**
 * 附件（下载管理）管理控制器
 */
class Attachment
{
    /**
     * 分页数据
     */
    public function index()
    {
        $params = request()->param([
            'name',
            'category_id',
            'created_at',
            'page/d' => 1,
            'size/d' => 10
        ]);

        $attachments = AttachmentModel::field([
                'id',
                'image',
                'name',
                'category_id',
                'sort',
                'recommend',
                'created_at'
            ])
            ->with(['category' => function ($query) {
                $query->field(['id', 'name' => 'category_name']);
            }])
            ->withSearch(['name', 'created_at'], [
                'name'       => $params['name']??null,
                'created_at' => !empty($params['created_at']) ? explode(',', $params['created_at']) : null
            ])
            ->language(request()->lang_id)
            ->categoryId($params['category_id']??null)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $params['size'],
                'page'      => $params['page']
            ])
            ->bindAttr('category', ['category_name'])
            ->hidden(['category_id', 'category'])
            ?->each(fn($item) => $item->image = thumb($item->image));

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

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

        $attachment = AttachmentModel::with(['category' => function ($query) {
                $query->field(['id', 'name' => 'category_name']);
            }])
            ->field([
                'id',
                'category_id',
                'name',
                'desc',
                'image',
                'applicable_to',
                'support_platform',
                'attach',
                'sort',
                'recommend',
                'seo_title',
                'seo_keywords',
                'seo_desc'
            ])
            ->bypk($id)
            ->find()
            ->bindAttr('category', ['category_name'])
            ->hidden(['category']);
        if (empty($attachment)) {
            return error('附件不存在');
        }

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

    /**
     * 附件添加
     */
    public function save()
    {
        $post = request()->post([
            'name',
            'desc',
            'category_id',
            'sort',
            'recommend',
            'image',
            'applicable_to',
            'support_platform',
            'attach',
            'seo_title',
            'seo_keywords',
            'seo_desc'
        ]);
        $data = array_merge($post, ['language_id' => request()->lang_id]);

        $validate       = new AttachmentValidate;
        $data['attach'] = json_decode($data['attach'], true);
        if (!$validate->scene('create')->check($data)) {
            return error($validate->getError());
        }

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

    /**
     * 附件更新
     */
    public function update()
    {
        $id  = request()->param('id');
        $put = request()->put([
            'name',
            'desc',
            'category_id',
            'sort',
            'recommend',
            'image',
            'applicable_to',
            'support_platform',
            'attach',
            'seo_title',
            'seo_keywords',
            'seo_desc'
        ]);

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

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

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

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

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

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

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

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

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

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