<?php
defined('PP_PATH') or exit;
class products_control extends admin_control {
	// 内容管理
	public function index() {
		$cid = intval(R('cid'));
		$cid = !isset($cid) ? $cid : intval(R($_ENV['_config']['cookie_pre'].'2_cid','R'));
		$tuan = intval(R('tuan'));
		$status = intval(R('status'));
		$keyword = empty($_POST) ? R('keyword') : R('keyword', 'P');
		if($keyword) {
			$keyword = urldecode($keyword);
			$keyword = safe_str($keyword);
		}
		$this->assign('keyword', $keyword);

		$user_group = &$this->user_group;
		$group_arr = $user_group->get_groups();

		foreach($group_arr as $k=>$g){
			$purviews	= json_decode($group_arr[$k]['purviews'],true);
			if($g['groupid'] < 5 || !empty($purviews['other']['issuper'])){	//去除管理组、超级组（全站免费）
				unset($group_arr[$k]);
			}
			unset($group_arr[$k]['purviews']);
		}

		$_group_arr	= json_encode($group_arr);
		$this->assign('group_arr', $_group_arr);

		// 获取分类下拉框
		$cidhtml = $this->category->get_cidhtml_by_mid(2, $cid, '所有资源');
		$category_array = $this->category->get_category();
		$cidjson = array();
		if(isset($category_array[2])) {
			$cidjson	= json_encode($category_array[2]);
		}
		$this->assign('cidhtml', $cidhtml);
		$this->assign('cidjson', $cidjson);

		// 初始模型表名
		$this->cms_content->table = 'cms_products';

		// 初始分页
		$pagenum = 20;
		$where = array();
		
		$now = strtotime(date('Y-m-d',time())); //1449417600    1442332799

		if($keyword) {
			$where['title'] = array('LIKE'=>$keyword);
			$total = $this->cms_content->find_count($where);
			$urlstr = '-keyword-'.urlencode($keyword);
		}elseif($cid) {
			$where['cid'] = $cid;
			$categorys = $this->category->read($cid);
			$total = isset($categorys['count']) ? $categorys['count'] : 0;
			$urlstr = '-cid-'.$cid;
		}elseif($tuan==1){ //限时已结束
			$where['zk_start'] = array('>'=>0);
			$where['zk_end'] = array('>'=>0,'<='=>$now);
			$total = $this->cms_content->find_count($where);
			$urlstr = '-tuan-'.$tuan;
		// }elseif($tuan==2){ //未成功的团购
			// $where['tuanover'] = array('>'=>0);
			// $where['zk_end'] = array('>'=>0,'<='=>$now);
			// $total = $this->cms_content->find_count($where);
			// $urlstr = '-tuan-'.$tuan;
		}elseif($tuan==3){ //限时优惠中
			$where['zk_start'] = array('>'=>0,'<'=>$now);
			$where['zk_end'] = array('>'=>0,'>='=>$now);
			$total = $this->cms_content->find_count($where);
			$urlstr = '-tuan-'.$tuan;
		}elseif($status==1){
			$where['status'] = array('='=>1);
			$total = $this->cms_content->find_count($where);
			$urlstr = '-status-'.$status;
		}elseif($status==2){
			$where['status'] = array('='=>2);
			$total = $this->cms_content->find_count($where);
			$urlstr = '-status-'.$status;
		}else{
			$total = $this->cms_content->count();
			$urlstr = '';
		}
		$maxpage = max(1, ceil($total/$pagenum));
		$page = min($maxpage, max(1, intval(R('page'))));
		$pages = pp_pages($page, $maxpage, 'index.php?u=products-index'.$urlstr.'-page-{page}');
		$this->assign('total', $total);
		$this->assign('pages', $pages);
		$this->assign('order', $order);

		// 读取内容列表
		$flag_arr = array(1=>'推荐', 2=>'热点', 3=>'头条', 4=>'精选', 5=>'幻灯');
		//$cms_products_arr = $this->cms_content->list_arr($where, $orderby, $orderway, ($page-1)*$pagenum, $pagenum, $total);
		$cms_products_arr = $this->cms_content->list_arr($where, 'id', -1, ($page-1)*$pagenum, $pagenum, $total);
		foreach($cms_products_arr as &$v){
			$this->cms_content->format($v, 2, 'Y-m-d H:i:s', 20);
			// 属性
			$v['flagstr'] = '';
			$v['imgstr'] = '';
			if(!empty($v['imagenum'])) {
				$v['imgstr'] .= ' [图]';
			}
			$flags = empty($v['flags']) ? array() : explode(',', $v['flags']);
			foreach($flag_arr as $k=>$flag) {
				if(in_array($k,$flags)){
					$v['flagstr'] .= ' <a  href="javascript:setflags('.$v['id'].', '.$v['cid'].', '.$k.',\'确定取消？\');" class="label label-success">'.$flag.'</a>';
				}else{
					$v['flagstr'] .= ' <a  href="javascript:setflags('.$v['id'].', '.$v['cid'].', '.$k.',\'确定设置？\');" class="label label-gray">'.$flag.'</a>';
				}
			}
			if($v['imgstr']) $v['imgstr'] = '<font color="red">'.$v['imgstr'].'</font>';

			$v['zk_start'] 	= !empty($v['zk_start']) ? date('Y/m/d', $v['zk_start']) : '';
			$v['zk_end'] 	= !empty($v['zk_end']) ? date('Y/m/d', $v['zk_end']) : '';
			$v['tuanadmin']	  = '<a class="but3" href="javascript:tuan_edit('.$v['id'].');">设置</a>';
			$v['timestyle']	= '';
			if($v['iszk']){
				$v['timestyle']	= 'color:green;';
			}else{
				if($v['zk_end']){
					$v['tuanadmin']	  .= ' <a class="but3" href="javascript:tuan_over('.$v['id'].', '.$v['cid'].',3);">撤销</a>';
				}
			}
			$v['cate_arr'] = $this->category->get_cache($v['cid']);
			if(!empty($v['need_groupid'])){
				$v['need_groupname'] = $group_arr["user_group-groupid-".$v['need_groupid']]['groupname'] ;
			}
		}

		$this->assign('flag_arr', $flag_arr);
		$this->assign('cms_products_arr', $cms_products_arr);
		$this->display();
	}
	
	public function faq() {
		
		$pid = intval(R('pid'));

		$this->_pkey = 'content';
		$this->_ukey = 'products-faq-pid-'.$pid;
		$this->_title = 'FAQ管理';
		$this->_place = '内容 &#187; 内容管理 &#187 FAQ管理';
		
		
		$this->cms_content->table = 'cms_products';
		$pro = $this->cms_content->get($pid);

		// 初始模型表名
		$this->cms_content->table = 'cms_faq';

		// 初始分页
		$pagenum = 20;
		if($pid) {
			$where = array('pid' => $pid);
			$total = $this->cms_content->find_count($where);
			$urlstr = '-pid-'.$pid;
		}else{
			$where = array();
			$total = $this->cms_content->count();
			$urlstr = '';
		}
		$maxpage = max(1, ceil($total/$pagenum));
		$page = min($maxpage, max(1, intval(R('page'))));
		$pages = pp_pages($page, $maxpage, 'index.php?u=products-faq'.$urlstr.'-page-{page}');
		$this->assign('total', $total);
		$this->assign('pages', $pages);

		$cms_article_arr = $this->cms_content->list_arr($where, 'id', -1, ($page-1)*$pagenum, $pagenum, $total);
		
		$this->assign('pid', $pid);
		$this->assign('title', $pro['title']);
		$this->assign('cms_article_arr', $cms_article_arr);
		$this->display();
	}

	
	// 发布faq
	public function faq_add() {

		$uid = $this->_user['uid'];
		if(empty($_POST)) {
			$pid = intval(R('pid'));
			
			$this->_pkey = 'content';
			$this->_ukey = 'products-faq_add-pid-'.$pid;
			$this->_title = '添加faq';
			$this->_place = '内容 &#187; 资源管理 &#187 添加faq';
			
			$this->cms_content->table = 'cms_products';
			$pro = $this->cms_content->get($pid);

			$this->assign('pid', $pid);
			$this->assign('title', $pro['title']);

			$this->display('products_faq_set.htm');
		}else{
			$pid 		= intval(R('pid', 'P'));
			$title 		= trim(strip_tags(R('title', 'P')));
			$contentstr = trim(R('content', 'P'));
			$dateline 	= trim(R('dateline', 'P'));

			empty($title) && E(1, '亲，您的标题忘了填哦！');
			if(strlen($contentstr) < 5) E(1, '亲，您的内容字数太少了哦！');

			// 写入内容表
			$data = array(
				'pid' => $pid,
				'title' => $title,
				'uid' => $uid,
				'dateline' => $dateline ? strtotime($dateline) : $_ENV['_time'],
				'lasttime' => $_ENV['_time'],
			);
			$this->cms_content->table = 'cms_faq';
			$id = $this->cms_content->create($data);
			if(!$id) {
				E(1, '写入内容表出错');
			}

			// 写入内容数据表
			$this->cms_content_data->table = 'cms_faq_data';
			if(!$this->cms_content_data->set($id, array('pid' => $pid,'content' => $contentstr))) {
				E(1, '写入内容数据表出错');
			}
			
			//更新faqs
			$this->cms_content->table = 'cms_products';
			$pdata = $this->cms_content->read($pid);
			
			$pdata['faqs']++;
			if(!$this->cms_content->update($pdata)) {
				E(1, '更新内容faq数量出错！');
			}

			E(0, '发布完成');
		}
	}
	
	// 编辑
	public function faq_edit() {
		if(empty($_POST)) {
			$id = intval(R('id'));
			$pid = intval(R('pid'));

			$this->_pkey = 'content';
			$this->_ukey = 'products-faq_edit-pid-'.$pid.'-id-'.$id;
			$this->_title = '编辑faq';
			$this->_place = '内容 &#187; faq管理 &#187 编辑faq';
			
			$this->cms_content->table = 'cms_products';
			$pro = $this->cms_content->get($pid);

			$this->assign('pid', $pid);
			$this->assign('title', $pro['title']);

			// 读取内容
			$this->cms_content->table = 'cms_faq';
			$this->cms_content_data->table = 'cms_faq_data';
			$data = $this->cms_content->get($id);
			if(empty($data)) $this->message(0, '内容不存在！', -1);

			$data2 = $this->cms_content_data->get($id);
			$data = array_merge($data, $data2);
			$data['content'] = htmlspecialchars($data['content']);
			$data['dateline'] = date('Y-m-d H:i:s', $data['dateline']);
			$data['lasttime'] = date('Y-m-d H:i:s', $data['lasttime']);

			$this->assign('data', $data);

			$this->display('products_faq_set.htm');
		}else{
			$id = intval(R('id', 'P'));
			$pid = intval(R('pid', 'P'));
			
			$title = trim(strip_tags(R('title', 'P')));

			$contentstr = trim(R('content', 'P'));

			$uid = $this->_user['uid'];

			empty($id) && E(1, 'ID不能为空！');
			empty($pid) && E(1, '哪个资源的faq？');
			empty($title) && E(1, '亲，您的标题忘了填哦！');
			if(strlen($contentstr) < 5) E(1, '亲，您的内容字数太少了哦！');

			$this->cms_content->table = 'cms_faq';
			$data = $this->cms_content->get($id);
			if(empty($data)) E(1, '内容不存在！');

			$endstr = '';

			// 写入内容表
			$data['pid'] = $pid;
			$data['id'] = $id;
			$data['title'] = $title;

			$data['uid'] = $uid;

			$data['dateline'] = strtotime(trim(R('dateline', 'P')));
			$data['lasttime'] = $_ENV['_time'];

			if(!$this->cms_content->update($data)) {
				E(1, '更新内容表出错');
			}

			// 写入内容数据表
			$this->cms_content_data->table = 'cms_faq_data';
			if(!$this->cms_content_data->set($id, array('content' => $contentstr))) {
				E(1, '写入内容数据表出错');
			}

			E(0, '编辑完成');
		}
	}
	
	// 删除faq
	public function faq_del() {
		$id = (int) R('id', 'P');
		$pid = (int) R('pid', 'P');

		empty($id) && E(1, 'ID不能为空！');
		empty($pid) && E(1, '资源ID不能为空！');

		$err = $this->cms_faq->xdelete('products', $pid, $id);
		if($err) {
			E(1, $err);
		}else{
			E(0, '删除成功！');
		}
	}
	
	// 添加
	public function add() {
		$uid = $this->_user['uid'];
		if(empty($_POST)) {
			$this->_pkey = 'content';
			$this->_ukey = 'products-add';
			$this->_title = '添加资源';

			$habits = (array)$this->kv->get('user_habits_uid_'.$uid);
			$cid = isset($habits['last_add_cid']) ? (int)$habits['last_add_cid'] : 0;

			$data = $this->kv->get('auto_save_products_uid_'.$uid);
			if($data) {
				!empty($data['cid']) && $cid = $data['cid'];
				!empty($data['size_mb']) && $data['size_mb'] = $data['size_mb']-0;
				$data['pic_src'] = empty($data['pic']) ? '../static/img/nopic.gif' : '../'.$data['pic'];
				empty($data['author']) && $data['author'] = $this->_user['username'];
				!empty($data['images']) && $data['images'] = (array)$data['images'];
				!empty($data['downs']) && $data['downs'] = (array)$data['downs'];
				$data['content'] = htmlspecialchars($data['content']);
			}else{
				$data['pic_src'] = '../static/img/nopic.gif';
				$data['author'] = $this->_user['username'];
				$data['views'] = 0;
			}

			$data['lan'] = form::loop('select', 'info[lan]', $_ENV['_config']['lan'], $data['lan'], ' ','form-control');
			$data['sqls'] = form::loop('select', 'info[sqls]', $_ENV['_config']['sqls'], $data['sqls'], ' ','form-control');
			$data['license'] = form::loop('select', 'info[license]', $_ENV['_config']['license'], $data['license'], ' ','form-control');
			$this->assign('data', $data);

			$cidhtml = $this->category->get_cidhtml_by_mid(2, $cid);
			$this->assign('cidhtml', $cidhtml);

			$edit_cid_id = '&mid=2';
			$this->assign('edit_cid_id', $edit_cid_id);

			$this->display('products_set.htm');
		}else{
			$cid 		= intval(R('cid', 'P'));
			
			//主表数据
			$info 			= R('info','P');
			$info['cid'] 	= $cid;
			$info['uid'] 	= $uid;
			$info['title'] 	= trim(strip_tags($info['title']));

			//副表数据
			$contentstr = trim(R('content', 'P'));
			$images 	= (array)R('images', 'P');
			$downs 		= (array)R('downs', 'P');

			empty($cid) && E(1, '没有选择分类！');
			empty($info['title']) && E(1, '标题不能为空！');

			$categorys = $this->category->read($cid);
			if(empty($categorys)) E(1, '分类ID不存在！');

			$mid = $this->category->get_mid_by_cid($cid);
			$table = $this->models->get_table($mid);

			// 防止提交到其他模型的分类
			if($table != 'products') E(1, '分类ID非法！');

			// 检测别名是否能用
			if($info['alias'] && $err_msg = $this->only_alias->check_alias($info['alias'])){
				E(1, $err_msg);
			}
			
			// 标签预处理，最多支持5个标签
			$tags = trim($info['tags'], ", \t\n\r\0\x0B");
			$tags_arr = explode(',', $tags);
			$this->cms_content_tag->table = 'cms_'.$table.'_tag';
			$tagdatas = $tags = array();
			for($i=0; isset($tags_arr[$i]) && $i<5; $i++) {
				$name = trim($tags_arr[$i]);
				if($name) {
					$tagdata = $this->cms_content_tag->find_fetch(array('name'=>$name), array(), 0, 1);
					if($tagdata) {
						$tagdata = current($tagdata);
					}else{
						$tagid = $this->cms_content_tag->create(array('name'=>$name, 'count'=>0, 'content'=>''));
						if(!$tagid) E(1, '写入标签表出错');
						$tagdata = $this->cms_content_tag->get($tagid);
					}

					$tagdata['count']++;
					$tagdatas[] = $tagdata;
					$tags[$tagdata['tagid']] = $tagdata['name'];
				}
			}
			
			// 远程图片本地化
			$isremote = intval(R('isremote', 'P'));
			$endstr = '';
			if($isremote) {
				$endstr .= $this->get_remote_img($table, $contentstr, $mid, $uid);
			}
			
			// 计算图片数，和非图片文件数
			$imagenum = $this->cms_attach->find_count(array('id'=>0, 'mid'=>$mid, 'uid'=>$uid, 'isimage'=>1));
			$filenum = $this->cms_attach->find_count(array('id'=>0, 'mid'=>$mid, 'uid'=>$uid, 'isimage'=>0));

			// 如果缩略图为空，并且内容含有图片，则将第一张图片设置为缩略图
			if(empty($info['pic']) && $imagenum) {
				$info['pic'] = $this->auto_pic($table, $uid);
			}
			
			// 如果摘要为空，自动生成摘要
			$info['intro'] = $this->auto_intro($info['intro'], $contentstr);

			// 写入内容表
			$info['tags'] 			= _json_encode($tags);
			$info['dateline'] 		= $info['dateline'] ? strtotime($info['dateline']) : $_ENV['_time'];
			$info['lasttime']		= $info['lasttime'] ? strtotime($info['lasttime']) : $_ENV['_time'];
			$info['seo_keywords']	= trim(strip_tags($info['seo_keywords']));
			$info['seo_description']= trim(strip_tags($info['seo_description'],'<br>'));
			
			$info['imagenum'] 		= $imagenum;
			$info['filenum'] 		= $filenum;
			
			$info['status'] 		= !empty($info['status']) ? $info['status'] : 0 ;

			
			$this->cms_content->table = 'cms_'.$table;
			
			$id = $this->cms_content->create($info);
			if(!$id) {
				E(1, '写入内容表出错');
			}

			// 写入全站唯一别名表
			if($info['alias'] && !$this->only_alias->set($info['alias'], array('mid' => $mid, 'cid' => $cid, 'id' => $id))) {
				E(1, '写入全站唯一别名表出错');
			}

			// 写入内容数据表
			$this->cms_content_data->table = 'cms_'.$table.'_data';
			if(!$this->cms_content_data->set($id, array('content' => $contentstr, 'images' => json_encode($images), 'downs' => json_encode($downs)))) {
				E(1, '写入内容数据表出错');
			}

			// 更新附件归宿 cid 和 id
			if($imagenum || $filenum) {
				if(!$this->cms_attach->find_update(array('id'=>0, 'uid'=>$uid), array('cid'=>$cid, 'id'=>$id))) {
					E(1, '更新内容附件表出错');
				}
			}

			// 写入评分表
			$this->cms_content_golds->table = 'cms_'.$table.'_golds';
			if(!$this->cms_content_golds->set($id, array('cid' => $cid, 'gold' => 0, 'golder' => 0))) {
				E(1, '写入评分表出错');
			}
			
			// 写入内容标签表
			$this->cms_content_tag_data->table = 'cms_'.$table.'_tag_data';
			foreach($tagdatas as $tagdata) {
				$this->cms_content_tag->update($tagdata);
				$this->cms_content_tag_data->set(array($tagdata['tagid'], $id), array('id'=>$id));
			}

			// 如果内容含有图片附件，则标记图片属性
			$this->cms_content_flag->table = 'cms_'.$table.'_flag';
			if($imagenum && !$this->cms_content_flag->set(array(0, $id), array('cid'=>$cid))) {
				E(1, '写入内容属性标记表出错');
			}

			// 更新用户发布的内容条数
			$this->_user['contents']++;
			$this->user->update($this->_user);

			// 更新分类的内容条数
			$categorys['count']++;
			$categorys['count_'.$info['status']]++;
			
			$this->category->update($categorys);
			$this->category->update_cache($cid);

			$data = $this->kv->delete('auto_save_products_uid_'.$uid);

			// 记住最后一次发布的分类ID，感觉这样人性化一些吧。
			$habits = (array) $this->kv->get('user_habits_uid_'.$uid);
			$habits['last_add_cid'] = $cid;
			$habits = $this->kv->set('user_habits_uid_'.$uid, $habits);
			
			if(!empty($info['baidu'])){
				$_thisurl = $this->_cfg['webdomain'].$this->cms_content->content_url($cid, $id, $alias, $dateline);
				$thisurl = array('http://'.$_thisurl);
				$res = $this->mmisc->baidup($thisurl,$this->_cfg['bdts']);
				if($res['success']>0){ //推送成功
					$this->cms_content->update(array('id'=>$id,'baidu'=>1));
				}
			}
			
			E(0, '发布完成'.$endstr);
		}
	}

	// 编辑
	public function edit() {
		$uid 		= $this->_user['uid'];
		if(empty($_POST)) {
			$id = intval(R('id'));
			$cid = intval(R('cid'));

			$this->_pkey = 'content';
			$this->_ukey = 'products-edit-cid-'.$cid.'-id-'.$id;
			$this->_title = '编辑资源';

			$cidhtml = $this->category->get_cidhtml_by_mid(2, $cid);
			$this->assign('cidhtml', $cidhtml);

			$table = 'products';

			// 读取内容
			$this->cms_content->table = 'cms_'.$table;
			$this->cms_content_data->table = 'cms_'.$table.'_data';
			$data = $this->cms_content->get($id);
			if(empty($data)) $this->message(0, '内容不存在！', -1);

			$data2 = $this->cms_content_data->get($id);
			$data = array_merge($data, $data2);
			$data['content'] = htmlspecialchars($data['content']);
			$data['tags'] = implode(',', (array)_json_decode($data['tags']));
			$data['dateline'] = date('Y-m-d H:i:s', $data['dateline']);
			$data['lasttime'] = date('Y-m-d H:i:s', $data['lasttime']);

			$data['pic_src'] = empty($data['pic']) ? '../static/img/nopic.gif' : '../'.$data['pic'];
			$data['images'] = (array)_json_decode($data['images']);
			$data['downs'] = (array)_json_decode($data['downs']);

			$data['lan'] = form::loop('select', 'info[lan]', $_ENV['_config']['lan'], $data['lan'], ' ','form-control');
			$data['sqls'] = form::loop('select', 'info[sqls]', $_ENV['_config']['sqls'], $data['sqls'], ' ','form-control');
			$data['license'] = form::loop('select', 'info[license]', $_ENV['_config']['license'], $data['license'], ' ','form-control');
			$this->assign('data', $data);

			//pid 缩略图id          down_id 附件id
			$edit_cid_id = '&mid=2&cid='.$data['cid'].'&id='.$data['id'].'&pid='.$data['pid'];
			$this->assign('edit_cid_id', $edit_cid_id);

			$this->display('products_set.htm');
		}else{
			$id 		= intval(R('id', 'P'));
			$cid 		= intval(R('cid', 'P'));
			
			//主表数据
			$info 			= R('info','P');
			$info['cid'] 	= $cid;
			$info['uid'] 	= $uid;
			$info['title'] 	= trim(strip_tags($info['title']));
			
			$info['status'] = !empty($info['status']) ? $info['status'] : 0 ;

			//副表数据
			$contentstr = trim(R('content', 'P'));
			$images 	= (array)R('images', 'P');
			$downs 		= (array)R('downs', 'P');

			empty($id) && E(1, 'ID不能为空！');
			empty($cid) && E(1, '您没有选择分类！');
			empty($info['title']) && E(1, '标题不能为空！');

			$categorys = $this->category->read($cid);
			if(empty($categorys)) E(1, '分类ID不存在！');

			$mid = $this->category->get_mid_by_cid($cid);
			$table = $this->models->get_table($mid);

			// 防止提交到其他模型的分类
			if($table != 'products') E(1, '分类ID非法！');

			$this->cms_content->table = 'cms_'.$table;
			$data = $this->cms_content->get($id);
			if(empty($data)) E(1, '内容不存在！');

			// 检测别名是否能用
			$alias_old = $data['alias'];
			if($info['alias'] && $info['alias'] != $alias_old && $err_msg = $this->only_alias->check_alias($info['alias'])) {
				E(1, $err_msg);
			}

			// 如果分类ID发生变化，更新分类内容数
			if($cid != $data['cid']) {
				// 旧的分类内容数减1
				$categorys_old = $this->category->read($data['cid']);
				$categorys_old['count'] --;
				$categorys_old['count_'.$data['status']] --;
				$this->category->update($categorys_old);

				// 新的分类内容数加1
				$categorys['count']++;
				$categorys['count_'.$data['status']]++;
				$this->category->update($categorys);

				$this->category->delete_cache();
				
				//分类改变时，别名也需要更新
				if(!$this->only_alias->set($info['alias'], array('mid' => $mid, 'cid' => $cid, 'id' => $id))) {
					E(1, '分类改变，但更新别名分类出错');
				}
			}
			
			//状态改变时更新分类内容数量
			if($info['status'] != $data['status']){
				$categorys['count_'.$info['status']]++;
				$categorys['count_'.$data['status']]--;
				$this->category->update($categorys);
				$this->category->delete_cache();
			}

			// 编辑时，别名有三种情况需要处理
			if($info['alias'] && $alias_old && $info['alias'] != $alias_old) {
				// 写入新别名
				if(!$this->only_alias->set($info['alias'], array('mid' => $mid, 'cid' => $cid, 'id' => $id))) {
					E(1, '写入全站唯一别名表出错');
				}

				// 删除旧别名
				if(!$this->only_alias->delete($alias_old)) {
					E(1, '删除别名表数据时出错');
				}
			}elseif($info['alias'] && empty($alias_old)) {
				// 写入新别名
				if(!$this->only_alias->set($info['alias'], array('mid' => $mid, 'cid' => $cid, 'id' => $id))) {
					E(1, '写入全站唯一别名表出错');
				}
			}elseif(empty($info['alias']) && $alias_old) {
				// 删除旧别名
				if(!$this->only_alias->delete($alias_old)) {
					E(1, '删除别名表数据时出错');
				}
			}

			// 比较标签变化
			$tags = trim($info['tags'], ", \t\n\r\0\x0B");
			$tags_new = explode(',', $tags);
			$tags_old = (array)_json_decode($data['tags']);
			$tags_arr = $tags = array();
			foreach($tags_new as $tagname) {
				$key = array_search($tagname, $tags_old);
				if($key === false) {
					$tags_arr[] = $tagname;
				}else{
					$tags[$key] = $tagname;
					unset($tags_old[$key]);
				}
			}

			// 标签预处理，最多支持5个标签
			$this->cms_content_tag->table = 'cms_'.$table.'_tag';
			$tagdatas = array();
			for($i=0; isset($tags_arr[$i]) && $i<5; $i++) {
				$name = trim($tags_arr[$i]);
				if($name) {
					$tagdata = $this->cms_content_tag->find_fetch(array('name'=>$name), array(), 0, 1);
					if($tagdata) {
						$tagdata = current($tagdata);
					}else{
						$tagid = $this->cms_content_tag->create(array('name'=>$name, 'count'=>0, 'content'=>''));
						if(!$tagid) E(1, '写入标签表出错');
						$tagdata = $this->cms_content_tag->get($tagid);
					}

					$tagdata['count']++;
					$tagdatas[] = $tagdata;
					$tags[$tagdata['tagid']] = $tagdata['name'];
				}
			}
			
			// 远程图片本地化
			$isremote = intval(R('isremote', 'P'));
			$endstr = '';
			if($isremote) {
				$endstr .= $this->get_remote_img($table, $contentstr, $mid, $uid, $cid, $id);
			}
			
			// 计算图片数，和非图片文件数
			$imagenum = $this->cms_attach->find_count(array('id'=>$id,'mid'=>$mid, 'uid'=>$uid, 'isimage'=>1));
			$filenum = $this->cms_attach->find_count(array('id'=>$id,'mid'=>$mid, 'uid'=>$uid, 'isimage'=>0));

			// 如果缩略图为空，并且内容含有图片，则将第一张图片设置为缩略图
			if(empty($info['pic']) && $imagenum) {
				$info['pic'] = $this->auto_pic($table, $uid);
			}

			// 如果摘要为空，自动生成摘要
			$info['intro'] = $this->auto_intro($info['intro'], $contentstr);
			
			// 写入内容表
			$info['tags'] 			= _json_encode($tags);
			$info['dateline'] 		= $info['dateline'] ? strtotime($info['dateline']) : $_ENV['_time'];
			$info['lasttime']		= strtotime(trim($info['lasttime']));
			$info['seo_keywords']	= trim(strip_tags($info['seo_keywords']));
			$info['seo_description']= trim(strip_tags($info['seo_description'],'<br>'));
			
			$info['imagenum'] 		= $imagenum;
			$info['filenum'] 		= $filenum;
			
			$data = array_merge($data,$info);

			
			if(!$this->cms_content->update($data)) {
				E(1, '更新内容表出错');
			}

			// 写入内容数据表
			$this->cms_content_data->table = 'cms_'.$table.'_data';
			if(!$this->cms_content_data->set($id, array('content' => $contentstr, 'images' => json_encode($images), 'downs' => json_encode($downs)))) {
				E(1, '写入内容数据表出错');
			}

			// 更新附件归宿 cid 和 id
			// if($imagenum || $filenum) {
				// if(!$this->cms_attach->find_update(array('id'=>0, 'uid'=>$uid), array('cid'=>$cid, 'id'=>$id))) {
					// E(1, '更新内容附件表出错');
				// }
			// }

			// 写入内容属性标记表
			$this->cms_content_flag->table = 'cms_'.$table.'_flag';

			// 如果内容含有图片附件，则标记图片属性，否则删除图片属性
			if($imagenum) {
				$this->cms_content_flag->set(array(0, $id), array('cid'=>$cid));
			}else{
				$this->cms_content_flag->delete(0, $id);
			}


			// 写入内容标签表
			$this->cms_content_tag_data->table = 'cms_'.$table.'_tag_data';
			foreach($tagdatas as $tagdata) {
				$this->cms_content_tag->update($tagdata);
				$this->cms_content_tag_data->set(array($tagdata['tagid'], $id), array('id'=>$id));
			}

			// 删除不用的标签
			foreach($tags_old as $tagid => $tagname) {
				$tagdata = $this->cms_content_tag->get($tagid);
				$tagdata['count']--;
				$this->cms_content_tag->update($tagdata);
				$this->cms_content_tag_data->delete($tagid, $id);
			}
			
			if(!empty($info['baidu'])){
				$_thisurl 	= $this->_cfg['webdomain'].$this->cms_content->content_url($cid, $id, $alias, $dateline);
				$thisurl 	= array('http://'.$_thisurl);
				$res 		= $this->mmisc->baidup($thisurl,$this->_cfg['bdts']);
				if($res['success']>0){ //推送成功
					$this->cms_content->update(array('id'=>$id,'baidu'=>1));
				}
			}

			E(0, '编辑完成'.$endstr);
		}
	}
	// 组团提前结束/退款
	public function tuan_over() {
		$id = (int) R('id', 'P');
		$cid = (int) R('cid', 'P');
		$type = (int) R('type', 'P'); //1 完成组团 2 失败退款 3 转为普通上架

		empty($id) && E(1, '内容ID不能为空！');
		empty($cid) && E(1, '分类ID不能为空！');
		$this->cms_content->table = 'cms_products';
		$data = $this->cms_content->get($id);
		
		$data['zk_start'] 	= 0;
		$data['zk_end'] 	= 0;
		$data['zk_price'] 	= 0;
		$this->cms_content->update($data);
		E(0, '操作成功');
	}
	// 列表页ajax更新价格、数量、等 
	public function ajaxset(){
		$id 		= intval(R('id', 'P'));
		$cid 		= intval(R('cid', 'P'));
		$type 		= R('type', 'P');
		$txtvalue 	= intval(R('txtvalue', 'P'));

		empty($id) && E(1, '内容ID不能为空！');
		
		$this->cms_content->table = 'cms_products';
		$data = $this->cms_content->get($id);
		$old_status = $data['status'] ;
		
		$data[$type] = $txtvalue;
		
		if(!$this->cms_content->update($data)) {
			E(1, '更新出错');
		}
		
		if($type == 'status'){
			$categorys = $this->category->read($cid);
			$categorys['count_'.$txtvalue]++;
			$categorys['count_'.$old_status]--;
			$this->category->update($categorys);
			$this->category->delete_cache();
		}
		
		E(0, '更新成功！');
	}
	//列表页更新幻灯等 只能一次设置一个属性
	public function ajaxsetflags(){
		$id 		= intval(R('id', 'P'));
		$cid 		= intval(R('cid', 'P'));
		$value 		= intval(R('value', 'P'));

		empty($id) && E(1, '内容ID不能为空！');

		$this->cms_content->table = 'cms_products';
		$this->cms_content_flag->table = 'cms_products_flag';
		$data = $this->cms_content->get($id);
		
		$flags_old = array();
		if($data['flags']){
			$flags_old = explode(',', $data['flags']);
		}
		if(in_array($value,$flags_old)){
			$key = array_search($value, $flags_old);
			//删除原有内容属性
			if(!$this->cms_content_flag->delete($value, $id)) {
				E(1, '删除原有内容属性出错');
			}
			unset($flags_old[$key]);
		}else{
			array_push($flags_old,$value);
			// 写入内容属性标记表
			if(!$this->cms_content_flag->set(array($value, $id), array('cid'=>$cid))) {
				E(1, '写入新内容属性出错');
			}
		}
		$data['flags'] 	= implode(",",$flags_old);
		if(!$this->cms_content->update($data)) {
			E(1, '更新内容表出错');
		}
		E(0, '更新成功！');
	}
	// 列表页推送到百度
	public function baidu(){
		$baidu 		= intval(R('baidu', 'P'));
		$id 		= intval(R('id', 'P'));
		$cid 		= intval(R('cid', 'P'));

		empty($id) && E(1, '内容ID不能为空！');
		empty($this->_cfg['bdts']) && E(1, '未设置百度推送接口，请到基本设置中填写！');
		
		$this->cms_content->table = 'cms_products';
		$data = $this->cms_content->get($id);
		
		if($baidu){
			$_thisurl = $this->_cfg['webdomain'].$this->cms_content->content_url($cid, $id, $data['alias'], $data['dateline']);
			$thisurl = array('http://'.$_thisurl);
			$res = $this->mmisc->baidup($thisurl,$this->_cfg['bdts']);
			
			!empty($res['error']) && E(1, $res['error'].':'.$res['message']);
			!empty($res['not_same_site']) && E(1, '推送的url与登记站点不符');
			!empty($res['not_valid']) && E(1, '不合法的url链接');
			
			if(!empty($res['success'])){ //推送成功
				$this->cms_content->update(array('id'=>$id,'baidu'=>1));
				E(0, '推送成功！');
			}else{
				E(1, '推送失败');
			}
		}
	}

	// 组团修改开团
	public function tuan_edit() {
		$id = intval(R('id', 'P'));

		empty($id) && E(1, '内容ID不能为空！');
		
		$this->cms_content->table = 'cms_products';
		$data = $this->cms_content->get($id);
		
		if(!empty($_POST)) {
			$data['zk_price'] 		= floatval(R('zk_price', 'P'));
			$startime				= trim(R('zk_start', 'P')) ;
			$endtime				= trim(R('zk_end', 'P')) ;

			if(empty($startime) || empty($endtime)){
				E(1, '开始时间或结束时间不正确！');
			}

			$data['zk_start'] 	= strtotime($startime.' 00:00:00');
			$data['zk_end'] 	= strtotime($endtime.' 23:59:59');
			
			if(empty($data['zk_price'])){
				E(1, '优惠价格不正确！');
			}
			
			$this->cms_content->update($data);
			E(0, '设置成功');
		}
	}
	// 删除
	public function del() {
		
		$id = (int) R('id', 'P');
		$cid = (int) R('cid', 'P');

		empty($id) && E(1, '内容ID不能为空！');
		empty($cid) && E(1, '分类ID不能为空！');

		
		$err = $this->cms_content->xdelete('products', $id, $cid);
		if($err) {
			E(1, $err);
		}else{
			E(0, '删除成功！');
		}
	}
	// 读取 (JSON)
	public function get_pro_json(){
		$id = intval(R('id', 'P'));
		
		$this->cms_content->table = 'cms_products';
		$data = $this->cms_content->get($id);
		
		if($data['zk_start']){
			$data['zk_start'] = date('Y-m-d', $data['zk_start']);
		}else{
			$data['zk_start'] = date('Y-m-d');
		}
		
		if($data['zk_end']){
			$data['zk_end'] = date('Y-m-d', $data['zk_end']);
		}else{
			$data['zk_end'] = date('Y-m-d',strtotime("+1 day"));
		}


		echo json_encode($data);
		exit;
	}

	// 移动分类
	public function batch_cid() {
		$id_arr = R('id_arr', 'P');
		$newcid = R('cid', 'P');
		empty($newcid) && E(1, '您没有选择分类！');

		if(!empty($id_arr) && is_array($id_arr)) {
			$err_num = $ok_num = 0;
			$this->cms_content->table = 'cms_products';
			$this->cms_content_flag->table = 'cms_products_flag';
			foreach($id_arr as $v) {
				//$v[0] === id
				//$v[1] === cid
				// 如果分类ID发生变化，更新分类内容数
				if($v[1] != $newcid){
					//分类改变时，别名也需要更新
					$data = $this->cms_content->get($v[0]);
					$data['cid'] = $newcid;
					if(!$this->cms_content->update($data)) {
						$err_num ++;
					}else{
						$ok_num ++ ;
						//更新alias
						if(!empty($data['alias'])){
							$this->only_alias->set($data['alias'], array('mid' => 2, 'cid' => $newcid, 'id' => $v[0]));
						}
						//更新flag
						if(!empty($data['flags'])){
							$flags_arr = explode(',', $data['flags']);
							foreach($flags_arr as $f){
								$this->cms_content_flag->set(array($f, $v[0]), array('cid'=>$newcid)) ;
							}
						}
					}
					// 旧的分类内容数减1
					$categorys_old = $this->category->read($v[1]);
					$categorys_old['count'] = max(0, $categorys_old['count']-1);
					$categorys_old['count_'.$data['status']] = max(0, $categorys_old['count_'.$data['status']]-1);
					$this->category->update($categorys_old);
				}
			}
			// 新的分类内容数增加
			$categorys = $this->category->read($newcid);
			$categorys['count'] += $ok_num;
			$categorys['count_'.$data['status']] += $ok_num;
			$this->category->update($categorys);
			
			$this->category->delete_cache();
			
			E(0, '更新成功！');
		}else{
			E(1, '参数不能为空！');
		}
	}
	// 批量删除
	public function batch_del() {
		$id_arr = R('id_arr', 'P');
		if(!empty($id_arr) && is_array($id_arr)) {
			$err_num = 0;
			foreach($id_arr as $v) {
				$err = $this->cms_content->xdelete('products', $v[0], $v[1]);
				if($err) $err_num++;
			}

			if($err_num) {
				E(1, $err_num.' 个资源删除失败！');
			}else{
				E(0, '删除成功！');
			}
		}else{
			E(1, '参数不能为空！');
		}
	}
	// 删除单个附件
	public function del_attach() {
		$aid = (int) R('aid', 'P');

		empty($aid) && E(1, 'AID不能为空！');
		$this->cms_attach->table = 'cms_attach';
		if($this->cms_attach->xdelete($aid,2)) {
			E(0, '删除成功！');
		}else{
			E(1, '删除失败！');
		}
	}
	
	// 单独保存文件
	public function save_downs() {
		$id = intval(R('id', 'P'));
		$downs = (array)R('downs', 'P');

		empty($id) && E(1, 'ID不能为空！');
		empty($downs) && E(1, '亲，您的文件忘上传了！');

		// 写入内容数据表
		$this->cms_content_data->table = 'cms_products_data';
		$data = $this->cms_content_data->read($id);
		if(empty($data)) {
			E(1, '内容不存在！');
		}
		$data['downs'] = json_encode($downs);
		if($this->cms_content_data->set($id, $data)) {
			E(0, '保存成功！');
		}else{
			E(1, '写入内容数据表出错！');
		}
	}
	// 单独保存图集
	public function save_images() {
		$id = intval(R('id', 'P'));
		$images = (array)R('images', 'P');

		empty($id) && E(1, 'ID不能为空！');
		//empty($images) && E(1, '亲，您的图集忘上传图片了！');

		// 写入内容数据表
		$this->cms_content_data->table = 'cms_products_data';
		$data = $this->cms_content_data->read($id);
		if(empty($data)) {
			E(1, '内容不存在！');
		}
		$data['images'] = json_encode($images);
		if($this->cms_content_data->set($id, $data)) {
			E(0, '保存成功！');
		}else{
			E(1, '写入内容数据表出错！');
		}
	}
	// 自动生成缩略图
	private function auto_pic($table, $uid, $id = 0) {
		$pic_arr = $this->cms_attach->find_fetch(array('id'=>$id, 'uid'=>$uid, 'isimage'=>1), array(), 0, 1);
		$pic_arr = current($pic_arr);
		$cfg = $this->runtime->xget();
		$path = 'upload/'.$table.'/'.$pic_arr['filepath'];
		$pic = image::thumb_name($path);
		$src_file = PP_PATH.$path;
		$dst_file = PP_PATH.$pic;
		if(!is_file($dst_file)) {
			image::thumb($src_file, $dst_file, $cfg['thumb_'.$table.'_w'], $cfg['thumb_'.$table.'_h'], $cfg['thumb_type'], $cfg['thumb_quality']);
		}
		return $pic;
	}
	// 获取远程图片
	private function get_remote_img($table, &$content, $mid , $uid, $cid = 0, $id = 0) {
		function_exists('set_time_limit') && set_time_limit(0);
		$cfg = $this->runtime->xget();
		$updir = 'upload/'.$table.'/';
		$_ENV['_prc_err'] = 0;
		$_ENV['_prc_arg'] = array(
			'hosts'=>array('127.0.0.1', 'localhost', $_SERVER['HTTP_HOST'], $cfg['webdomain']),
			'uid'=>$uid,
			'cid'=>$cid,
			'mid'=>$mid,
			'id'=>$id,
			'maxSize'=>10000,
			'upDir'=>PP_PATH.$updir,
			'preUri'=>$cfg['webdir'].$updir,
			'cfg'=>$cfg,
		);
		$content = preg_replace_callback('#\<img [^\>]*src=["\']((?:http|https|ftp)\://[^"\']+)["\'][^\>]*\>#iU', array($this, 'img_replace'), $content);
		unset($_ENV['_prc_arg']);
		return $_ENV['_prc_err'] ? '，但远程抓取图片失败 '.$_ENV['_prc_err'].' 张！' : '';
	}

	// 远程图片处理 (如果抓取失败则不替换)
	// $conf 用到4个参数 hosts preUri cfg upDir
	private function img_replace($mat) {
		static $uris = array();
		$uri = $mat[1];
		$conf = &$_ENV['_prc_arg'];

		// 排除重复保存相同URL图片
		if(isset($uris[$uri])) return str_replace($uri, $uris[$uri], $mat[0]);

		// 根据域名排除本站图片
		$urls = parse_url($uri);
		if(in_array($urls['host'], $conf['hosts'])) return $mat[0];

		$file = $this->cms_attach->remote_down($uri, $conf);
		if($file) {
			$uris[$uri] = $conf['preUri'].$file;
			$cfg = $conf['cfg'];

			// 是否添加水印
			if(!empty($cfg['watermark_pos'])) {
				image::watermark($conf['upDir'].$file, PP_PATH.'static/img/watermark.png', null, $cfg['watermark_pos'], $cfg['watermark_pct']);
			}

			return str_replace($uri, $uris[$uri], $mat[0]);
		}else{
			$_ENV['_prc_err']++;
			return $mat[0];
		}
	}
	// 自动保存
	public function auto_save() {
		$this->kv->set('auto_save_products_uid_'.$this->_user['uid'], $_POST) ? E(0, '自动保存成功！') : E(1, '自动保存失败！');
	}
	// 自动生成摘要
	private function auto_intro($intro, &$content) {
		if(empty($intro)) {
			$intro = preg_replace('/\s{2,}/', ' ', strip_tags($content));
			return trim(utf8::cutstr_cn($intro, 255, ''));
		}else{
			return str_replace(array("\r\n", "\r", "\n"), '<br />', strip_tags($intro));
		}
	}
}