<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-09
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\Db;
use app\common\model\Site;
use app\common\model\Visits;
use app\common\model\User;
use app\admin\model\Navlist;
use app\admin\model\Cmsmodels;
use app\admin\model\Adminlog;

use app\admin\model\Content;
use app\admin\model\Admin;
use Request;

class Index extends Base
{
	// 首页
	public function index($sitealias = '', $action = '')
	{
		if(Request::isPost()) {
			$siteid = Request::post('siteid');
			session('siteid',$siteid);
			return;
		}
		$menus['homeInfo'] = ['title'=>'首页','href'=>url('welcome')];
		$menus['logoInfo'] = ['title'=>config('sys.stitle'),'href'=>url('index'),'image'=>config('sys.slogo')];
		$menus['menuInfo'] = arr2tree_menu($this->adminmenu,0,1,3);
		// 切换站点
		if(!empty($sitealias)) {
			$site = Site::getByAlias($sitealias);
			if($site) {
				if(!$this->admininfo['isboss'] && !empty($this->admininfo['siteids'])) {
					if(!in_array($site['id'],explode(',', $this->admininfo['siteids']))) $this->error('站点错误');
				}
				session('siteid',$site['id']);
				session('sitealias',$sitealias);
			} else {
				$this->error('站点错误');
			}
		}
		if($action=='getmenu') return json($menus);
		$sys_bit = sys_bit();
		// 站点列表
		$sitelist = Site::order('id','torder')->when(!empty($this->admininfo['siteids']),function($query){
			$query->whereIn('id',$this->admininfo['siteids']);
		})->select();
		// 模型检测
		$cmsmodels = Cmsmodels::select();
		$error_models = [];
		foreach ($cmsmodels as $v) {
			if(!class_exists('app\\common\\model\\'.$v['classname'])) $error_models[] = $v;
		}
		return $this->fetch('',compact('sitelist','sys_bit','error_models'));
	}
	
	// 欢迎页
	public function welcome()
	{
		if(Request::isPost()) {
			$act = Request::post('act');
			if($act == 'line') {
				$data['data'] = null;
				for ($d = 6; $d >= 0; $d --) {
					$ds = strtotime(date('Y-m-d 00:00:00', strtotime("-".$d." day")));
					$de = strtotime(date('Y-m-d 23:59:59', strtotime("-".$d." day")));
					$data['list'][$d]['type'] = date('m-d',$ds);
					$data['list'][$d]['sum'] = Visits::whereTime('create_time',[$ds,$de])->count();
				}
				sort($data['list']);
				return $data;
			} else if($act == 'round') {
				$data['data'] = null;
				// 月份
				$z = date('Y-m');
		        $a = date('Y-m', strtotime('-5 months'));
		        $begin = new \DateTime($a);
		        $end = new \DateTime($z);
		        $end = $end->modify('+1 month');
		        $interval = new \DateInterval('P1M');
		        $daterange = new \DatePeriod($begin, $interval ,$end);
		        foreach($daterange as $k => $v){
		        	$themonth[$k] = $v->format("Ym");
		        }
				foreach ($themonth as $k => $v) {
					$data['list'][$k]['type'] = $v;
					if(strtolower(config('database.type')) == 'sqlite') {
						$sum = Db::query("SELECT COUNT(*) AS sum FROM `".config("database.prefix")."visits` WHERE strftime('%Y%m',datetime(`create_time`, 'unixepoch', 'localtime'))='".$v."'")[0]['sum'];
						
					} else {
						$sum = Db::query("SELECT COUNT(*) AS sum FROM `".config("database.prefix")."visits` WHERE FROM_UNIXTIME(`create_time`,'%Y%m')='".$v."'")[0]['sum'];
					}
					$data['list'][$k]['sum'] = $sum ? intval($sum) : 0;
				}
				return $data;
			}
		}
		// 用户统计
		$usercount = User::count();
		$newusercount = User::whereTime('create_time', 'm')->count();
		// 模型统计
		$modelcount = Cmsmodels::count();
		$modeltype1 = Cmsmodels::whereType(1)->count();
		// 访客统计
		$visitscount = Visits::whereSiteId(session('siteid'))->count();
		$todayvisitscount = Visits::whereSiteId(session('siteid'))->whereTime('create_time', 'd')->count();
		// 栏目统计
		$navcount = Navlist::whereSiteId(session('siteid'))->count();
		$modelnavcount = Navlist::whereSiteId(session('siteid'))->whereType('model')->count();
		// 操作数
		$adminlogcount = Adminlog::whereType(2)->whereAdminId(session('adminid'))->count();
		$todayadminlogcount = Adminlog::whereType(2)->whereAdminId(session('adminid'))->whereTime('create_time', 'd')->count();
		// 管理员登陆日志
		$adminlogindata = Adminlog::where(['type'=>1,'status'=>1,'admin_id'=>session('adminid')])->order('create_time asc')->select()->toArray();
		$adminlogincount = count($adminlogindata);
		$adminloginprevlast =$adminlogincount > 1 ? $adminlogindata[$adminlogincount-2] : end($adminlogindata);
		return $this->fetch('',compact('usercount','newusercount','modelcount','modeltype1','visitscount','todayvisitscount','navcount','modelnavcount','adminlogincount','adminloginprevlast','adminlogcount','todayadminlogcount'));
	}

	// 登陆
	public function login()
	{
		if(request()->isPost()) {
			$data = input('post.','','trim,htmlspecialchars');
			if(empty($data['captcha'])) {
                $this->error('请填写验证码');
            }
            if(!captcha_check($data['captcha'])) {
                $this->error("验证码错误");
            }
			//令牌验证
            if(!$this->checkToken($data)){
                $this->error(lang('requestfalse')); 
            }
			$result = Admin::adminLogin($data);
			if($result['code']==0) {
				$this->error($result['msg']);
			} else {
				$this->success($result['msg'],url('index'));
			}
		} else {
			// 防止重复登陆
			if($this->admininfo) {
				$this->redirect(url('index'));
			} else {
				return $this->fetch();
			}
		}
	}

	// 找回密码
	public function forget()
	{
		if(!config('app.email.email')) $this->error('邮件服务未开启，不能使用此功能！');
		if(request()->isPost()) {
			$data = input('post.','','trim,htmlspecialchars');
			if(empty($data['captcha'])) {
                $this->error('请填写验证码');
            }
            if(!captcha_check($data['captcha'])) {
                $this->error("验证码错误");
            }
			//令牌验证
            if(!$this->checkToken($data)){
                $this->error(lang('requestfalse')); 
            }
            if(empty($data['username']) || empty($data['email'])) $this->error('请填写必填项！');
			$result = Admin::forget($data);
			if($result['code']==0) {
				$this->error($result['msg']);
			} else {
				$this->success('密码找回成功,请查看密保邮箱',url('index'));
			}
		}
	}

	// 退出登陆
	public function loginOut()
	{
		// $this->clearCache();
		$adminid = session('adminid');
		session('adminid',NULL);
		session('siteid',NULL);
		session('sitealias',NULL);
		session('session_start_time',NULL);
		cache('forms_cache',NULL);
		cache('unviewlist_'.$adminid,NULL);
		$this->redirect('login');
	}

	// 清除缓存
	public function clearCache() // 删除缓存
	{
		try{
			delete_dir(env('runtime_path'));
		} catch (\Exception $e){
			$this->error(lang('cachefalse'));
		}
		$this->success(lang('cachetrue'));
	}

	// 清除首页
	public function clearindex()
	{
		// 如果开启静态首页
		if(request()->isPost() && config('app.home.indexhtml')){
			try{
				delete_dir(env("root_path").'public'.DS.'index',false);
			} catch (\Exception $e){
				$this->error($e->getMessage());
			}
			$this->success(lang('cleartrue'));
		}
	}

	// 轮询表单
	public function ajaxform($time='')
	{
		if(request()->isPost()){
			// 获取表单
			$forms_cache = \think\facade\Cache::remember('forms_cache',function(){
					return Model::hasWhere('formconfig','status = 1')->whereModeltype(3)->select();
				});
			$data = [];
			$map[0] = ['adminview','eq',0];
			if(config('app.user.userbindadmin') && !$this->admininfo['isboss'] && $this->admininfo['admingroup_id'] != config('app.user.userbindadmin_admingroup')) {
				$map[] = [['user_id','neq',0],['user_id','in',$this->admininfo['userids']]];
			}
			if(empty($time)) {
				foreach ($forms_cache as $k => $v) {
					$unviewcount = Content::name(tablepref($v['modeltype']).$v['tablename'])->where($map)->count();
					if($unviewcount) {
						$data[] = ['formid' => $v['id'],'formname' => $v['name'],'unviewcount'=>$unviewcount];
					}
				}
				return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data,'count'=>count($data)]);
			} else {
				foreach ($forms_cache as $k => $v) {
					$unview = Content::name(tablepref($v['modeltype']).$v['tablename'])->append(['user'])->where($map)->whereTime('create_time',$time)->select();
					if($unview) {
						foreach ($unview as $kv => $vv) {
							if($vv['user']) {
								$username = $vv['user']['nickname'];
							} else {
								$username = '匿名用户';
							}
							$data[] = ['formid' => $v['id'],'id' => $vv['id'],'formname' => $v['name'],'username'=>$username,'create_time'=>$vv['create_time']];
						}
					}
				}
				if(!cache('unviewlist_'.session('adminid'))) {
					$result = $data;
				} else {
					$result = get_diff_array_by_filter($data,cache('unviewlist_'.session('adminid')));
				}
				cache('unviewlist_'.session('adminid'),$data,20*60);
				return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$result,'count'=>count($result)]);
			}
			
		}
	}
}