<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-06-28
 */

namespace weapp\MakemHtml\controller;

use think\Page;
use think\Db;
use app\common\controller\Weapp;
use weapp\MakemHtml\model\MakemHtmlModel;
use think\Cache;
use app\common\logic\ArctypeLogic;
use app\admin\controller\Base;

/**
 * 插件的控制器
 */
class MakemHtml extends Weapp
{
    /**
     * 实例化模型
     */
    private $model;

    /**
     * 实例化对象
     */
    private $db;

    /**
     * 插件基本信息
     */
    private $weappInfo;

    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();
        $this->model = new MakemHtmlModel;
        $this->db = Db::name('WeappMakemHtml');

        /*插件基本信息*/
        $this->weappInfo = $this->getWeappInfo();
        $this->assign('weappInfo', $this->weappInfo);
        /*--end*/
    }
  /**
     * 插件使用指南
     */
    public function doc()
    {	
		 return $this->fetch();
	}
	
    /**
     * 插件配置
     */
    public function conf()
    {	
		$inc_type =  'seo';
		$config = tpCache($inc_type);
		$config['seo_pseudo'] = tpCache('seo.seo_pseudo');
		$templateConfig['view_path'] = "./template/".TPL_THEME."mobile/";
		 
		if(!file_exists($templateConfig['view_path'])){
		            $templateerror = 1;
					 $this->assign('templateerror', $templateerror);
					 
		  }
		  
		if($config['seo_pseudo']!=2){
			$conf_seo_pseudo = 1;
			$this->assign('conf_seo_pseudo', $conf_seo_pseudo);
		}
		 
		 
        if (IS_POST) {
			$seo_html_arcdir= M('config')->where('id',227)->value('value');
            $post = input('post.');
			$post['value1'] = $seo_html_arcdir;
  
				 $r = Db::name('weapp_makemhtml')
				 ->where('id',1)
				 ->update($post);
				//  echo( Db::getLastSql());die;
                if ($r) {
                    $this->success("操作成功!", weapp_url('MakemHtml/MakemHtml/conf'));
                }
            
            $this->success("操作成功!");
        }
		$seo_html_arcdir = $config['seo_html_arcdir']!=''?substr($config['seo_html_arcdir'],1):'html';
		 
		$row = M('weapp_makemhtml')->where(1)->find(); 
        $this->assign('row', $row);
		$this->assign('seo_html_arcdir', $seo_html_arcdir);
        return $this->fetch('conf');
    }
	
	// 静态生成
 public function build(){
        $config = tpCache('seo');
		$row = M('weapp_makemhtml')->where(1)->value('value');
		 $row = !empty($row) ? $row : '/m';
		$config['seo_html_position']='..'.$row.'/index.html';
		
        $this->assign('config',$config);//当前配置项
		 
        // 栏目列表
        $map = array(
            'status'  => 1,
            'is_del'  => 0, // 回收站功能
            'current_channel'    => ['neq', 51], // 问答模型
            'weapp_code'    => '',
        );
        $arctypeLogic = new ArctypeLogic();
        $select_html = $arctypeLogic->arctype_list(0, 0, true, config('global.arctype_max_level'), $map);
        $this->assign('select_html',$select_html);
        // 允许发布文档列表的栏目
        $arc_select_html = allow_release_arctype();
        $this->assign('arc_select_html', $arc_select_html);
		$row = M('weapp_makemhtml')->where('id',1)->value('value');		 
        $this->assign('row', $row);
	 
        return $this->fetch();
    }
	
    /**
     * 插件后台管理 - 列表
     */
    public function index()
    {
        
		
		/* 纠正栏目的HTML目录路径字段值 */
        $this->correctArctypeDirpath();
        /* end */

        $inc_type =  'seo';
        $config = tpCache($inc_type);
        $config['seo_pseudo'] = tpCache('seo.seo_pseudo');
        $seo_pseudo_list = get_seo_pseudo_list();
        $this->assign('seo_pseudo_list', $seo_pseudo_list);
		 $templateConfig['view_path'] = "./template/".TPL_THEME."mobile/index.htm";
		  
		 if(!file_exists($templateConfig['view_path'])){
			 
					 $templateerror = 1;
					 $this->assign('templateerror', $templateerror);
		   }
		if($config['seo_pseudo']!=2){
			$conf_seo_pseudo = 1;
			$this->assign('conf_seo_pseudo', $conf_seo_pseudo);
		}

        /* 生成静态页面代码 - 多语言统一设置URL模式 */
        $seo_pseudo_lang = '';
        $web_language_switch = tpCache('web.web_language_switch');
        if (is_language() && !empty($web_language_switch)) {
            $markArr = Db::name('language')->field('mark')->order('id asc')->limit('1,1')->select();
            if (!empty($markArr[0]['mark'])) {
                $seo_pseudo_lang = tpCache('seo.seo_pseudo', [], $markArr[0]['mark']);
            }
            $seo_pseudo_lang = !empty($seo_pseudo_lang) ? $seo_pseudo_lang : 1;
        }
        $this->assign('seo_pseudo_lang', $seo_pseudo_lang);
        /* end */

        /* 限制文档HTML保存路径的名称 */
        $wwwroot_dir = config('global.wwwroot_dir'); // 网站根目录的目录列表
        $disable_dirname = config('global.disable_dirname'); // 栏目伪静态时的路由路径
        $wwwroot_dir = array_merge($wwwroot_dir, $disable_dirname);
        // 不能与栏目的一级目录名称重复
        $arctypeDirnames = Db::name('arctype')->where(['parent_id'=>0])->column('dirname');
        is_array($arctypeDirnames) && $wwwroot_dir = array_merge($wwwroot_dir, $arctypeDirnames);
        // 不能与多语言的标识重复
        $markArr = Db::name('language_mark')->column('mark');
        is_array($markArr) && $wwwroot_dir = array_merge($wwwroot_dir, $markArr);
        $wwwroot_dir = array_unique($wwwroot_dir);
        $this->assign('seo_html_arcdir_limit', implode(',', $wwwroot_dir));
        /* end */

        $seo_html_arcdir_1 = '';
        if (!empty($config['seo_html_arcdir'])) {
            $config['seo_html_arcdir'] = trim($config['seo_html_arcdir'], '/');
            $seo_html_arcdir_1 = '/'.$config['seo_html_arcdir'];
        }
        $this->assign('seo_html_arcdir_1', $seo_html_arcdir_1);

        // 栏目列表
        $map = array(
            'status'  => 1,
            'is_del'  => 0, // 回收站功能
            'current_channel'    => ['neq', 51], // 问答模型
            'weapp_code'    => '',
        );
        $arctypeLogic = new ArctypeLogic();
        $select_html = $arctypeLogic->arctype_list(0, 0, true, config('global.arctype_max_level'), $map);
		
        $this->assign('select_html',$select_html);
        // 允许发布文档列表的栏目
        $arc_select_html = allow_release_arctype();
        $this->assign('arc_select_html', $arc_select_html);
        // 生成完页面之后,清除缓存
        $this->buildhtml_clear_cache();

        /*标记是否第一次切换静态页面模式*/
        if (!isset($config['seo_html_arcdir'])) {
            $init_html = 1; // 第一次切换
        } else {
            $init_html = 2; // 多次切换
        }
		
		$cms_version = getCmsVersion();
		$min_version = 'v1.5.7';
		if ($cms_version < $min_version) {
		    $this->error('当前CMS版本太低,该插件要求CMS版本 >= ' . $min_version . ',请升级系统!');
		}
		
		
		//读取手机目录	
		$row = M('weapp_makemhtml')->where('id',1)->find();		 
        $this->assign('row', $row['value']); 
		$this->assign('seo_html_arcdir',$row['value1']);
		 // echo $config['seo_html_arcdir'];die;
        $this->assign('init_html', $init_html);
        /*--end*/

        $this->assign('config',$config);//当前配置项
        return $this->fetch();
    }
 /**
     * 纠正栏目的HTML目录路径字段值
     */
    private function correctArctypeDirpath()
    {
        $system_correctArctypeDirpath = tpCache('system.system_correctArctypeDirpath');
        if (!empty($system_correctArctypeDirpath)) {
            return false;
        }

        $saveData = [];
        $arctypeList = Db::name('arctype')->field('id,parent_id,dirname,dirpath,grade')
            ->order('grade asc')
            ->getAllWithIndex('id');
        foreach ($arctypeList as $key => $val) {
            if (empty($val['parent_id'])) { // 一级栏目
                $saveData[] = [
                    'id'            => $val['id'],
                    'dirpath'       => '/'.$val['dirname'],
                    'grade'         => 0,
                    'update_time'   => getTime(),
                ];
            } else {
                $parentRow = $arctypeList[$val['parent_id']];
                if (empty($parentRow['parent_id'])) { // 二级栏目
                    $saveData[] = [
                        'id'            => $val['id'],
                        'dirpath'       => '/'.$parentRow['dirname'].'/'.$val['dirname'],
                        'grade'         => 1,
                        'update_time'   => getTime(),
                    ];
                } else { // 三级栏目
                    $topRow = $arctypeList[$parentRow['parent_id']];
                    $saveData[] = [
                        'id'            => $val['id'],
                        'dirpath'       => '/'.$topRow['dirname'].'/'.$parentRow['dirname'].'/'.$val['dirname'],
                        'grade'         => 2,
                        'update_time'   => getTime(),
                    ];
                }
            }
        }
        $r = model('Arctype')->saveAll($saveData);
        if (false !== $r) {
            /*多语言*/
            if (is_language()) {
                $langRow = \think\Db::name('language')->order('id asc')
                    ->cache(true, EYOUCMS_CACHE_TIME, 'language')
                    ->select();
                foreach ($langRow as $key => $val) {
                    tpCache('system', ['system_correctArctypeDirpath'=>1],$val['mark']);
                }
            } else {
                tpCache('system',['system_correctArctypeDirpath'=>1]);
            }
            /*--end*/
        }
    }
 
	
    /**
     * 生成完页面之后,清除缓存
     */
    private function buildhtml_clear_cache()
    {
        // 文档参数缓存
        cache("article_info_serialize",null);
        cache("article_page_total_serialize",null);
        cache("article_content_serialize",null);
        cache("article_tags_serialize",null);
        cache("article_attr_info_serialize",null);
        cache("article_children_row_serialize",null);
        // 栏目参数缓存
        cache("channel_page_total_serialize",null);
        cache("channel_info_serialize",null);
        cache("has_children_Row_serialize",null);
    }


  
}