<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;

class Staticstate extends Base
{
    protected $domain = '';

    public function _initialize(){
        $this->domain = "http://" . input('server.HTTP_HOST'); // 获取域名
    }

    public function index(){
        if(request()->isPost()){
            $visitUrl = 'index';
            $createName = 'index.html';
            $this->createHtml($visitUrl, $createName);
            $this->success('首页生成成功！');
        }else{
            return view();
        }
    }

    public function createCategory(){
        if(request()->isPost()){
            // http://studyfoxcms.studyfox.cn/category_28_1.shtml
            $ids = Db::name('category')->where('modelid','neq',0)->column('id');
            foreach ($ids as $id) {
                // 根据分类ID获取相应数据表名
                $tablename = getModInfoById($id, 'tablename');
                // 获取数据表中相应分类记录数，再计算出页数
                $count = Db::name($tablename)->where('catid', $id)->count();
                if($count){
                    $num = ceil($count/5); //进一取整函数
                    for($i = 1; $i<$num+1; $i++){
                        $visitUrl = 'category/id/'.$id.'?page='.$i;
                        $createName = 'category_'.$id.'_'.$i.'.html';
                        $this->createHtml($visitUrl, $createName, true, $id);
                    }
                }
            }
            $this->success('分类页生成成功！');
        }
    }

    public function createInfo(){
        if(request()->isPost()){
            // 获取模型中所有的tablename
            $models = Db::name('models')->column('tablename');
            foreach ($models as $name) {
                $lists = Db::name($name)->field('id,catid')->select();
                if(count($lists)){
                    foreach ($lists as $value) {
                        $visitUrl = 'info/id/'.$value['id'].'/catid/'.$value['catid'];
                        $createName = 'show_'.$value['catid'].'_'.$value['id'].'.html';
                        $this->createHtml($visitUrl, $createName);
                    }
                }
            }
            $this->success('内容页生成成功！');
        }
    }

    public function createHtml($visitUrl, $createName, $hasPage = false, $catid = 0){
        $url = $this->domain . '/index.php/index/index/' . $visitUrl; //动态页面地址
        $fn = ROOT_PATH . 'html/' . $createName; //生成文件名
        
        $content = file_get_contents($url);
        if($hasPage){
            $content = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)", "<a href='category_".$catid."_$1.html'>$2</a>", $content);
        }
        $fs = fopen($fn, 'w');
        fwrite($fs, $content);
    }
}
