<?php
defined('PP_PATH') or exit;
class blockmanage_control extends admin_control {
	// 管理碎片
	public function index(){
		// 初始模型表名
		$this->cms_content->table = 'cms_block';
		// 初始分页 一页全部输出
		$pagenum = 100;
		$where = array();
		$total = $this->cms_content->count();
		$urlstr = '';
		$maxpage = max(1, ceil($total/$pagenum));
		$page = min($maxpage, max(1, intval(R('page'))));
		$pages = pages($page, $maxpage, 'index.php?u=blockmanage-index'.$urlstr.'-page-{page}');
		$this->assign('total', $total);
		$this->assign('pages', $pages);

		// 读取内容列表
		$cms_block_arr = $this->cms_content->list_arr($where, 'id', -1, ($page-1)*$pagenum, $pagenum, $total);
		
		//存入
		$_block_list = array();
		foreach($cms_block_arr as &$t){
			$t['isjs'] 		= empty($t['isjs']) ? 0 : 1;
			$_block_list	= array_merge($_block_list, array($t['pos'] =>array('isjs'=>$t['isjs'],'content'=>$t['content'])));
		}
		$this->runtime->set('block', $_block_list);
		$this->assign('cms_block_arr', $cms_block_arr);
		$this->display();
	}

	// 增加/编辑链接
	public function set() {
        $this->cms_content->table = 'cms_block';

		$pos = htmlspecialchars(R('pos', 'P'));
		$title = htmlspecialchars(R('title', 'P'));
        $content = urldecode(R('content', 'P'));
		isset($_POST['id']) && $id = (int) R('id', 'P');
		$isjs = (int) R('isjs', 'P');

		!$pos && E(1, '碎片标识不能为空！', 'pos');
		!$title && E(1, '标题不能为空！', 'title');

		if( !preg_match("/^[a-zA-Z0-9_]+$/",$pos) ){
			E(1, '仅限英文字母、数字、下划线');
		}

		$row = array('pos' => $pos, 'isjs' => $isjs,'title' => $title,'content'=>$content);
		$js_content = t2js($content);
		$js_path = PP_PATH.'upload/js/';
		if($isjs){
			if(!is_dir($js_path) && !mkdir($js_path, 0755, true)) {
				E(1, $js_pat.'目录创建失败');
			}
		}
		if(isset($id)) {
			$row['id'] = $id ;
			$this->cms_content->update($row);
			if($isjs){
				file_put_contents($js_path.$pos.'.js',$js_content);
			}
			E(0, '保存成功！');
		}else{
			// 检测是否能用
			if( $this->cms_content->find_fetch_key(array('pos'=>$pos))) {
				E(1, '标识名已经被使用了！');
			}
            $row['dateline'] = time();
			$this->cms_content->create($row);
			if($isjs){
				file_put_contents($js_path.$pos.'.js',$js_content);
			}
			E(0, '保存成功！');
		}
	}

	// 删除
	public function del() {
		$key = R('key', 'P');

		$arr = explode('-', $key);
		$id = end($arr);

		$this->cms_content->table = 'cms_block';
		$this->cms_content->delete($id);
		E(0, '删除完成！');
	}
        
}
