<?php
/**
 * 106云盘自动发卡平台网盘系统
 * ============================================================================
 * 版权所有 2016-2028 扎兰屯市姝妍计算机服务有限公司，并保留所有权利。
 * 网站地址: http://www.106ym.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */
namespace uhome\controller;

class V extends Uhome {
	
	/**
	 * @description 属性
	 * @param $category 栏目一维数组
	 * @param $model 模型一维数组
	 * @param $debug 开启调试
	 */
	private $debug = false;
	private $category;
	private $model;
	private $tpl;
	
	/**
	 * @description 初始加载，下面四个参数至少传递一个
	 * @param $category_id 栏目id
	 * @param $category_name 栏目名称
	 * @param $model_id 模型id
	 * @param $model_name 模型名称
	 */
	protected function _initialize(){
		parent::_initialize();
		//权限限制，待定
		$category_id=I('category_id',false);
		$category_name=I('category_name',false);
		$model_id=I('model_id',false);
		$model_name=I('model_name',false);
		$this->debug=I('debug',false);
		if(!$category_id && !$category_name && !$model_id && !$model_name){
		    $this->error('请传入分类或模型信息');
		}
		//判断分类id，准备获取分类信息
		if($category_id){
		    $this->category=M('Category')->find($category_id);
			//获取顶级分类
			if(!empty($category_id)){
			    $this->category_top=get_category_top($category_id);
			}else{
				$model_name=$category_name;
			}
		}else if($category_name){
			$where=array(
				'name'=>$category_name
			);
			$this->category=M('Category')->where($where)->find();
			//获取顶级分类
			if(!empty($this->category)){
			    $this->category_top=get_category_top($this->category['id']);
			}else{
				$model_name=$category_name;
			}
		}
		//获取模型信息
		if($model_id){//有模型id，直接根据模型id获取
			$this->model=M('model')->find($model_id);
		}else if($model_name){//有模型名称，直接根据模型名称获取
			$where=array(
				'name'=>$model_name
			);
			$this->model=M('model')->where($where)->find();
		}else{//根据分类信息获取
			$this->model=M('model')->find($this->category['model_id']);
		}
		if(!$this->model){
		    $this->display('Msg_404');
			exit;
		}
		if(empty($this->model['pk'])){
		    $this->model['pk']='id';
		}
		if(empty($this->model['prefix'])){
		    $this->model['prefix']=false;
		}
		
		//模型
		if(!empty($this->category['model'])){
		    $model_str=$this->category['model'];
		}else if(!empty($this->category_top['model'])){
		    $model_str=$this->category_top['model'];
		}else if(!empty($this->model['model'])){
		    $model_str=$this->model['model'];
		}
		
		$model_str=preg_split("/[\r\n]+/s", $model_str,-1,PREG_SPLIT_NO_EMPTY);
		foreach ($model_str as $k => &$v) {
			list($k1,$v1)=explode(':', $v);
			$this->model[$k1]=$v1;
		}
		//模板
		if(!empty($this->category['template'])){
		    $tpl_str=$this->category['template'];
		}else if(!empty($this->category_top['template'])){
		    $tpl_str=$this->category_top['template'];
		}else if(!empty($this->model['template'])){
		    $tpl_str=$this->model['template'];
		}
		$tpl_str=preg_split("/[\r\n]+/s", $tpl_str,-1,PREG_SPLIT_NO_EMPTY);
		$this->tpl=array();
		foreach ($tpl_str as $k => &$v) {
			list($k1,$v1)=explode(':', $v);
			$this->tpl[$k1]=$v1;
		}
		//限制登录
		$action=array('add','mod','del');
		if(in_array(ACTION_NAME, $action) && !is_login() && $this->model['model_allow']==1){
		    $this->error("请先登录",I('gourl',$_SERVER["HTTP_REFERER"]));
		}
    }
	
	
	/**
	 * @description 频道
	 */
	public function index(){
		//模板
		if(!empty($this->tpl['index'])){
		    $tpl=$this->tpl['index'];
		}else{
			$tpl=ucfirst(str_replace('Pub/', '', $this->model['name'])).'_index';
		}
		$this->display($tpl);
    }
	

	/**
	 * @description 列表
	 */
	public function lists(){
		$where=array();
		if(!empty($this->category)){
		    //分类id串
			$category_ids=(string) get_category_ids($this->category['id']);
			$where['category_id']=array('in',$category_ids);
		}
		$max=I('max','');
		if(!empty($max)){
			$where['id']=array('gt',$max);
		}
		
		//模型定义
		if(!empty($this->model['lists'])){
			$m=D($this->model['lists']); 
		}else{
			$m=M(ucfirst($this->model['name']));
		}
		//字段定义
		if(!empty($this->category['field_lists'])){
			$field_lists=$this->category['field_lists']; 
		}else if(!empty($this->category_top['field_lists'])){
			$field_lists=$this->category_top['field_lists']; 
		}else if(!empty($this->model['field_lists'])){
			$field_lists=$this->model['field_lists']; 
		}
		if(preg_match("/table:/i",trim($field_lists) , $matches)){
			$field_lists_arr=preg_split("/\s*table:\s*/s", trim($field_lists),-1,PREG_SPLIT_NO_EMPTY);
			if(is_array($field_lists_arr)){
			    $viewFields=array();
				foreach ($field_lists_arr as $k => &$v) {
					$field_lists_arr[$k]=preg_split("/[\r\n]+/s", trim($v),-1,PREG_SPLIT_NO_EMPTY);
					$arr=array();
					foreach ($field_lists_arr[$k] as $k1 => &$v1) {
						if($k1!=0){
							preg_match('/[\s]*_([\w]+):(.*)[\s\n\r]*/i', $v1, $field);
							if(!empty($field)){
							    $arr['_'.$field[1]]=$field[2];
							}
							preg_match('/[\s,]*field:([\w_]+)[\s\n\r,]*/i', $v1, $field);
							if(!empty($field)){
							    $arr[]=$field[1];
							}
							$viewFields[$field_lists_arr[$k][0]]=$arr;
						}
					}
				}
				$m->viewFields=$viewFields;
			}
		}else{
			$field_lists_arr=preg_split("/[\r\n]+/s", trim($field_lists),-1,PREG_SPLIT_NO_EMPTY);
			foreach ($field_lists_arr as $k => &$v) {
				preg_match('/[\s,]*field:([\w_]+)[\s\n\r,]*/i', $v, $field);
				$v=$field[1];
			}
			$field=$field_lists_arr;
		}
		
		//管理列表显示处理
		$grid_arr=preg_split("/[\r\n]+/s", trim($field_lists),-1,PREG_SPLIT_NO_EMPTY);
		$grid=array();
		$field_search=array();
		foreach ($grid_arr as $k => &$v) {
			//排除视图模型 _as _on
			if(strpos($v, 'field')===false){
			   continue;
			}
			//排除列表隐藏字段
			preg_match("/field:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['field']=$matches[1];
			preg_match("/[\s,]+title:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['title']=$matches[1];
			preg_match("/[\s,]+hidden:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['hidden']=(boolean)$matches[1];
			preg_match("/[\s,]+hidden_admin:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['hidden_admin']=(boolean)$matches[1];
			preg_match("/[\s,]+hidden_member:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['hidden_member']=(boolean)$matches[1];
			preg_match("/[\s,]+width:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['width']=$matches[1];
			preg_match("/[\s,]+class:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['class']=$matches[1];
			preg_match("/[\s,]+fun:([^,\r\n]+)[\(]+/i", $v, $matches);
			$grid[$k]['fun']=$matches[1];
			preg_match("/[\s,]+fun:[\w_]+\(([^\(\)]+)\)/i", $v, $matches);
			$grid[$k]['fun_param']=preg_split("/[,]+/s", $matches[1],-1,PREG_SPLIT_NO_EMPTY);
			preg_match("/[\s,]+href:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['href']=(boolean)$matches[1];
			preg_match("/[\s,]+search_exp:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['search_exp']=$matches[1];
			preg_match("/[\s,]+search_title:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['search_title']=$matches[1];
			preg_match("/[\s,]+search_hidden_admin:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['search_hidden_admin']=(boolean)$matches[1];
			preg_match("/[\s,]+search_hidden_member:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches);
			$grid[$k]['search_hidden_member']=(boolean)$matches[1];
			
			if(!empty($grid[$k]['search_exp']) && $grid[$k]['hidden']!==true){
				array_push($field_search,array('field'=>$grid[$k]['field'],'search_exp'=>$grid[$k]['search_exp'],'search_title'=>$grid[$k]['search_title'],'search_hidden_admin'=>$grid[$k]['search_hidden_admin'],'search_hidden_member'=>$grid[$k]['search_hidden_member']));
			}
		}
		$this->assign('field_search',$field_search);
		$this->assign('grid',$grid);
		
		//条件搜索
		foreach($grid as $k=>&$v){
			if($v['search_exp']=='like' && !empty($_REQUEST[$v['field']])){
			    $where[$v['field']]=array('like','%'.$_REQUEST[$v['field']].'%');
			}else if($v['search_exp']=='eq' && isset($_REQUEST[$v['field']]) && !empty($_REQUEST[$v['field']])){
				$where[$v['field']]=array('eq',$_REQUEST[$v['field']]);
			}else if($v['search_exp']=='eq_input' && isset($_REQUEST[$v['field']])){
				$where[$v['field']]=array('eq',$_REQUEST[$v['field']]);
			}else if($v['search_exp']=='find_in_set' && !empty($_REQUEST[$v['field']])){
				$where[$v['field']]=array('find_in_set',$_REQUEST[$v['field']]);
			}else if($v['search_exp']=='position' && $_REQUEST[$v['field']]>0){
				$where[$v['field']]=array('position',$_REQUEST[$v['field']]);
			}else if($v['search_exp']=='between'){
				$min=floatval($_REQUEST[$v['field'].'_min']);
				$max=floatval($_REQUEST[$v['field'].'_max']);
				if(!empty($_REQUEST[$v['field'].'_min']) && !empty($_REQUEST[$v['field'].'_max'])){
				    $where[$v['field']]=array('between',array($min,$max));
				}else if(!empty($_REQUEST[$v['field'].'_min'])){
					$where[$v['field']]=array('egt',$min);
				}else if(!empty($_REQUEST[$v['field'].'_max'])){
					$where[$v['field']]=array('elt',$max);
				}
			}
		}
		if(I('post._string') && $where['_string']){
		    $where['_string']=" and ".base64_decode(I('post._string'));
		}else if(I('post._string')){
		    $where['_string']=base64_decode(I('post._string'));
		}
		
		//排序
		if(!empty($this->category['model_order'])){//判断分类是否有排序，如果有则用分类排序
			$order=$this->category['model_order'];
		}else if(!empty($this->category_top['model_order'])){//判断分类是否有排序，如果有则用分类排序
			$order=$this->category_top['model_order'];
		}else if(!empty($this->model['model_order'])){//判断模型是否有排序，如果有则用模型排序
			$order=$this->model['model_order'];
		}else{
			$order=$this->model['pk']." desc";//否则按id倒序排列
		}
		//分页条数
		if(I('row')>0){
		    $row=I('row');
		}else if(!empty($this->category['list_row'])){
		    $row=$this->category['list_row'];
		}else if(!empty($this->category_top['list_row'])){
			$row=$this->category_top['list_row'];
		}else if(!empty($this->model['list_row'])){
			$row=$this->model['list_row'];
		}
		
		$count=$m->where($where)->count();
		$page       = new \source\Page($count,$row); //3.2
		$nowPage = I("p",1);
		$this->page  = $page->show();
		if($m->viewFields){
			$list=$m->order($order)->where($where)->page($nowPage.','.$page->listRows)->select();
		}else{
			$list=$m->order($order)->field($field)->where($where)->page($nowPage.','.$page->listRows)->select();
		}
		$this->list=$list;
		if($this->debug){
		    echo ($m->getlastsql());
			dump($this->list);
		}
		if(IS_AJAX || I('ajax')==1){
			foreach ($list as $k => &$v) {
				if(!empty($v['imgs'])){
				    $imgs_arr=preg_split("/[,]+/s", $v['imgs'],-1,PREG_SPLIT_NO_EMPTY);
				}
				if(!empty($imgs_arr) && !empty($v['imgs'])){
					$v['imgs']=M('Picture')->where(array('id'=>array('in',$imgs_arr)))->select();
					foreach ($v['imgs'] as $k1 => &$v1) {
						$v1['path']=$v1['path'];
					}
				}
			}
			$totalPage=ceil($count/$row);
			$page_a=array();
			for ($i=1;$i<=$totalPage;$i++) {
				array_push($page_a,$i);
			}
			if($m->viewFields){
				$redata=array(
			    	'sql'=>$m->getlastsql(),
					'totalPage'=>$totalPage,
					'data'=>$list,
					'max'=>$m->where($where)->max('a.'.$this->model['pk']),
					'page'=>array(
						'p'=>$nowPage,
						'totalPage'=>$totalPage,
						'totalRs'=>$count,
						'a'=>$page_a,
					),
					'cache_list_name'=>md5($m->getlastsql()),
				);
			}else{
				$redata=array(
			    	'sql'=>$m->getlastsql(),
					'totalPage'=>$totalPage,
					'data'=>$list,
					'max'=>$m->where($where)->max($this->model['pk']),
					'page'=>array(
						'p'=>$nowPage,
						'totalPage'=>$totalPage,
						'totalRs'=>$count,
						'a'=>$page_a,
					),
					'cache_list_name'=>md5($m->getlastsql()),
				);
			}
		    
			$this->ajaxReturn($redata);
		}
		
		//模板
		if(!empty($this->tpl['lists'])){
		    $tpl=$this->tpl['lists'];
		}else{
			$tpl=ucfirst(str_replace('Pub/', '', $this->model['name'])).'_lists';
		}
		$this->assign('category',$this->category);
		$this->assign('model',$this->model);
		$this->display($tpl);
    }


	/**
	 * @description 管理列表
	 */
	public function my(){
		$where=array();
		if(!empty($this->category)){
		    //分类id串
			$category_ids=(string) get_category_ids($this->category['id']);
			$where['category_id']=array('in',$category_ids);
		}
		//模型定义
		if(!empty($this->model['my'])){
			$m=D($this->model['my']); 
		}else{
			$m=D('pub/'.ucfirst($this->model['name']));
		}
		//字段定义
		if(!empty($this->category['field_lists'])){
			$field_lists=$this->category['field_lists']; 
		}else if(!empty($this->category_top['field_lists'])){
			$field_lists=$this->category_top['field_lists']; 
		}else if(!empty($this->model['field_lists'])){
			$field_lists=$this->model['field_lists']; 
		}
		//视图字段定义
		if(preg_match("/table:/i",trim($field_lists) , $matches)){
			$field_lists=preg_split("/\s*table:\s*/s", trim($field_lists),-1,PREG_SPLIT_NO_EMPTY);
			if(is_array($field_lists)){
			    $viewFields=array();
				foreach ($field_lists as $k => &$v) {
					$field_lists[$k]=preg_split("/[\r\n]+/s", trim($v),-1,PREG_SPLIT_NO_EMPTY);
					$arr=array();
					foreach ($field_lists[$k] as $k1 => &$v1) {
						$field_lists[$k][$k1]=preg_split("/[:]+/s", trim($v1),-1,PREG_SPLIT_NO_EMPTY);
						if($k1!=0){
							if($field_lists[$k][$k1][1]!==null){
							    $arr[$field_lists[$k][$k1][0]]=$field_lists[$k][$k1][1];
							}else{
								$arr[]=$field_lists[$k][$k1][0];
							}
						}
						$viewFields[$field_lists[$k][0][0]]=$arr;
					}
				}
				$m->viewFields=$viewFields;
			}
		}
		
		//解析列表规则
        $fields = array();
		if(!empty($this->category['list_grid'])){
		    $this->model['list_grid']=$this->category['list_grid'];
		}
		$grids  = preg_split('/[;\r\n]+/s', trim($this->model['list_grid']),-1,PREG_SPLIT_NO_EMPTY);
        foreach ($grids as &$value) {
        	if(trim($value) === ''){
        		continue;
        	}
            // 字段:标题:链接:宽度
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1],'width'=>$val[3],'align'=>$val[4]);
            if(isset($val[2])){
                // 链接信息
                $value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array	=	explode('|',$val);
                $fields[] = $array[0];
            }
			
        }
		
		// 条件搜索
		if(!empty($this->category['list_grid_search_home'])){
		    $list_grid_search=$this->category['list_grid_search_home'];
		}else if(!empty($this->category_top['list_grid_search_home'])){
			$list_grid_search=$this->category_top['list_grid_search_home'];
		}else if(!empty($this->model['list_grid_search_home'])){
			$list_grid_search=$this->model['list_grid_search_home'];
		}else if(!empty($this->category['list_grid_search'])){
			$list_grid_search=$this->category['list_grid_search'];
		}else if(!empty($this->category_top['list_grid_search'])){
			$list_grid_search=$this->category_top['list_grid_search'];
		}else if(!empty($this->model['list_grid_search'])){
			$list_grid_search=$this->model['list_grid_search'];
		}
		$list_grid_search=preg_split("/[\r\n]+/s", $list_grid_search,-1,PREG_SPLIT_NO_EMPTY);
		foreach($list_grid_search as $k=>&$v){
			$v=preg_split("/[\|]+/s", $v,-1,PREG_SPLIT_NO_EMPTY);
			if($v[1]=='position' && $_REQUEST[$v[0]]>0){
				$where['_string']='position & '.$_REQUEST['position'];
			}else if($v[1]=='like' && !empty($_REQUEST[$v[0]])){
				$where[$v[0]]=array('like','%'.$_REQUEST[$v[0]].'%');
			}else if($v[1]=='find_in_set' && !empty($_REQUEST[$v[0]])){
				$where[$v[0]]=array('find_in_set',$_REQUEST[$v[0]]);
			}else if($v[1]=='eq' && !empty($_REQUEST[$v[0]])){
				$where[$v[0]]=array('eq',$_REQUEST[$v[0]]);
			}else if($v[1]=='between' && isset($_REQUEST[$v[0].'_min']) && isset($_REQUEST[$v[0].'_max'])){
				$min=floatval($_REQUEST[$v[0].'_min']);
				$max=floatval($_REQUEST[$v[0].'_max']);
				if(!empty($_REQUEST[$v[0].'_min']) && !empty($_REQUEST[$v[0].'_max'])){
				    $where[$v[0]]=array('between',array($min,$max));
				}else if(!empty($min)){
					$where[$v[0]]=array('egt',$min);
				}else if(!empty($max)){
					$where[$v[0]]=array('elt',$max);
				}
			}
		}
		//排序
		if(!empty($this->category['model_order'])){//判断分类是否有排序，如果有则用分类排序
			$order=$this->category['model_order'];
		}else if(!empty($this->category_top['model_order'])){//判断分类是否有排序，如果有则用分类排序
			$order=$this->category_top['model_order'];
		}else if(!empty($this->model['model_order'])){//判断模型是否有排序，如果有则用模型排序
			$order=$this->model['model_order'];
		}else{
			$order="id desc";//否则按id倒序排列
		}
		//分页条数
		if(I('row')>0){
		    $row=I('row');
		}else if(!empty($this->category['list_row'])){
		    $row=$this->category['list_row'];
		}else if(!empty($this->category_top['list_row'])){
			$row=$this->category_top['list_row'];
		}else if(!empty($this->model['list_row'])){
			$row=$this->model['list_row'];
		}
		$count=$m->where($where)->count();
		$page       = new \source\Page($count,$row); //3.2
		$nowPage = I("p",1);
		$this->page  = $page->show();
		$this->list=$m->order($order)->where($where)->page($nowPage.','.$page->listRows)->select();
		if($this->debug){
		    dump($m->getlastsql());
			dump($this->list);
		}
		
		$this->assign('category',$this->category);
		$this->assign('model',$this->model);
		$this->assign('list_grids', $grids);
		//模板
		if(!empty($this->category['template_my'])){
		    $tpl=$this->category['template_my'];
		}else if(!empty($this->category_top['template_my'])){
		    $tpl=$this->category_top['template_my'];
		}else{
			$tpl='V_my';
		}
		$this->display($tpl);
    }
	
	
	/**
	 * @description 详情
	 */
	public function show(){
		$id=I('id',0);
		//模型定义
		if(!empty($this->model['show'])){
			$m=D($this->model['show']); 
		}else{
			$m=D('pub/'.ucfirst($this->model['name']));
		}
		$where=array(
			'id'=>$id
		);
		$info = $m->where($where)->find();
		$this->info=$info;
		if($this->debug){
		    dump($m->getlastsql());
			dump($this->info);
		}
		if(empty($this->info)){
		    $this->error('文章不存在，或已被删除');
		}
		if(IS_AJAX){
			$info['img']=C('WEB_SITE_STATIC_DOAMIN').$info['img'];
			$info['content']=wd_content_img_qiniu($info['content'],'?imageView2/2/w/600/q/80/interlace/1');
			if(!empty($info['imgs'])){
			    $imgs_arr=preg_split("/[,]+/s", $info['imgs'],-1,PREG_SPLIT_NO_EMPTY);
			}
			if(!empty($imgs_arr) && !empty($info['imgs'])){
			    $where=array();
				$where['id']=array('in',$imgs_arr);
				$info['imgs']=M('Picture')->where($where)->select();
				foreach ($info['imgs'] as $k1 => &$v1) {
					$v1['path']=C('WEB_SITE_STATIC_DOAMIN').$v1['path'];
				}
			}
		    $this->ajaxReturn($info);
		}
		
		//模板
		if(!empty($this->tpl['show'])){
		    $tpl=$this->tpl['show'];
		}else{
			$tpl=ucfirst(str_replace('Pub/', '', $this->model['name'])).'_show';
		}
		$this->assign('category',$this->category);
		$this->assign('model',$this->model);
		$this->display($tpl);
	}
	
	/**
	 * @description 前台投稿
	 */
	public function add(){
		if($this->model['model_allow']==0){
		    $this->error('禁止发布');
		}
		
		if(IS_POST){
			//模型定义
			if(!empty($this->model['add'])){
				$m=D($this->model['add']); 
			}else{
				$m=D('pub/'.ucfirst($this->model['name']));
			}
			if(method_exists($m, 'wdadd')){
			    $m->wdadd();
				if($this->debug){
				    dump($m->getlastsql());
					dump($data);
				}
				if($m->getError()){
				    $this->error($m->getError());
				}
				$this->success('添加成功',I('gourl',$_SERVER["HTTP_REFERER"]));
			}
			if($data=$m->create() && $m->add()){
				if($this->debug){
				    dump($m->getlastsql());
					dump($data);
					dump(I('post.'));
					die;
				}
				$this->success('添加成功',cookie('v_lists'));
			}else{
				$this->error($m->getError());
			}
		}else{
			//表单分组
			$field_group_arr=preg_split("/[,]+/s", $this->model['field_group'],-1,PREG_SPLIT_NO_EMPTY);
			$field_group=array();
			foreach ($field_group_arr as $k => &$v) {
				list($k1,$v1)=preg_split("/[:]+/s", $v,-1,PREG_SPLIT_NO_EMPTY);
				$field_group[$k1]=$v1;
			}
			$this->assign('field_group',$field_group);
			//表单定义
			if(!empty($this->category['field_form'])){
			    $field_form_str=$this->category['field_form'];
			}else if(!empty($this->category_top['field_form'])){
				$field_form_str=$this->category_top['field_form'];
			}else if(!empty($this->model['field_form'])){
				$field_form_str=$this->model['field_form'];
			}
			$field_form_arr=preg_split("/[\r\n]+/s", $field_form_str,-1,PREG_SPLIT_NO_EMPTY);
			$field_form=array();
			foreach ($field_form_arr as $k => &$v) {
				if(preg_match("/[\s,]+hidden_admin:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches)){
				    continue;
				}
				preg_match("/field:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches1);
				preg_match("/[\s,]+title:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches2);
				array_push($field_form,array('field'=>$matches1[1],'title'=>$matches2[1]));
			}
			$fields = get_model_attribute($this->model['id']);
			$fields_new=array();
			foreach ($field_form as $k => $v) {
				foreach ($fields as $k1 => $v1) {
					foreach ($v1 as $k2 => $v2) {
						if($v2['name']==$v['field']){
						    $fields_new[$k1][$k2]=$fields[$k1][$k2];
							if(!empty($v['title'])){
							    $fields_new[$k1][$k2]['title']=$v['title'];
							}
						}
						
					}
				}
			}
			if(!empty($fields_new)){
			    $fields=$fields_new;
			}
	        $this->assign('fields', $fields);
			
			
			
			//模板
			if(!empty($this->tpl['add'])){
			    $tpl=$this->tpl['add'];
			}else{
				$tpl=$this->model['name'].'_add';
			}
			$this->assign('category',$this->category);
			$this->assign('model',$this->model);
			$this->display($tpl);
		}
	}
	
	/**
	 * @description 前台编辑
	 */
	public function mod($id){
		if($this->model['model_allow']==0){
		    $this->error('禁止编辑');
		}
		//模型定义
		if(!empty($this->model['mod'])){
			$m=D($this->model['mod']); 
		}else{
			$m=D('pub/'.ucfirst($this->model['name']));
		}
		if(IS_POST){
			if(method_exists($m, 'wdmod')){
			   	$m->wdmod();
				if($this->debug){
				    dump($m->getlastsql());
					dump($data);
				}
				if($m->getError()){
				    $this->error($m->getError());
				}
				$this->success('修改成功',I('gourl',$_SERVER["HTTP_REFERER"]));
			}
			if($data=$m->create() && $m->save()){
				if($this->debug){
				    dump($m->getlastsql());
					dump($data);
				}
				$this->success('修改成功',cookie('v_lists'));
			}else{
				$this->error($m->getError());
			}
		}else{
			//表单分组
			$field_group_arr=preg_split("/[,]+/s", $this->model['field_group'],-1,PREG_SPLIT_NO_EMPTY);
			$field_group=array();
			foreach ($field_group_arr as $k => &$v) {
				list($k1,$v1)=preg_split("/[:]+/s", $v,-1,PREG_SPLIT_NO_EMPTY);
				$field_group[$k1]=$v1;
			}
			$this->assign('field_group',$field_group);
			//表单定义
			if(!empty($this->category['field_form'])){
			    $field_form_str=$this->category['field_form'];
			}else if(!empty($this->category_top['field_form'])){
				$field_form_str=$this->category_top['field_form'];
			}else if(!empty($this->model['field_form'])){
				$field_form_str=$this->model['field_form'];
			}
			$field_form_arr=preg_split("/[\r\n]+/s", $field_form_str,-1,PREG_SPLIT_NO_EMPTY);
			$field_form=array();
			foreach ($field_form_arr as $k => &$v) {
				if(preg_match("/[\s,]+hidden_admin:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches)){
				    continue;
				}
				preg_match("/field:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches1);
				preg_match("/[\s,]+title:([^,\r\n]+)[\s\n\r,]*/i", $v, $matches2);
				array_push($field_form,array('field'=>$matches1[1],'title'=>$matches2[1]));
			}
			$fields = get_model_attribute($this->model['id']);
			$fields_new=array();
			foreach ($field_form as $k => $v) {
				foreach ($fields as $k1 => $v1) {
					foreach ($v1 as $k2 => $v2) {
						if($v2['name']==$v['field']){
						    $fields_new[$k1][$k2]=$fields[$k1][$k2];
							if(!empty($v['title'])){
							    $fields_new[$k1][$k2]['title']=$v['title'];
							}
						}
						
					}
				}
			}
			if(!empty($fields_new)){
			    $fields=$fields_new;
			}
	        $this->assign('fields', $fields);
			$this->modval = $m->find($id);
			if(empty($this->modval)){
			    $this->error('你要修改的信息不存在');
			}
			//模板
			if(!empty($this->tpl['mod'])){
			    $tpl=$this->tpl['mod'];
			}else{
				$tpl=$this->model['name'].'_mod';
			}
			
			$this->assign('category',$this->category);
			$this->assign('model',$this->model);
			$this->display($tpl);
		}
	}
	
	/**
	 * @description 前台删除
	 */
	public function del($id){
		if($this->model['model_allow']==0){
		    $this->error('禁止删除');
		}
		
		//模型定义
		if(!empty($this->model['del'])){
			$m=D($this->model['del']); 
		}else{
			$m=D('pub/'.ucfirst($this->model['name']));
		}
		//数据准备
		if(!is_array($id)){
		    $id=preg_split("/[,]+/s", $id,-1,PREG_SPLIT_NO_EMPTY);
		}
		$where[$this->model['pk']]=array('in',$id);
		$m->where($where)->delete();
		$this->success('删除成功',cookie('v_lists'));
	}
	
	
	protected function checkAttr($Model,$model_id){
        $fields     =   get_model_attribute($model_id,false);
        $validate   =   $auto   =   array();
        foreach($fields as $key=>$attr){
            if($attr['is_must']){// 必填字段
                $validate[]  =  array($attr['name'],'require',$attr['title'].'必须!');
            }
            // 自动验证规则
            if(!empty($attr['validate_rule'])) {
                $validate[]  =  array($attr['name'],$attr['validate_rule'],$attr['error_info']?$attr['error_info']:$attr['title'].'验证错误',0,$attr['validate_type'],$attr['validate_time']);
            }
            // 自动完成规则
            if(!empty($attr['auto_rule'])) {
                $auto[]  =  array($attr['name'],$attr['auto_rule'],$attr['auto_time'],$attr['auto_type']);
            }elseif('checkbox'==$attr['type']){ // 多选型
                $auto[] =   array($attr['name'],'arr2str',3,'function');
            }
        }
        return $Model->validate($validate)->auto($auto);
    }
}

