<?php

Class ProductAction extends CommonAction {

        public function saveTag($vo,$list,$module) {
            if (!empty($vo) && !empty($list)) {
                $Tag = M("Tag");
                $Tagged = M("Tagged");
                $tags = explode(' ',$vo['tags']);
                foreach($tags as $key=>$val) {
                    $val = trim($val);
                    if (!empty($val)) {
                       // 记录已经存在的标签
                       $map["module"] = "Product";
                       $map["name"] = $val;
                       $tagg = $Tag->where($map)->find();
                        if ($tagg) {
							$tagId = $tagg['id'];
                            $Tag->setInc('count','id='.$tagg["id"]);
                        }else {
                            $t = array();
                            $t["name"] = $val;
                            $t["count"] = 1;
                            $t["module"] = $module;
                            $result = $Tag->add($t);
                            $tagId = $result;
                       }
                    }
					//记录tag信息
					$t = array();
					$t["module"] = $module;
					$t["recordId"] = $list;
					$t["tagTime"] = time();
					$t["tagId"] = $tagId;
					$Tagged->add($t);
                }
            }
        }
       // 保存日志的标签和附件
	public function _trigger($vo,$list) {
		if(ACTION_NAME=='insert') {
            $dao = M("Attach");
			$attach['verify'] = 0;
			$attach['recordId'] = $list;
            $dao->where("verify='".$_SESSION["attach_verify"]."'")->save($attach);
		}
		$this->saveTag($vo,$list,"Product");
	}


   public function insert() {
   		$file=$_FILES['attachment']['name'];
		//初始值设为空
		$savefile=$savethumb='';	
		$Product = D("Product");
		$Path=date('Ym');
		if ($vo = $Product->create()) {
			if ($file){
				$uploadfile=$this->_upload('Product',$Path);
				$savefile=$uploadfile[0]['savename'];
				$savethumb=explode('.',$savefile);
				$savethumb=$savethumb[0].C(THUMBSUFFIX).'.'.$savethumb[1];
			}
			$Product->savepath = './Public/Uploads/';
			$Product->attachpath=$Path;
			$Product->attachment=$savefile;
			$Product->attachthumb=$savethumb;
			$list = $Product->add();
			if ($list) {
				//数据保存触发器
				if (method_exists($this,'_trigger')) {
					$this->_trigger($vo,$list);
				}
				$this->success("操作成功");
			}else {
				$this->error("操作失败");
			}
		}else {
			$this->error($Product->getError());
		}
	}
        
	// 查看分类文章
        public function procategory() {
            $pid = $_GET["pid"];
        	$id = $_REQUEST["id"];
            if (!empty($id)) {
                $CateList = M("Procategory");
                if ($CateList) {
                    $procategoryName = $CateList->where('id='.$id and 'id='.$pid)->getField("title");
                    $this->assign('procategoryName', $procategoryName);
                    $dao = D('ProductView');
                    //导入分页类
                    import("@.ORG.Page");
                    //取得满足条件的记录数
                    $count = $dao->where('status=1')->where('procategoryId='.$id)->count();
                    $p = new Page($count, 5);
                    //分页查询数据
                    $voList = $dao->where('status=1')->where('procategoryId='.$id)->limit($p->firstRow.','.$p->listRows)->select();
                    //分页显示
                    $page = $p->show();
                    //模板赋值显示
                    $this->assign('list', $voList);
                    $this->assign("count", $count);
                    $this->assign("page", $page);
                }else {
                   $this->redirect('index');
                   return ;
                }
            }else {
                $this->redirect('index');
            }
            
            $this->display();
            return ;
        }

        public function show() {
            $this->getComment();
            $this->getAttach();
            $id = $_REQUEST["id"];
            if (!empty($id)) {
               $Product = D("ProductView");
               $result = $Product->where('Product.id='.$id)->find();  // 这里为什么用select()就读不出来
               if ($result) {
                   $this->assign('vo', $result);
               }else {
                   $this->redirect('index');
                   return ;
               }
            }else {
                $this->redirect('index');
            }
            $this->display();
            return ;
        }

        public function _after_show() {
            $Product = D("Product");
            $product = $this->get('vo');
            // 阅读计数
            $id	= $product["id"];
            if(!isset($_SESSION['product_read_count_'.$id])) {
		$Product->setInc('readCount',"id=".$id);
		$_SESSION['product_read_count_'.$id] = true;
            }
        }

        public function _before_add() {
                $verify = build_verify(8);
                $_SESSION['attach_verify'] = $verify;
                $this->assign('verify',$verify);
        }
        public function add() {
		    $Cate = M("Procategory");
		    $cateList = $Cate->findAll();
		    $this->assign("procategory", $cateList);        	
            $this->display();
        }
	public function index() {
	       //Load('extend');
		   $Cate = M("Procategory");
		   //$cateList = $Cate->findAll();
		   //$cateList = list_to_tree();

		   $cateList=$Cate->field("id,title,pid,path,concat(path,'-',id) as bpath")->order('bpath')->select();
	       foreach($cateList as $key=>$value){
		   		   $cateList[$key]['count']=count(explode('-',$value['bpath']));
		   	   }
		   $this->assign("procategory", $cateList);
	    
        
                if (ACTION_NAME != "add") {
                    //切换到高级模型
                    $Product = M("Product", "AdvModel");
                    $Comment = M("Comment", "AdvModel");
                    // 需要将msubstr()从扩展库extend.php中拷贝到common.php中
                    $new = $Product->where('status=1')->order("cTime desc")->top10();
                    $comment = $Comment->where('status=1')->order("id desc")->top8();
                    $this->assign("lastProducts", $new);
                    $this->assign("lastComments", $comment);
                    // 标签列表
                    $List = M("Tag");
                    $list  = $List->where("module='Product'")->field('id,name,count')->order('count desc')->limit('0,25')->findAll();
                    $this->assign('tags',$list);

                    $list = array();
                    // 获取归档文章
                    if(!isset($_SESSION["ProductArchiveList2"])) {
                        $Product = M("Product");
                        $new = $Product->max("cTime");
                        $old = strtotime("-1 year");
                        $time = $new;
                        while($time>=$old) {
                            $list[] = array('year'=>date('Y',$time),'month'=>date('m',$time),'show'=>$time);
                            $time = strtotime('-1 month',$time);
			}
                        $_SESSION['ProductArchiveList2'] = $list;
                    }else {
                        $list = $_SESSION['ProductArchiveList2'];
                    }
                    $this->assign('monthList',$list);
                }
		
            $Product = D("ProductView");
            $count = $Product->count();
            $mode = "normal";
            if (isset($_REQUEST["mode"])) {
                $mode = $_REQUEST["mode"];
            }
            if ($mode == "list") {
                $listRows = 23;
                //$fields	= 'id,title,procategoryId,procategory,cTime,readCount,commentCount';
            }else {
                $listRows = 3;
                //$fields	= 'id,title,procategoryId,cTime,readCount,commentCount,content,tags';
            }
            import("@.ORG.Page");
            $p = new Page($count, $listRows);
            $p->setConfig("header", "篇文章");
            $this->assign("mode", $mode);
            $list =  $Product->order("cTime desc")->limit($p->firstRow.','.$p->listRows)->select();
            $page = $p->show();
            $this->assign("list", $list);
            $this->assign("count", $count);
            $this->assign("page", $page);

            //统计数据
            $Product = M("Product");
            $stat = array();
            $stat["beginTime"] = $Product->min('cTime');
            $stat["productCount"] = $Product->where("status=1")->count();
            $stat["readCount"] = $Product->where("status=1")->sum("readCount");
            $stat["commentCount"] = $Product->where("status=1")->sum("commentCount");
            $this->assign($stat);

            $this->display();
	}

        public function tag() {
            $Tag = M("Tag");
            if(!empty($_GET['name'])) {
                $name = trim($_REQUEST['name']);
                $list = $Tag->where("module='Product' and name='$name'")->field('id,count')->find();
				$tagId = $list['id'];
				$count = $list['count'];
				import("@.ORG.Page");
				$listRows = 5;
				$fields	= 'a.id,a.userId,a.procategoryId,a.cTime,a.readCount,a.commentCount,a.title,c.title as procategory';
				$p = new Page($count,$listRows);
				$p->setConfig('header' ,'篇文章 ');
				$dao = D("Product");
				$list = $dao->query("select ".$fields." from ".C('DB_PREFIX').'product as a,'.C('DB_PREFIX').'tagged as b, '.C('DB_PREFIX').'procategory as c where b.tagId  in ('.$tagId.') and a.procategoryId= c.id and a.status=1  and a.id=b.recordId order by a.id desc limit '.$p->firstRow.','.$p->listRows);
				if($list) {
                    $page = $p->show();
                    $this->assign("page", $page);
                    $this->assign('list',$list);
                }
                $this->assign('tag',$name);
                $this->assign("count",$count);
            }else {
                $list = $Tag->where("module='Product'")->findAll();
                //dump($list);
                $this->assign('tags',$list);
            }
            $this->display();
        }

        public function edit() {
            $Product = M("Product");
            $id = $_REQUEST['id'];
            $product = $Product->where('id='.$id)->find();
            //dump($product);
            if($product) {
                $this->getAttach();
                $this->assign('vo',$product);
                $this->display();
            }else{
                $this->redirect('Product/index');
            }
	}
        public function update() {
           $savefile=$savethumb='';
            $file=$_FILES['attachment']['name'];
		    $attachpath=trim($_POST['attachpath']);
		    $oattach=trim($_POST['attachment']);   
			$qattach=trim($_POST['attachthumb']); 
			
			$model = D("Product");
            $vo = $model->create('','edit');
            if(!$vo) {
                $this->error($model->getError());
            }
            $id	= is_array($vo)?$vo[$model->getPk()]:$vo->{$model->getPk()};
            $result  = $model->save($vo);
          
            if($result) {
                //如果有文件上传
                if ($file){
				if ($attachpath=="") $attachpath=date('Ym');
				$uploadfile=$this->_upload('product',$attachpath);
				$savefile=$uploadfile[0]['savename'];
				$savethumb=explode('.',$savefile);
				$savethumb=$savethumb[0].C(THUMBSUFFIX).'.'.$savethumb[1];
				@unlink(C(ATTACHDIR).'/product/'.$attachpath.'/'.$oattach);
				@unlink(C(ATTACHDIR).'/product/'.$attachpath.'/'.$qattach);
			 }
			 $model->savepath = './Public/Uploads/';

			 $model->attachment=$savefile;
			 $model->attachthumb=$savethumb;
			 $data = $model->save();
			 if($data) {
			    //成功提示
                $this->success("操作成功！");
             }else {
                //错误提示
                $this->error("操作失败");
              }
		     }
          }
        	  // 删除数据 
    public function delete() { 
        if(!empty($_POST['id'])) { 
            $Product    =    M("Product"); 
            $result    =    $Product->delete($_POST['id']); 
            if(false !== $result) { 
                $this->ajaxReturn($_POST['id'],'删除成功！',1); 
            }else{ 
                $this->error('删除出错！'); 
            } 
        }else{ 
            $this->error('删除项不存在！'); 
        } 
    }
   // 图像上传
    protected function _upload() {
        import("@.ORG.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize = 3292200;
        //设置上传文件类型
        $upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
        //设置附件上传目录
        $upload->savePath = './Public/Uploads/';
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = true;
        // 设置引用图片类库包路径
        $upload->imageClassPath = '@.ORG.Image';
        //设置需要生成缩略图的文件后缀
        $upload->thumbPrefix = 'm_,s_';  //生产2张缩略图
        //设置缩略图最大宽度
        $upload->thumbMaxWidth = '400,100';
        //设置缩略图最大高度
        $upload->thumbMaxHeight = '400,100';
        //设置上传文件规则
        $upload->saveRule = uniqid;
        //删除原图
        $upload->thumbRemoveOrigin = true;
        if (!$upload->upload()) {
            //捕获上传异常
            $this->error($upload->getErrorMsg());
        } else {
             return $upload->getUploadFileInfo();
        }
       
    } 

}
?>