<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: DefaultController.php
 * Time: 7:52
 */

namespace app\app\controller;


use app\common\controller\BaseController;
use app\common\toolKit\CommonKit;
use app\common\toolKit\SiteKit;
use think\Db;

class DefaultController extends BaseController
{
    public function indexAction()
    {
        return $this->render('index');
    }

    public function channelAction($cid)
    {
        $categoryId = intval($cid);
        $currentCategory = Db::name('category')->where('id', $categoryId)->find();
        $currentCategoryCType = intval($currentCategory['c_type']);
        if (!$currentCategory || $currentCategoryCType === 0 || $currentCategoryCType === 3) {
            return json(['success' => false, 'message' => '栏目不存在']);
        }
        $currentCategoryAllChildren = json_decode($currentCategory['all_children']);
        $allHasArchiveCat = $this->findHasArchiveCat($currentCategoryAllChildren);
        $table = CommonKit::getModelByCType($currentCategoryCType);
        $items = [];
        $perPage = 5;
        $currentPage = intval(input('?get.page') ? input('get.page') : input('post.page', 1));
        $currentPage = $currentPage > 0 ? $currentPage : 1;
        $total = 0;
        if (count($allHasArchiveCat) === 0) {
        } elseif (count($allHasArchiveCat) === 1) {
            $base = Db::name($table)->where('category_id', $allHasArchiveCat[0]);
            $total = $base->count();
            $items = $base->where('category_id', $allHasArchiveCat[0])->order('weight desc,create_time desc')->page($currentPage, $perPage)->select();
        } else {
            $base = Db::name($table)->where('category_id', 'in', implode(',', $allHasArchiveCat));
            $total = $base->count();
            $items = $base->where('category_id', 'in', implode(',', $allHasArchiveCat))->order('weight desc,create_time desc')->page($currentPage, $perPage)->select();
        }
        $hasContent = false;
        if (count($items) > 0) {
            $hasContent = true;
            foreach ($items as &$item){
                $item['url'] = url('detail',['cid'=>$item['category_id'],'aid'=>$item['id']]);
            }
        }
        $hasLastPage = false;
        $hasNextPage = false;
        $lastPage = $currentPage - 1;
        $lastPageUrl = '';
        if ($lastPage > 0) {
            $hasLastPage = true;
            $lastPageUrl = url('channel', ['cid' => $cid, 'page' => $lastPage]);
        }
        $nextPageUrl = '';
        if ($currentPage * $perPage < $total) {
            $nextPage = $currentPage + 1;
            $hasNextPage = true;
            $nextPageUrl = url('channel', ['cid' => $cid, 'page' => $nextPage]);
        }

        $params = [
            'current_cat' => $currentCategory,
            'items' => $items,
            'has_content' => $hasContent,
            'has_last_page' => $hasLastPage,
            'has_next_page' => $hasNextPage,
            'last_page_url' => $lastPageUrl,
            'next_page_url' => $nextPageUrl
        ];
        $tag = $table;
        $viewFile = '';
        if (isset($currentCategory['view']) && !empty($currentCategory['view']) && !is_null($currentCategory['view'])){
            $tag ='';
            $viewFile = trim($currentCategory['view']);
        }
        return $this->render($tag, $params,$viewFile);
    }

    public function listAction($cid)
    {
        $categoryId = intval($cid);
        $currentCategory = Db::name('category')->where('id', $categoryId)->find();
        $currentCategoryCType = intval($currentCategory['c_type']);
        if (!$currentCategory || $currentCategoryCType === 0 || $currentCategoryCType === 3) {
            return json(['success' => false, 'message' => '栏目不存在']);
        }
        $table = CommonKit::getModelByCType($currentCategoryCType);
        $perPage = 5;
        if ($table=='product'){
            $perPage = 8;
        }
        $currentPage = intval(input('?get.page') ? input('get.page') : input('post.page', 1));
        $currentPage = $currentPage > 0 ? $currentPage : 1;

        $base = Db::name($table);
        $total = $base->where('category_id', $categoryId)->count();
        $items = $base->where('category_id', $categoryId)->order('weight desc,create_time desc')->page($currentPage, $perPage)->select();
        $hasContent = false;
        if (count($items) > 0) {
            $hasContent = true;
            foreach ($items as &$item){
                $item['url'] = url('detail',['cid'=>$categoryId,'aid'=>$item['id']]);
            }
        }
        $hasLastPage = false;
        $hasNextPage = false;
        $lastPage = $currentPage - 1;
        $lastPageUrl = '';
        if ($lastPage > 0) {
            $hasLastPage = true;
            $lastPageUrl = url('list', ['cid' => $cid, 'page' => $lastPage]);
        }
        $nextPageUrl = '';
        if ($currentPage * $perPage < $total) {
            $nextPage = $currentPage + 1;
            $hasNextPage = true;
            $nextPageUrl = url('list', ['cid' => $cid, 'page' => $nextPage]);
        }

        $params = [
            'current_cat' => $currentCategory,
            'items' => $items,
            'has_content' => $hasContent,
            'has_last_page' => $hasLastPage,
            'has_next_page' => $hasNextPage,
            'last_page_url' => $lastPageUrl,
            'next_page_url' => $nextPageUrl
        ];
        $tag = $table;
        $viewFile = '';
        if (isset($currentCategory['view']) && !empty($currentCategory['view']) && !is_null($currentCategory['view'])){
            $tag ='';
            $viewFile = trim($currentCategory['view']);
        }
        return $this->render($tag, $params,$viewFile);
    }

    public function detailAction($cid, $aid)
    {
        $categoryId = intval($cid);
        $aid = intval($aid);
        if ($cid===0 || $aid===0){
            return json(['success'=>false, 'message'=>'内容未找到']);
        }
        $table = CommonKit::getModelByCategoryId($cid);
        $item = Db::name($table)->where('id', intval($aid))->find();
        if (!$item) {
            return json(['success'=>false, 'message'=>'内容未找到']);
        }
        $currentCat = CommonKit::getCategoryByCategoryId($categoryId);
        if (count($currentCat)<1){
            return json(['success'=>false, 'message'=>'内容未找到']);
        }
        if ($table=='product'){
            $item['extra'] = json_decode($item['extra']);
        }

        $params = [
            'item' => $item,
            'current_cat'=>$currentCat
        ];
        $tag = $table;
        $viewFile = '';
        if (isset($item['view']) && !empty($item['view']) && !is_null($item['view'])){
            $tag ='';
            $viewFile = trim($item['view']);
        }
        return $this->render($tag, $params,$viewFile);
    }

    public function singleAction($cid)
    {
        $currentCategory = CommonKit::getCategoryByCategoryId(intval($cid));
        if (count($currentCategory)<1){
            return json(['success'=>false, 'message'=>lang('Failure')]);
        }
        $item = Db::name('single')->where('category_id', intval($cid))->find();
        if (!$item) {
            $item = [];
        }
        return $this->render('single', [
            'item' => $item,
            'current_cat'=>$currentCategory
        ]);
    }

    private function findHasArchiveCat($ids)
    {
        $result = [];
        $siteId = SiteKit::currentSiteId();
        $categoryFromCache = cache('categories.site.' . $siteId);
        foreach ($ids as $id) {
            $currentCat = $categoryFromCache[$id];
            $currentCatCType = intval($currentCat['c_type']);
            if (!$currentCat['has_children'] && $currentCatCType !== 0 && $currentCatCType !== 3) {
                array_push($result, $id);
            }
        }
        return $result;
    }
}