<?php
class YsjAction extends AdminAction {

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

    public function index() {
		$cid = $this->_request('cid');
		$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);
			}						
		}
		
		if(!$cid){
			$cid=0;	
		}
		$this->assign('cid',$cid);		
		
        $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").$this->_name.".*,".C("DB_PREFIX")."admin.u_name as author_name")
                        ->join(C("DB_PREFIX")."category ON ".C("DB_PREFIX")."category.id=".C("DB_PREFIX").$this->_name.".cid")
                        ->join(C("DB_PREFIX")."admin ON ".C("DB_PREFIX")."admin.u_id=".C("DB_PREFIX").$this->_name.".uid")
                        ->where($where)->limit($obj_page->firstRow, $obj_page->listRows)->order(C("DB_PREFIX").$this->_name.'.`update_time` DESC')->select();


		$category = $this->getSelect($cid);
		$this->assign('category',$category);
        $this->assign("data", $ary_data);
        $this->assign("page", $page);
        $this->display();
    }

    public function Add() {
        $category = $this->getSelect();
        $this->assign("category",$category);
        $this->display('edit');
    }


    public function Save(){
        $ary_post = $this->_post();
		if($ary_post['id']){
			$this->EditSave();
		}else{
			$this->AddSave($ary_post);
		}
    }
	
	
	public function AddSave($ary_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/'.ucfirst($this->_name).'/');
				}else{
					$this->error("新增失败",'/Admin/'.ucfirst($this->_name).'/');
				}
			}else{
				$this->error("数据有误，请重试……",'/Admin/'.ucfirst($this->_name).'/');
			}		
	}
    

    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("请选择需要编辑的对象",'/Admin/'.ucfirst($this->_name).'/');
        }
    }
    
    public function EditSave(){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $field = $mod->getDbFields();
        $ary_request = $this->_request();
        $id = $ary_request[$pk];
        unset($ary_request[$pk]);
        if($id){
            $where = array();
            $where[$pk] = array('NEQ',$id);
            $where[$field[1]] = $ary_request[$field[1]];
            $ary_data = $mod ->where($where)->find();
            if(!empty($ary_data) && is_array($ary_data)){
                $this->error("名称已存在",'/Admin/'.ucfirst($this->_name).'/');
            }else{
                $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("编辑成功",'/Admin/'.ucfirst($this->_name).'/');
                }else{
                    $this->error("编辑失败",'/Admin/'.ucfirst($this->_name).'/');
                }
            }
        }else{
            $this->error("请选择需要编辑的对象",'/Admin/'.ucfirst($this->_name).'/');
        }
        
    }

    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("启用成功",'/Admin/'.ucfirst($this->_name).'/');
                }else{
                    $this->success("禁用成功",'/Admin/'.ucfirst($this->_name).'/');
                }
            }  else {
                if(!empty($ary_post['val']) && $ary_post['val'] == '1'){
                    $this->success("启用失败",'/Admin/'.ucfirst($this->_name).'/');
                }else{
                    $this->success("禁用失败",'/Admin/'.ucfirst($this->_name).'/');
                }
            }
        }else{
            $this->error("该信息不存在",'/Admin/'.ucfirst($this->_name).'/');
        }
    }

    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/'.ucfirst($this->_name).'/');
            } else {
                $this->error("删除失败",'/Admin/'.ucfirst($this->_name).'/');
            }
        } else {
            $this->error("请选择删除的对象",'/Admin/'.ucfirst($this->_name).'/');
        }
    }
    
    private function getSelect($selectedid =0, $selectname = 'cid'){
        $sReturn = '<select name="' . $selectname . '"><option value="0">-- 请选择 --</option>';
        $ary_category = D("Category")->where(array('model'=>ucfirst($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'=>ucfirst($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'=>ucfirst($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-url='/Admin/$this->modulename/CategoryEdit?id=\$id'  class='dialog' alt='编辑' title='编辑'  data-height='200' data-width='500'>编缉</a>
                       <a href='/Admin/$this->modulename/CategoryDelete?ids=\$id' class='doDel' title='删除'>删除</a>
                            </div>
                        </td>
                    </tr>";
            $tree->init($array);
            $list = $tree->get_tree(0, $str);
            $this->assign('Category_index', $list);
			 $this->assign('list', $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("请选择需要编辑的对象",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
			}		
	}	
	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("不能选择自己为父分类",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
				}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("编辑成功",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
					}else{
						$this->error("编辑失败",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
					}
				}				
			}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/'.ucfirst($this->_name).'/CategoryIndex/');
						}else{
							$this->error("新增失败",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
						}
					}else{
						$this->error("数据有误，请重试……",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
					}				
			}
	}	
	
	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/'.ucfirst($this->_name).'/CategoryIndex/');
            } else {
                $this->error("删除失败",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
            }
        } else {
            $this->error("请选择删除的对象",'/Admin/'.ucfirst($this->_name).'/CategoryIndex/');
        }
	}	
	
    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'=>ucfirst($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;
    }
    
    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;
    }	
    
}