<?php
/**
 *
 * 文章模块操作
 *
 * @package             Ivears
 * @author              Terry QQ:466209365 <admin@ivears.com>
 * @copyright           Copyright (c) 20012-2013  (http://www.ivears.com)
 * @license             http://www.ivears.com/license.txt
 * @version             Ivears企业网站管理系统 v1.0 2013-04-14 ivears.com $
 */
class ArticleAction extends AdminAction {

    public function _initialize() {
        parent::_initialize();
    }

    /**
     * 文章列表
     * @author billow.wang<admin@ivears.com>
     * @date 2013-07-02
     */
    public function index() {
		

		$cid = $this->_request('cid');
		$school_id = $this->_request('school_id');
        $action = D($this->_name);
        $ary_get['pageall'] = $this->_get('pageall', 'htmlspecialchars', 8);
		if($cid){
			
			$wherearr=array();
			$childcid_arr=D('category')->where(array('pid'=>$cid))->select();
			if($childcid_arr){
					foreach($childcid_arr  as $key=>$one){
						$wherearr[]=$one['id'];	
					}
				$wherearr[]=$cid;
				$wherestr=implode(',',$wherearr);
				$where="cid in($wherestr)";
			}else{
				$where['cid']=$cid;
			}			
			$catarr=D('category')->where(array('id'=>$cid))->find();
			if($catarr['pid']){
				$catarr_parr=D('category')->where(array('id'=>$catarr['pid']))->find();
				$this->assign("catarr_parr",$catarr_parr);
			}						
		}else{
			$cid=0;	
		}
		if($school_id){
			if($where){
				if(is_array($where)){
					$where['school_id']=$school_id;	
				}else{
					$where.=" and school_id=$school_id";	
				}
			}else{
				$where="school_id=$school_id";	
			}
		}else{
			$school_id=0;	
		}		
		$this->assign('cid',$cid);
		$this->assign('school_id',$school_id);
        $count = $action->where($where)->count();
        $obj_page = $this->_Page($count, $ary_get['pageall']);
        $page = $obj_page->newshow();
        
        $ary_data = $action
                        ->field(C("DB_PREFIX")."category.title as cat_title,".C("DB_PREFIX")."article.*,".C("DB_PREFIX")."admin.u_name as author_name")
                        ->join(C("DB_PREFIX")."category ON ".C("DB_PREFIX")."category.id=".C("DB_PREFIX")."article.cid")
                        ->join(C("DB_PREFIX")."admin ON ".C("DB_PREFIX")."admin.u_id=".C("DB_PREFIX")."article.uid")
                        ->where($where)->limit($obj_page->firstRow, $obj_page->listRows)->order(C("DB_PREFIX").'article.`id` DESC')->select();
						
		$category = $this->getSelect($cid);
		$this->assign('category',$category);						
        $this->assign("data", $ary_data);
        $this->assign("page", $page);
        $this->display();
    }

    /**
     * 添加文章
     * @author billow.wang<admin@ivears.com>
     * @date 2013-12-10
     */
    public function addArticle() {
        $category = $this->getSelect();
        $this->assign("category",$category);
        $this->display('addArticle');
    }

    /**
     * 保存文章
     * @author billow.wang<admin@ivears.com>
     * @date 2013-12-10
     */
    public function doAdd(){
        $ary_post = $this->_post();
        
        if(!empty($ary_post) && is_array($ary_post)){
            $module = D($this->_name);
            $ary_post['create_time'] = date("Y-m-d H:i:s");
            $ary_post['uid'] = $_SESSION[C('USER_AUTH_KEY')];
            $ary_result = $module->add($ary_post);
            if(FALSE !== $ary_result){
                $this->success("新增成功",'/Admin/'.MODULE_NAME.'/');
            }else{
                $this->error("新增失败");
            }
        }else{
            $this->error("数据有误，请重试……");
        }
    }
    
    /**
     * 更新文章状态
     * @author billow.wang<admin@ivears.com>
     * @date 2013-12-10
     */
    public function edit(){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $ids = trim($this->_request($pk), ',');
        if ($ids) {
            $ary_data = $mod -> where(array($pk=>$ids))->find();
            $category = $this->getSelect($ary_data['cid']);
            $this->assign('data',$ary_data);
            $this->assign("category",$category);
            $this->display();
        }else{
            $this->error("请选择需要编辑的对象");
        }
    }
    
    public function doEdit(){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $field = $mod->getDbFields();
        $ary_request = $this->_request();
        $id = $ary_request[$pk];
        unset($ary_request[$pk]);
        if($id){

                $ary_request['update_time'] = date("Y-m-d H:i:s");
                $ary_request['uid'] = $_SESSION[C('USER_AUTH_KEY')];
                $ary_res = $mod ->where(array($pk=>$id))->data($ary_request)->save();
                if(FALSE !== $ary_res){
                    $this->success("编辑成功");
                }else{
                    $this->error("编辑失败");
                }

        }else{
            $this->error("请选择需要编辑的对象");
        }
        
    }
    
    /**
     * 更改文章状态
     * @author billow.wang<admin@ivears.com>
     * @date 2013-12-10
     */
    public function doEditStatus(){
        $ary_post = $this->_post();
        if(!empty($ary_post['id']) && isset($ary_post['id'])){
            $mod = D($this->_name);
            $data = array();
            $data[$ary_post['field']] = $ary_post['val'];
            $ary_result = $mod->where(array('id'=>$ary_post['id']))->data($data)->save();
            if(FALSE !== $ary_result){
                if(!empty($ary_post['val']) && $ary_post['val'] == '1'){
                    $this->success("启用成功");
                }else{
                    $this->success("禁用成功");
                }
            }  else {
                if(!empty($ary_post['val']) && $ary_post['val'] == '1'){
                    $this->success("启用失败");
                }else{
                    $this->success("禁用失败");
                }
            }
        }else{
            $this->error("该信息不存在");
        }
    }

    /**
     * 删除操作
     * @author billow.wang<admin@ivears.com>
     * @date 2013-12-10
     */
    public function doDelete(){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $ids = $this->_request('ids');
        if ($ids) {
			if(is_array($ids)){
				$idstr=implode(',',$ids);
			}else{
				$idstr=$ids;	
			}			
            if (false !== $mod->delete($idstr)) {
                $this->success("删除成功",'/Admin/'.$this->_name."/");
            } else {
                $this->error("删除失败",'/Admin/'.$this->_name."/");
            }
        } else {
            $this->error("请选择删除的对象",'/Admin/'.$this->_name."/");
        }
    }
    
    private function getSelect($selectedid =0, $selectname = 'cid'){
        $sReturn = '<select name="' . $selectname . '" validate="{ selected:true}"><option value="0">-- 请选择 --</option>';
        $ary_category = D("Category")->where(array('model'=>$this->_name))->order('`order` desc')->select();
        $sReturn .= $this->getOptions($ary_category, $selectedid);
        $sReturn .= '</select>';
        return $sReturn;
    }

    private function getOptions($category, $selectedid = 0, $pid = 0, $sublevelmarker = ''){
        if($pid) $sublevelmarker .= '└─ ';
        foreach($category as $value){
            if($pid == $value['pid']){
                $strHtml .= '<option ';
                if(!$pid){
                    $strHtml .= 'style="font-weight:bold;"';
                }
                $strHtml .= 'value="' . $value['id'] . '"';
                if($selectedid == $value['id']){
                    $strHtml .= 'selected';
                }else{
                    $strHtml .= '';
                }
                $strHtml .= '>' . $sublevelmarker . $value['title'] .'</option>';
                $strHtml .= $this->getOptions($category, $selectedid, $value['id'], $sublevelmarker);
            }
        }

        return $strHtml;
    }
	
	
	public function CategoryIndex(){
    	$category = D("Category");
        $ary_get['pageall'] = $this->_get('pageall', 'htmlspecialchars', 10);
        $count = $category->where(array('model'=>$this->_name))->count();
        $obj_page = $this->_Page($count, $ary_get['pageall']);
        $page = $obj_page->newshow();
        $tree = new Tree();
        $tree->icon = array('│ ','├─ ','└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $where = array('model'=>$this->_name);
        $ary_data = $category->where($where)->limit($obj_page->firstRow, $obj_page->listRows)->order('`order` DESC')->select();
        $array = array();
        if(!empty($ary_data) && is_array($ary_data)){
            foreach($ary_data as $vl){
                $vl['str_status'] = '<img class="pointer" data-id="'.$vl['id'].'" style="cursor: pointer;" data-field="status" data-value="'.$vl['status'].'" src="__PUBLIC__/Admin/images/icons/icon_'. ($vl['status'] == 1 ? '1' : '0').'.png" alt="'. ($vl['status'] == 1 ? '启用' : '停用').'" title="'. ($vl['status'] == 1 ? '启用' : '停用').'" />';
                $vl['parentid_node'] = ($vl['pid'])? ' class="child-of-node-'.$vl['pid'].'"' : '';
                $array[] = $vl;
            }
            $str = "<tr id='list_\$id' \$parentid_node>
                        <td class='align-center'>
                            <input type='checkbox' value='\$id' name='ids[]' class='checkSon' data-xid='checkSon_x'/>
                        </td>
                        <td align='left'>\$spacer\$title</td>
                        <td class='align-center'>\$id</td>
                        <td class='align-center'>\$order</td>
                        <td class='align-center'>\$str_status</td>
                        <td class='align-center'>\$create_time</td>
                        <td class='align-center'>\$update_time</td>
                        <td class='align-center'>
                            <div class='button-group'>
                                <a href='javascript:void(0);' data-height='200' data-width='500'  data-url='/Admin/$this->_name/CategoryEdit?id=\$id'  class='dialog' alt='编辑' title='编辑'>编缉</a>
                       <a href='/Admin/$this->_name/CategoryDelete?ids=\$id' class='doDel'  title='删除'>删除</a>
                            </div>
                        </td>
                    </tr>";
            $tree->init($array);
            $list = $tree->get_tree(0, $str);
			$this->assign('list', $list);
            $this->assign('Category_index', $list);
			 
        }
       
        $this->assign("data", $ary_data);
        $this->assign("page", $page);
        $this->assign("filter",$ary_get);
        $this->display('Category_index');			
	}
	public function CategoryAdd(){
			$category = $this->CateGetSelect();
			$this->assign("category",$category);		
			$this->display('Category_add');	
	}
	public function CategoryEdit(){
			$mod = D('Category');
			$pk = $mod->getPk();
			$ids = trim($this->_request($pk), ',');
			if ($ids) {
				$ary_data = $mod -> where(array($pk=>$ids))->find();
				$category = $this->CateGetSelect($ids,$ary_data['pid']);
				$this->assign('data',$ary_data);
				$this->assign("category",$category);		
				$this->display('Category_add');	
			}else{
				$this->error("请选择需要编辑的对象");
			}		
	}	
	
	
	public function CategorySave(){
			$mod = D('Category');
			$ary_post = $this->_post();
			$ary_request = $this->_request();
			$pk = $mod->getPk();
			
			if($ary_post['id']){
				$id = $ary_request[$pk];
				$mod = D('Category');
				$where = array('id'=>$ary_post['id']);
				$ary_data = $mod ->where($where)->find();
				if($ary_post['id']==$ary_post['pid']){
					$this->error("不能选择自己为父分类");
				}else{
					$ary_request['update_time'] = date("Y-m-d H:i:s");
					$ary_res = $mod ->where(array($pk=>$id))->data($ary_post)->save();
					if(FALSE !== $ary_res){
						$this->success("编辑成功");
					}else{
						$this->error("编辑失败");
					}
				}				
			}else{
					if(!empty($ary_post) && is_array($ary_post)){
						$module = D('Category');
						$ary_post['create_time'] = date("Y-m-d H:i:s");
						$ary_result = $module->add($ary_post);
						if(FALSE !== $ary_result){
							$this->success("新增成功",'/Admin/'.MODULE_NAME.'/');
						}else{
							$this->error("新增失败");
						}
					}else{
						$this->error("数据有误，请重试……");
					}				
			}
	}	
	
	public function CategoryDelete(){
        $mod = D('Category');
        $pk = $mod->getPk();
        $ids = $this->_request('ids');
        if ($ids) {
			if(is_array($ids)){
				$idstr=implode(',',$ids);
			}else{
				$idstr=$ids;	
			}
            if (false !== $mod->delete($idstr)) {
                $this->success("删除成功",'/Admin/'.$this->_name."/CategoryIndex/");
            } else {
                $this->error("删除失败",'/Admin/'.$this->_name."/CategoryIndex/");
            }
        } else {
            $this->error("请选择删除的对象",'/Admin/'.$this->_name."/CategoryIndex/");
        }
	}	
	
   /**
     * 分类下拉函数
     * @author billow.wang<admin@ivears.com>
     * @date 2013-12-10
     */
    private function CateGetSelect($currentid, $selectedid =0, $showzerovalue = 1, $selectname = 'pid'){
        $strHtml = '<select name="' . $selectname . '" class="select rounded">';
        if($showzerovalue){
            $strHtml .= '<option value="0">一级栏目</option>';
        }
        $where = array('model'=>$this->_name);
        $where['status'] = '1';
        $ary_category = D("Category")->where($where)->order('`order` desc')->select();
        $strHtml .= $this->CateGetOption($ary_category, $currentid, $selectedid);
        $strHtml .= '</select>';
        return $strHtml;
    }
    
    /**
     * 分类选项列表函数
     * @author billow.wang<admin@ivears.com>
     * @date 2013-12-10
     */
    private function CateGetOption($category, $currentid = 0, $selectedid = 0, $pid = 0, $sublevelmarker = ''){
        if($pid) $sublevelmarker .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├─ ';
        
        foreach($category as $value){
            if($pid == $value['pid'] AND $value['id'] != $currentid){
                $strHtml .= '<option ';
                if(!$pid){
                    $strHtml .= 'style="font-weight:bold;"';
                }
                $strHtml .= 'value="' . $value['id'] . '"';
                if($selectedid == $value['id']){
                    $strHtml .= 'selected';
                }else{
                    $strHtml .= '';
                }
                $strHtml .= '>' . $sublevelmarker . $value['title'] .'</option>';
                $strHtml .= $this->CateGetOption($category, $currentid, $selectedid, $value['id'], $sublevelmarker);
            }
        }
        
        return $strHtml;
    }		
    
}