<?php

namespace app\controller;

use app\model\{Article as MArticle,
    Category,
    Model
};
use page\DxtcPageA;
use think\Collection;
use think\Paginator;

class Article extends Base
{

    //详情
    public function detail($id = 0)
    {
        if ($id <= 0) {
            return $this->error('错误页面');
        }
        $article = MArticle::getById($id);
        if (empty($article)) {
            return $this->error('无此文章');
        }

        MArticle::updateById($id, ['views' => $article['views'] + 1]);
        $category = Category::getById($article['category_id']);

        $description = $article['seo_description'] ?: $this->system['seo_description'];
        $keywords    = $article['seo_keywords'] ?: $this->system['seo_keywords'];
        $title       = $article['seo_title'] ?: $article['title'].' | '.$this->system['seo_title'];


        $this->data['images'] = json_decode($this->isMobile ? $article['imgs_mobile'] :$article['imgs'], true);
        $this->data['resource'] = json_decode($this->isMobile ? $article['other_text2'] :$article['other_text1'], true);

        $this->setSeo($title, $keywords, $description);
        $this->data['firstBg']       = $this->firstBanner($category);
        $this->data['item']          = MArticle::parseInfo($article);
        $this->data['category']      = $category;
//        $this->data['secondInfo']    = $secondCategory;
        $this->data['categoryId']    = $category['id'];
        $this->data['categoryPath']  = Category::categoryPath($category['path']);
        $this->data['topCategoryId'] = Category::firstGradeId($category['path'], $category['id']);
        $this->detailPrevAndNext($article);
        $this->detailRecommendList($article, $category['recommend_num']);
        return $this->view($category['template_detail'] ?? 'news_detail');
    }

    // 上下篇
    private function detailPrevAndNext($article)
    {
        $prev = [];
        $next = [];

        if ($article) {
            $sortCategoryIds = [];

            /*
            $caseCategoryIds = Category::getCategoryWithChildrenIds(Category::CATEGORY_COMMUNITY);
            if(in_array($article['category_id'], $caseCategoryIds)) {
                $sortCategoryIds = $caseCategoryIds;
            }
            */

            if (!empty($sortCategoryIds)) {
                $prevWhere = [
                    ['sort', '>', $article['sort']],
                    ['category_id', 'in', $sortCategoryIds]
                ];
                $prevOrder = ['a.sort' => 'asc'];
                $prev      = MArticle::getPrevArticleByTimeAndCategoryIds($prevWhere, $prevOrder);
                $nextWhere = [
                    ['sort', '<', $article['sort']],
                    ['category_id', 'in', $sortCategoryIds]
                ];
                $nextOrder = ['sort' => 'desc'];
                $next      = MArticle::getNextArticleByTimeAndCategoryIds($nextWhere, $nextOrder);
            } else {
                $prev = MArticle::getPrevArticleBySortAndCategoryId($article['sort'], $article['category_id']);

                $next = MArticle::getNextArticleBySortAndCategoryId($article['sort'], $article['category_id']);

            }
        }

        $this->data['prev'] = $prev;
        $this->data['next'] = $next;
    }

    // 相关推荐
    private function detailRecommendList($article, $num = 8)
    {
        // 目前规则为：除当前以外的同栏目下最新8个
        $orderList = ['top' => 'desc', 'recommend' => 'desc', 'id' => 'desc'];
        $list      = MArticle::getLastTopList($article['category_id'], $num, [$article['id']], $orderList);

        $this->data['recommendList'] = $list;
    }

    //列表页
    public function index($categoryId = 0)
    {
        $categoryId = empty($categoryId) ? $this->request->param("category_id") : $categoryId;
        $category   = Category::getById($categoryId);
        if (!$category || $category['model_id'] != Model::MODEL_ARTICLE) {
            return $this->error('错误页面');
        }

        $description = $category['seo_description'] ?: $this->system['seo_description'];
        $keywords    = $category['seo_keywords'] ?: $this->system['seo_keywords'];
        $title       = $category['seo_title'] ?: $category['title'].' | '.$this->system['seo_title'];
        $this->setSeo($title, $keywords, $description);

        // 自定义分页驱动
        app('think\App')->bind(Paginator::class, DxtcPageA::class);

        $this->data['categoryPath']  = Category::categoryPath($category['path']);
        $this->data['topCategoryId'] = Category::firstGradeId($category['path'], $categoryId);

        $items = MArticle::getList($categoryId, $category['number'] ?? 10);
        foreach ($items as $item) {
            $item['uri']             = archiveGetUri($item);
            $item['create_date_d']   = date('d', $item['create_time']);
            $item['create_date_y_m'] = date('Y.m', $item['create_time']);
        }
        $this->data['items']    = $items;
        $this->data['category'] = $category;

        $this->data['categoryId']    = $categoryId;
        $this->data['topCategoryId'] = Category::firstGradeId($category['path'], $categoryId);
        $this->data['bodyClass']     = 'main';

        return $this->view($category['template_list'] ?? '/news_list');
    }

    //文章列表接口，获取栏目下文章列表
    public function ajaxList()
    {
        $categoryId = input('category_id/d', 0);
        $keyword    = input('keyword/s', '');
        $page       = input('page/s', 1);

        if ($categoryId <= 0) {
            return $this->json(1, '参数错误');
        }
        $category = Category::getById($categoryId);
        if (empty($category)) {
            return $this->json(2, '栏目不存在');
        }

        $items = MArticle::findListByWhere(["category_id" => $categoryId], $page, $category['number']);

        foreach ($items as $item) {
            $item['uri']             = archiveGetUri($item);
            $item['create_date_d']   = date('d', $item['create_time']);
            $item['create_date_y_m'] = date('Y-m', $item['create_time']);
        }

        return $this->json(0, 'ok', $items);
    }

    //文章列表接口，获取栏目下文章列表
    public function getList()
    {
        $categoryId = input('category_id/d', 0);
        $page       = input('page/d', 1);
        $size       = input('size/d', 10);

        if ($categoryId <= 0) {
            return $this->json(1, '参数错误');
        }
        $category = Category::getById($categoryId);
        if (empty($category)) {
            return $this->json(2, '栏目不存在');
        }

        $items = MArticle::findListByWhere(["category_id" => $categoryId], $page, $size);

        foreach ($items as $item) {
            $item['uri']             = archiveGetUri($item);
            $item['create_date_d']   = date('d', $item['create_time']);
            $item['create_date_y_m'] = date('Y-m', $item['create_time']);
            $item['src']             = $this->isMobile ? $item['src_mobile'] : $item['src'];
        }

        return $this->json(0, 'ok', $items);
    }

    //获取活动列表
    public function getActivity()
    {
        $categoryId = input('category_id/d', 0);
        $page       = input('page/d', 1);
        $size       = input('size/d', 10);

        if ($categoryId <= 0) {
            return $this->json(1, '参数错误');
        }
        $category = Category::getById($categoryId);
        if (empty($category)) {
            return $this->json(2, '栏目不存在');
        }

        $items = MArticle::findListByWhere(["category_id" => $categoryId, 'is_prev' => 0], $page, $size);

        foreach ($items as $item) {
            $item['uri']             = archiveGetUri($item);
            $item['src']             = $this->isMobile ? $item['src_mobile'] : $item['src'];
        }

        return $this->json(0, 'ok', $items);
    }
}