<?php
namespace Admin\Controller;
use Think\Controller;

class ArchiveController extends Controller {
	public function addArchive() {
		$Archive           = M('archives');
		$TagRelationship   = M('tags_relationships');
		$Cate              = M('categories');
		$Tags              = M('tags');
		$data['category']  = $_POST['category'];
		$data['userid']    = $_SESSION['userid'];
		$data['showid']    = $_POST['showid'];
		$data['ispublish'] = $_GET['publish'];
		if ("" != $_POST['title']) {
			$data['title'] = $_POST['title'];
		} else {
			$data['title'] = "未命名";
		}

		$data['content']    = $_POST['editorValue'];
		$data['precontent'] = $_POST['preContent'];
		$data['writetime']  = date('Y-m-d H:i:s', time());
		$data['writeip']    = $_SERVER['REMOTE_ADDR'];
		$tag_arr            = explode(',', $_POST['tagsHide']);

		if (($i = $Archive->data($data)->add()) != 0) {
			for ($j = 0; $j < sizeof($tag_arr); $j++) {
				$tagData['aid'] = $i;
				$tagData['tid'] = $tag_arr[$j];
				$TagRelationship->data($tagData)->add();
				$Tags->where('id=' . $tag_arr[$j])->setInc('archives_sum', 1);
				$this->updateArchiveSum($data['category']);
			}
			$rtnArr = array(
				'saveTime'  => date('Y-m-d H:i:s', time()),
				'title'     => $data['title'],
				'archiveId' => $i,
				'msg'       => '您已经撰写新文章超过2分钟，保存为草稿',
				'status'    => 'success',
			);
			echo json_encode($rtnArr);
		} else {
			$rtnArr = array(
				'saveTime' => date('Y-m-d H:i:s', time()),
				'title'    => $data['title'],
				'msg'      => '保存错误',
				'status'   => 'fail',
			);
			echo json_encode($rtnArr);
		}

	}

	public function listArchive() {
		$Archive                          = M('archives');
		if (null == $_GET['type']) {$list = $Archive->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where('a.category=c.id and a.userid=' . $_SESSION['userid'])->order('a.id asc')->field('a.*,c.catename')->select();} else if ('cate' == $_GET['type']) {$list = $Archive->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where('a.category=' . $_GET['id'] . ' and a.category=c.id and a.userid=' . $_SESSION['userid'])->order('a.id asc')->field('a.*,c.catename')->select();} elseif ('tag' == $_GET['type']) {
			{ $list                           = $Archive->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'categories c')->where('a.id in (select aid from ' . C('DB_PREFIX') . 'tags_relationships where tid=' . $_GET['id'] . ') and a.category=c.id and a.userid=' . $_SESSION['userid'])->order('a.id asc')->field('a.*,c.catename')->select();}
		}
		return $list;
	}
	public function editArchive() {

		$Archive           = M('archives');
		$TagRelationship   = M('tags_relationships');
		$data['category']  = $_POST['category'];
		$data['showid']    = $_POST['showid'];
		$data['ispublish'] = $_GET['publish'];
		$data['title']     = $_POST['title'];
		$data['content']   = $_POST['editorValue'];
		if (($_POST['preContent']) != null) {
			$data['precontent'] = $_POST['preContent'];
		}

		$data['writetime'] = date('Y-m-d H:i:s', time());
		$data['writeip']   = $_SERVER['REMOTE_ADDR'];
		$tag_arr           = explode(',', $_POST['tagsHide']); //获取提交更改的tags
		$arr               = $Archive->where('id=' . $_GET['id'] . ' and userid="' . $_SESSION['userid'] . '"')->field('category')->find(); //获取修改前分类ID
		$cateID            = $arr['category']; //赋值修改前分类ID
		$arr               = $TagRelationship->where('aid=' . $_GET['id'])->field('tid')->select(); //获取修改前Tags列表
		for ($j = 0; $j < sizeof($arr); $j++) //对修改前的Tag列表进行格式化
		{
			$oldTagsArr[$j] = $arr[$j]['tid'];
		}
		if (null != $oldTagsArr && null != $tag_arr) {
			$allArray = array_unique($oldTagsArr + $tag_arr);
		}
		//修改前与修改后的Tags取并集
		elseif (null == $oldTagsArr && null != $tag_arr) {
			$allArray = $tag_arr;
		}
		if ($Archive->where('id=' . $_GET['id'] . ' and userid="' . $_SESSION['userid'] . '"')->save($data) != 0) {
			if ($cateID != $data['category']) //判断是否更新分类对应的文章数
			{
				$this->updateArchiveSum($cateID);
				$this->updateArchiveSum($data['category']);
			}
			$TagRelationship->where('aid=' . $_GET['id'])->delete(); //删除所有Tags关系
			for ($j = 0; $j < sizeof($tag_arr) - 1; $j++) //重建Tag关系
			{
				$tagData['aid'] = $_GET['id'];
				$tagData['tid'] = $tag_arr[$j];
				$TagRelationship->data($tagData)->add();
			}
			for ($j = 0; $j < sizeof($allArray); $j++) //修改Tag多对应的文章数
			{
				$this->updateTagSum($allArray[$j]);
			}
			$rtnArr['title']    = $data['title'];
			$category           = M('categories');
			$arr                = $category->where('id=' . $data['category'])->find();
			$rtnArr['category'] = $arr['catename'];
			switch ($data['showid']) {
				case -1:
					$rtnArr['showid'] = '全部可见';
					break;
				case -0:
					$rtnArr['showid'] = '好友可见';
					break;
				default:
					$rtnArr['showid'] = '自己可见';
					break;
			}
			$rtnArr['writetime'] = $data['writetime'];
			$rtnArr['writeip']   = $data['writeip'];
			switch ($data['ispublish']) {
				case 1:
					$rtnArr['ispublish'] = '草稿';
					break;

				default:
					$rtnArr['ispublish'] = '发布';
					break;
			}
			if ('json' == $_GET['type']) {
				echo json_encode($rtnArr); //该处用户ajax的快速编辑文章
			} else {
				$rtnArr = array(
					'saveTime'  => date('Y-m-d H:i:s', time()),
					'title'     => $data['title'],
					'archiveId' => $_GET['id'],
					'msg'       => '您已经撰写新文章超过2分钟，保存为草稿',
					'status'    => 'success',
				);
				echo json_encode($rtnArr);
			}

		} else {
			$rtnArr = array(
				'saveTime' => date('Y-m-d H:i:s', time()),
				'title'    => $data['title'],
				'msg'      => '保存错误',
				'status'   => 'fail',
			);
			echo json_encode($rtnArr);
		}
	}
	public function delArchive() {
		$Archive = M('archives');
		$arr     = $Archive->where('id=' . $_GET['id'] . ' AND userid=' . $_SESSION['userid'])->find();
		$title   = $arr['title'];
		$cateID  = $arr['category'];
		if ($Archive->where('id=' . $_GET['id'] . ' AND userid=' . $_SESSION['userid'])->delete() != 0) {

			$Comment            = M('comments');
			$o                  = $Comment->where('archive=' . $_GET['id'])->delete();
			$rtnArr['title']    = $title;
			$rtnArr['comments'] = $o;
			echo json_encode($rtnArr);
			$this->delTagRelationships($_GET['id']);
			$this->updateArchiveSum($cateID);
		} else {
			$this->error('删除失败');
		}

	}
	public function delMutilArchivies() {
		$arr_id = (explode(',', $_POST['idlist']));
		for ($i = 1;i < sizeof($arr_id); $i++) {
			$Archive = M('archives');
			$arr     = $Archive->where('id=' . $arr_id[$i] . ' AND userid=' . $_SESSION['userid'])->find();
			$title   = $arr['title'];
			$cateID  = $arr['category'];
			if ($Archive->where('id=' . $arr_id[$i] . ' AND userid=' . $_SESSION['userid'])->delete() != 0) {

				$Comment            = M('comments');
				$o                  = $Comment->where('archive=' . $arr_id[$i])->delete();
				$rtnArr['title']    = $title;
				$rtnArr['comments'] = $o;
				echo json_encode($rtnArr);
				$this->delTagRelationships($arr_id[$i]);
				$this->updateArchiveSum($cateID);
			} else {
				$this->error('删除失败');
			}

		}

	}
	public function getArchive($id) {
		$Archive = M('archives');
		$arr     = $Archive->where('id=' . $_GET['id'] . ' AND userid=' . $_SESSION['userid'])->find();
		return $arr;
	}
	public function updateTagSum($tid) //刷新tags表中 tag所对应的文章数目
	{
		$t = M();
		$t->execute("UPDATE `" . C('DB_PREFIX') . "tags` SET `archives_sum` =(SELECT count(*) FROM `" . C('DB_PREFIX') . "tags_relationships` as r WHERE r.tid=" . $tid . " ) WHERE `" . C('DB_PREFIX') . "tags`.`id` = " . $tid);
		//$this->show($t->getlastsql());
	}
	public function delTagRelationships($aid) //删除tagsRelationship中的记录并且更新 tag的文章数
	{
		$TagRelationship = M('tags_relationships');
		$arr             = $TagRelationship->where('aid=' . $aid)->select();
		$TagRelationship->where('aid=' . $aid)->delete();
		for ($i = 0; $i < sizeof($arr); $i++) {
			$this->updateTagSum($arr[$i]['tid']);
		}
	}
	public function updateArchiveSum($cateID) {
		$t = M();
		$t->execute("UPDATE `" . C('DB_PREFIX') . "categories` SET `archives_sum` =(SELECT count(*) FROM `" . C('DB_PREFIX') . "archives` as a WHERE a.category=" . $cateID . " ) WHERE `" . C('DB_PREFIX') . "categories`.`id` = " . $cateID);

	}
	public function getArchiveSum() {
		$Archive = M('archives');
		$arr     = $Archive->where('userid=' . $_SESSION['userid'])->field('COUNT("id")')->select();
		return $arr[0]['COUNT("id")'];
	}
	public function getLastArchive($top = 3) {
		$Archive = M('archives');
		$arr     = $Archive->where('userid=' . $_SESSION['userid'])->order('id desc')->limit($top)->select();
		return $arr;
	}
}