<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\model\ArticleCategoryModel;
use app\index\model\ArticleLeaveMessageModel;
use app\index\model\ArticleModel;
use app\index\model\SysBannerItemModel;
use think\facade\Validate;
use think\facade\View;

/**
 * 文章控制器
 */
class Article extends Common
{
    /**
     * 文件列表
     */
    public function index()
    {
        // 获取上级分类
        $param = request()->param([
            'pid',
            'cid',
            'keywords' => null,
            'page/d'   => 1,
            'size/d'   => 12,
        ]);

        // 获取banner焦点图
        $banner = SysBannerItemModel::hasWhere('banner', [
                'language_id'  => $this->lang_id,
                'unique_label' => 'BANNER_67f9fc71e27db',
                'at_platform'  => request()->from
            ])
            ->type('image')
            ->visible(['id', 'title', 'image', 'link'])
            ->enabled()
            ->find();
        View::assign('banner', $banner);

        // 获取分类列表
        $categorys = ArticleCategoryModel::field([
                'id',
                'pid',
                'name'
            ])
            ->language($this->lang_id)
            ->parent($param['pid']??null)
            ->isShow(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
        View::assign('categorys', $categorys);

        // 获取文章列表
        if (!$categorys->isEmpty()) {
            $articles = ArticleModel::field([
                    'id',
                    'title',
                    'desc',
                    'image',
                    'release_time'
                ])
                ->withSearch(['title'], ['title' => $param['keywords']??null])
                ->category($param['cid']??$categorys[0]['id'])
                ->order(['sort' => 'asc', 'release_time' => 'desc', 'id' => 'desc'])
                ->paginate([
                    'list_rows' => $param['size'],
                    'page'      => $param['page'],
                    'query'     => request()->param([
                        'cid',
                        'keywords',
                    ]) // 保留查询参数，防止分页丢失
                ]);
        }
        View::assign('articles', $articles??[]);

        return View::fetch('index');
    }

    /**
     * 文章详情
     */
    public function detail()
    {
        $id     = request()->param('id');
        $detail = ArticleModel::withoutField([
                'created_at',
                'updated_at',
                'deleted_at'
            ])
            ->bypk($id)
            ->find();
        View::assign('detail', $detail);

        // 获取分享配置相关
        $share_config = $this->getSysConfig($this->lang_id, ['article_share']);
        View::assign('share_config', $share_config['article_share']);

        // 获取文章评论数据
        $comments = ArticleLeaveMessageModel::field([
                'id',
                'name',
                'email',
                'content',
                'created_at'
            ])
            ->article($id)
            ->audited(true)
            ->order(['id' => 'desc'])
            ->limit(5)
            ->select();
        View::assign('comments', $comments);

        // 获取倒序或发布时间倒序3篇文章做为推荐文章
        $category_model = new ArticleCategoryModel;
        $parent_id      = $category_model->bypk($detail['category_id'])->value('pid');
        $categorys      = $category_model->child($parent_id)->column('id');
        $recommends     = ArticleModel::field([
                'id',
                'title',
                'desc',
                'image'
            ])
            ->where('id', '<>', $id)
            ->language($this->lang_id)
            ->category($categorys)
            ->order(['release_time' => 'desc', 'id' => 'desc'])
            ->limit(3)
            ->select();
        View::assign('recommends', $recommends);

        return View::fetch('detail');
    }

    /**
     * 留言
     */
    public function comment()
    {
        $id   = request()->param('id');
        $post = request()->post([
            'name',
            'email',
            'content'
        ]);

        // 验证字段
        $validate = Validate::rule([
            'name'  => 'require|max:64',
            'email' => 'require|email'
        ])
        ->message([
            'name.require'  => '姓名不能为空',
            'name.max'      => '姓名不能超过:rule个字符',
            'email.require' => '邮箱不能为空',
            'email.email'   => '邮箱格式不正确'
        ]);
        if (!$validate->check($post)) {
            return error($validate->getError());
        }

        // 保存留言
        $data = array_merge($post, [
            'article_id' => $id,
            'ip'         => request()->ip(),
            'user_agent' => request()->header('user-agent')
        ]);
        $ret = ArticleLeaveMessageModel::create($data);
        if ($ret->isEmpty()) {
            return error(lang('信息提交失败！'));
        }

        return success(lang('信息已成功提交！'));
    }
}
