<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\ArticleModel;
use app\admin\validate\v1\ArticleValidate;

/**
 * 文章管理控制器
 */
class Article
{
    // 文章列表
    public function index()
    {
        $param = request()->param([
            'title',
            'category_id',
            'release_time',
            'page/d'     => 1,
            'size/d'     => 10,
        ]);

        $article = ArticleModel::withoutField([
                'language_id',
                'author',
                'source',
                'desc',
                'link',
                'content',
                'updated_at',
                'deleted_at',
                'seo_title',
                'seo_keywords',
                'seo_desc'
            ])
            ->with('category')
            ->language(request()->lang_id)
            ->where(function($query) use($param) {
                if (isset($param['category_id'])) {
                    if (str_contains($param['category_id'], ',') || is_array($param['category_id'])) {
                        $query->whereIn('category_id', $param['category_id']);
                    } else {
                        $query->where('category_id', '=', $param['category_id']);
                    }
                }
            })
            ->withSearch(['title', 'release_time'], [
                'title'        => $param['title']??null,
                'release_time' => !empty($param['release_time']) ? explode(',', $param['release_time']) : null
            ])
            ->order('sort', 'desc')
            ->paginate([
                'page'      => $param['page'],
                'list_rows' => $param['size'],
            ])
            ->hidden([
                'category',
                'category_id'
            ])
            ->bindAttr('category', ['category_name' => 'name'])
            ->each(fn($item) => $item->image = thumb($item->image));

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

    // 文章详情
    public function read()
    {
        $article = ArticleModel::with(['category' => function($query) {
                $query->field(['id', 'name' => 'category_name']);
            }])
            ->withoutField([
                'language_id',
                'updated_at',
                'deleted_at',
            ])
            ->bypk(request()->param('id'))
            ->find()
            ?->bindAttr('category', ['category_name'])
            ->hidden(['category']);
        if (is_null($article)) {
            return error('文章不存在');
        }
        if (!$article->inc('view_count', 1)->save()) {
            return error('记录浏览量失败');
        }

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

    // 添加文章
    public function save()
    {
        $post = request()->post([
            'category_id',
            'title',
            'image',
            'link',
            'sort' => 0,
            'desc',
            'content',
            'recommend',
            'release_time',
            'seo_title',
            'seo_keywords',
            'seo_desc',
        ]);
        $data = array_merge($post, ['language_id' => request()->lang_id]);

        $validate = new ArticleValidate;
        if (!$validate->check($data)) {
            return error($validate->getError());
        }

        $article = new ArticleModel;
        if (!$article->save($data)) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    // 更新文章
    public function update()
    {
        $id  = request()->param('id');
        $put = request()->put([
            'category_id',
            'title',
            'image',
            'link',
            'sort',
            'desc',
            'content',
            'recommend',
            'release_time',
            'seo_title',
            'seo_keywords',
            'seo_desc',
        ]);
        $data = array_merge($put, ['language_id' => request()->lang_id]);

        $validate = new ArticleValidate;
        if (!$validate->check(array_merge($data, ['id' => $id]))) {
            return error($validate->getError());
        }

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

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

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

        $article = ArticleModel::bypk($id)->find();
        if (empty($article)) {
            return error('请确认操作对象是否存在');
        }
        if ($sort != $article->sort) {
            $article->sort = $sort;
            if (!$article->save()) {
                return error('操作失败');
            }
        }
        
        return success('操作成功');
    }

    // 删除文章
    public function delete()
    {
        $id = request()->param('id');
        $article = ArticleModel::bypk($id)->find();
        if (is_null($article)) {
            return error('请确认操作对象是否存在');
        }

        if (!$article->useSoftDelete('deleted_at', date('Y-m-d H:m:s', time()))->delete()) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    // 文章导出
    public function export()
    {
        $schema = [
            'id'            => 'ID',
            'category_name' => '文章分类',
            'title'         => '文章名称',
            'author'        => '作者',
            'source'        => '来源',
            'image'         => '封面图片',
            'link'          => '跳转链接',
            'desc'          => '文章描述',
            'content'       => '内容详情',
            'recommend'     => '是否推荐',
            'sort'          => '排序值',
            'view_count'    => '浏览量',
            'praise_count'  => '点赞数',
            'seo_title'     => 'seo标题',
            'seo_keywords'  => 'seo关键词',
            'seo_desc'      => 'seo描述',
            'release_time'  => '发布时间',
            'created_at'    => '添加时间',
            'updated_at'    => '最后更新时间'
        ];

        // 获取导出数据
        $data = $this->getExportArticleData();
        
        // 导出
        return xlsx_writer($data, $schema, '文章列表' . date('YmdHis'));
    }

    // 获取文章导出数据
    private function getExportArticleData()
    {
        $server = request()->server();
        $image_host = $server['REQUEST_SCHEME'] . "://" . $server['SERVER_NAME'] . '/';
        $param = request()->param(['title', 'category_id', 'release_time']);
        $data = ArticleModel::field([
                '*',
                'image',
                'CASE WHEN recommend = 1 THEN "是" ELSE "否" END' => 'recommend'
            ])
            ->with('category', function($query) {
                return $query->field(['id', 'name']);
            })
            ->language(request()->lang_id)
            ->categoryNullable($param['category_id']??null)
            ->withSearch(['title', 'release_time'], [
                'title'        => $param['title']??null,
                'release_time' => !empty($param['release_time'])?explode(',', $param['release_time']):null
            ])
            ->order('sort', 'desc')
            ->select()
            ->hidden([
                'language_id',
                'category_id',
                'category',
            ])
            ->bindAttr('category', ['category_name' => 'name'])
            ->each(function ($item) use($image_host) {
                $item->image = !empty($item->image) ? url_join($image_host, $item->image) : '';
                return $item;
            });

        return $data->toArray();
    }
}
