<?php
namespace Home\Controller;
use Think\Controller;

define("PAGE_COUNT", 20);

class IndexController extends Controller
{
    public function index()
    {
        //参数列表
        $paramCategory = '';
        $paramPage = '';
        if (I()) {
            $paramCategory = I('get.category', '', 'htmlspecialchars');
            $paramPage = I('get.page', '0', 'htmlspecialchars');
        }
        $this->assign('paramCategory', $paramCategory);
        $this->assign('paramPage', $paramPage);

        //分类信息
        $modelCategory = D('pcategory');
        $categoryList = $modelCategory->where('is_del=0')->select();
        array_unshift($categoryList, array(
            'id' => '',
            'category' => '全部',
            'url' => ''
        ));
        foreach ($categoryList as &$value) {
            $categoryUrl = '/index/index';

            if ($value['category'] != '全部') {
                $categoryUrl = $categoryUrl . '/category/' . $value['id'];
            }

            $value['url'] = $categoryUrl;
        }

        $this->assign('categoryList', $categoryList);

        //当前分类
        $Model = new \Think\Model();
        $currectCategory = array();
        if ($paramCategory != '') {
            $currectCategory = $this->getlCategoryBycategoryID($Model, $paramCategory);
            $this->assign('currectCategory', $currectCategory);
        }

        //分类条件
        $sqlCategory = '';
        if ($paramCategory != '') {
            $sqlCategory = ' AND `id` IN (SELECT pid FROM `program_category` WHERE `cid`=' . $paramCategory . ')';
        }
        //排序
        $sortTime = ' ORDER BY `tm` DESC';

        //分页
        $programListStart = (int)$paramPage * PAGE_COUNT;
        $sqlLimit = ' LIMIT ' . $programListStart  . ',' . PAGE_COUNT;
        $time = time();
        $nowtime=' AND tm <= ' . $time . '';
        $programList = $Model->query('SELECT `id`, `name`, `logo`, `introduce`, FROM_UNIXTIME(`tm`, \'%Y.%m.%d\') AS ptm FROM `program` WHERE `is_del`=0 ' . $nowtime . $sqlCategory . $sqlTime . $sortTime . $sqlLimit);

        foreach ($programList as &$program) {
            $program['category'] = $paramCategory==''? $this->getlCategoryByProgramID($Model, $program['id']): $currectCategory;
            $program['label'] = $this->getlLabelByProgramID($Model, $program['id']);
        }
        $this->assign('programList', $programList);

        //总数量
        $programListCountRes = $Model->query('SELECT COUNT(`id`) as count FROM `program` WHERE `is_del`=0 ' . $nowtime.$sqlCategory . $sqlTime . $sortTime);
        $programListCount = $programListCountRes[0]['count'];
        $this->assign('programListCount', $programListCount);

        //页数
        $programPageCount = ceil((int)$programListCount / PAGE_COUNT);
        $this->assign('programPageCount', $programPageCount);

        //分页信息 -- start
        $programPage = array();
        $pageUrl = '/Index/index';
        if($paramCategory != '') {
            $pageUrl = $pageUrl . '/category/' . $paramCategory;
        }
        if($paramTime != '') {
            $pageUrl = $pageUrl . '/time/' . $paramTime;
        }
        if($paramSort != '') {
            $pageUrl = $pageUrl . '/sort/' . $paramSort;
        }
        $istart = 0;
        $iEnd = $programPageCount;
        if($programPageCount > 7) {
            if((int)$paramPage > 3 && (int)$paramPage  + 3 < $programPageCount) {
                $istart = (int)$paramPage - 3;
                $iEnd = (int)$paramPage + 4;
            } else if ((int)$paramPage  + 3 >= $programPageCount){
                $istart = $programPageCount - 7;
            } else if ((int)$paramPage <= 3) {
                $iEnd = 7;
            }
        }

        for ($i=$istart; $i<$iEnd; $i++) {
            $programPage[$i] = array(
                'title' => $i + 1,
                'url' => $pageUrl . '/page/' . $i,
                'currect' => ($i == (int)$paramPage)?'1':'0'
            );
        }
        $this->assign('programPage', $programPage);

        $prePageUrl = '#';
        if((int)$paramPage != 0) {
            $prePageUrl = $pageUrl . '/page/' . ((int)$paramPage - 1);
        }
        $this->assign('prePageUrl', $prePageUrl);

        $nextPageUrl = '#';
        if((int)$paramPage != $programPageCount - 1) {
            $nextPageUrl = $pageUrl . '/page/' . ((int)$paramPage + 1);
        }
        $this->assign('nextPageUrl', $nextPageUrl);
        //分页信息 -- End

        //SEO
        if($paramCategory==''){
           $seo=array(
               "title" => '微信小程序 - 首页',
           );
        }else{
            $categoryInfo=M('pcategory')->where(array('id'=>$paramCategory))->find();
            $seo= array(
                "title" => $categoryInfo['category'].'-微信小程序',
                "keywords" => $categoryInfo['category'],
                "description" => $categoryInfo['introduce'],
            );
        }
        $this->assign('seo',$seo);

        $this->display('index');
    }

    public function detail()
    {

        $programID = I('get.id', '', 'htmlspecialchars');
        if ($programID == '') {
            header('Location: https://www.zhuige.com/');
            die();
        }
        $time = time();
        $nowtime = ' AND tm <= ' . $time . '';
        $modelProgram = D('program');
        $programList = $modelProgram->where('id=' . $programID . ' AND is_del=0 ' . $nowtime)->select();


        if (count($programList) > 0) {
            $Model = new \Think\Model();

            $program = $programList[0];
            $labels = $this->getlLabelByProgramID($Model, $program['id']);
            $program['label'] = $labels;
            $program['ctegory'] = $this->getlCategoryByProgramID($Model, $program['id']);

            $this->assign('program', $program);

            //增加小程序查看次数
            $modal = new \Think\Model();
            $this->increaseProgramViews($program['id'], $modal);

            //SEO -- start
            $keywords = '';
            $labelCount = count($labels);
            for ($i = 0; $i < $labelCount; $i++) {
                $label = $labels[$i];
                $keywords .= $label['name'];
                if ($i != ($labelCount - 1)) {
                    $keywords .= ',';
                }
            }

            $this->assign('seo', array(
                "title" => $program['name'] . "-微信小程序",
                "keywords" => $keywords,
                "description" => $program['introduce'],
            ));
            //SEO -- end
            $this->assign('programID', $programID);
            $this->display("detail");
        } else {
            header("Location:/Error/index/code/404");
        }
    }

    //标签列表
    public function tagList()
    {
        $paramTag = '';
        $paramPage = '';
        if (I()) {
            $paramTag = I('get.tag', '', 'htmlspecialchars');
            $paramPage = I('get.page', '0', 'htmlspecialchars');
        }
        $this->assign('paramTag', $paramTag);
        $this->assign('paramPage', $paramPage);

        $Model = new \Think\Model();
        $tagName = '';
        if ($paramTag != '') {
            //获取tag的名字
            $TagList = $Model->query('SELECT `name` FROM `plabel` WHERE `id`=' . $paramTag);
            if (count($TagList) > 0) {
                $tagName = $TagList[0]['name'];
            }
        }
        $this->assign('tagName', $tagName);

        //文章列表过滤
        $sqlTag = '';
        if ($paramTag != '') {
            $sqlTag = ' AND `id` IN (SELECT pid FROM `program_label` WHERE `lid`=' . $paramTag . ')';
        }

        //分页
        $programListStart = (int)$paramPage * PAGE_COUNT;
        $sqlLimit = ' LIMIT ' . $programListStart . ',' . PAGE_COUNT;
        $time = time();
        $nowtime = ' AND tm <= ' . $time . '';
        $programList = $Model->query('SELECT `id`, `name`, `logo`, `introduce`, FROM_UNIXTIME(`tm`, \'%Y.%m.%d\') AS ptm FROM `program` WHERE `is_del`=0 ' . $nowtime . $sqlTag . ' ORDER BY `tm` DESC' . $sqlLimit);

        foreach ($programList as &$program) {
            $program['category'] = $paramCategory == '' ? $this->getlCategoryByProgramID($Model, $program['id']) : $currectCategory;
            $program['label'] = $this->getlLabelByProgramID($Model, $program['id']);
        }
        $this->assign('programList', $programList);

        //总数量
        $programListCountRes = $Model->query('SELECT COUNT(`id`) as count FROM `program` WHERE `is_del`=0  ' . $nowtime . $sqlTag);
        $programListCount = $programListCountRes[0]['count'];
        $this->assign('programListCount', $programListCount);

        //页数
        $programPageCount = ceil((int)$programListCount / PAGE_COUNT);
        $this->assign('programPageCount', $programPageCount);

        //分页信息 -- start
        $programPage = array();
        $pageUrl = '/Index/tagList';
        if ($paramTag != '') {
            $pageUrl = $pageUrl . '/tag/' . $paramTag;
        }
        for ($i = 0; $i < $programPageCount; $i++) {
            $programPage[$i] = array(
                'title' => $i + 1,
                'url' => $pageUrl . '/page/' . $i,
                'currect' => ($i == (int)$paramPage) ? '1' : '0'
            );
        }
        $this->assign('programPage', $programPage);

        $prePageUrl = '#';
        if ((int)$paramPage != 0) {
            $prePageUrl = $pageUrl . '/page/' . ((int)$paramPage - 1);
        }
        $this->assign('prePageUrl', $prePageUrl);

        $nextPageUrl = '#';
        if ((int)$paramPage != $programPageCount - 1) {
            $nextPageUrl = $pageUrl . '/page/' . ((int)$paramPage + 1);
        }
        $this->assign('nextPageUrl', $nextPageUrl);
        //分页信息 -- End

        $this->assign('seo', array(
            "title" => $tagName . "-" . '微信小程序',

        ));

        $this->display('tag_list');
    }

    //增加小程序查看次数
    private function increaseProgramViews($id, $modal)
    {
        $res = $modal->execute('UPDATE `program` SET `views`=`views`+1 WHERE `id`=' . $id);
    }

    //获取小程序分类信息
    private function getlCategoryByProgramID($Model, $programID)
    {
        $categoryList = $Model->query('SELECT `pcategory`.`id`, `pcategory`.`category` FROM `pcategory`, `program_category`, `program` WHERE `program`.`id`=' . $programID . ' AND `pcategory`.`id`=`program_category`.`cid` AND `program`.`id` = `program_category`.`pid`');

        if (count($categoryList) == 0) {
            return '未分类';
        } else {
            return $categoryList[0];
        }
    }

    //获取小程序分类信息
    private function getlCategoryBycategoryID($Model, $categoryID)
    {
        $category = $Model->query('SELECT `id`, `category` FROM `pcategory` WHERE `pcategory`.`id`=' . $categoryID);

        if (count($category) == 0) {
            return '未分类';
        } else {
            return $category[0];
        }
    }

    //获取小程序tag
    private function getlLabelByProgramID($Model, $programID) {
        $labelList = $Model->query('SELECT `plabel`.`id`, `plabel`.`name` FROM `plabel`, `program_label`, `program` WHERE `program`.`id`=' . $programID . ' AND `plabel`.`id`=`program_label`.`lid` AND `program`.`id` = `program_label`.`pid`');

        return $labelList;
    }

}