<?php
class retitleAction extends BackendAction {
	public function _initialize() {
        parent::_initialize();
        
    }

	public function index(){
		$catelist = D('article_cate')->select();
		$this->assign('catelist', $catelist);
		$this->display();
	}
	
	public function setting(){
		if(IS_POST){					
			$fo	    = I('fo');
			$to	    = I('to');	
			$cate_id	    = I('cate_id');
			if($cate_id){
			$where['cate_id'] = $cate_id;
			}
			$where[] = "LOCATE('".$fo."',title)>0";
			$list = D('article')->field('id,title')->where($where)->limit('1,5000')->order('id desc')->select();				
			F('retitle_setting', array(				
				'fo' => $fo,
				'to' => $to,
                'list'=>$list				
			));			
			$this->collect();
		}
	}
    public function changetitle($txt,$fo,$to){
		$title = str_replace($fo,$to, $txt);
		return $title;
	}
    public function collect() {		
		if (false === $setting = F('retitle_setting')) {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
		$p = I('p', 1 ,'intval');
		if($p==1){
			$totalcoll = 0;
		}else{
			$totalcoll = F('totalcoll');
		}
		$list = $setting['list'];
		$fo = $setting['fo'];
		$to = $setting['to'];
		$totalnum = count($list);
		$start = ($p-1)*50;
		$end = $p*50;
		if($totalnum){
		for($i=$start;$i<$end;$i++){					
				$title = $this->changetitle($list[$i]['title'],$fo,$to);
				$itemarray['title']  = $title;
				$itemarray['id'] = $list[$i]['id'];
				if($itemarray['title'] && $itemarray['id']){
			      $result['item_list'][] = $itemarray;
			    }
		}	
		} 	
		
        
		$coll=0;		
		foreach ($result['item_list'] as $key => $val) {
			$res= $this->_ajax_tb_publish_insert($val);
			if($res>0){
				$coll++;
			}
			$totalcoll++;
		}		
		
		F('totalcoll',$totalcoll);
		if($end>$totalnum){		
		F('totalcoll',NULL);
		F('retitle_setting',NULL);
		$this->ajaxReturn(0, '更新完成！');		
		}
		$this->assign('p',$p);
		$this->assign('coll', $coll); 
		$this->assign('totalnum', $totalnum);
		$this->assign('totalcoll', $totalcoll);
		$resp = $this->fetch('collect');
		$this->ajaxReturn(1, '文章更新中', $resp);
    }
	
	private function _ajax_tb_publish_insert($item) { 
		  $result = D('article')->where(array('id'=>$item['id']))->save(array('title'=>$item['title']));
        return $result;
    }
    
}