<?php
// 公告模型
class AnnouncementModel extends Model {
	public function save() {
		$info = $_POST['info'];
		$info['id'] = intval($info['id']);
		if (empty($info['id'])) {
			$info['id'] = $this -> getId('id');
			$info['userid'] = get_cookie('userid');
			$info['username'] = get_cookie('username');
			$info['addtime'] = TIME;
			$isAdd = true;
		} else {
			$isAdd = false;
			if (isset($info['upaddtime'])) $info['addtime'] = TIME;
		}
		$info['starttime'] = Func :: timeStamp($info['starttime']);
		$info['endtime'] = Func :: timeStamp($info['endtime']);
		// 判断标题有效性
		$info['title'] = trim($info['title']);
		if (empty($info['title'])) {
			$this -> error = L('TITLE_EMPTY');
			return false;
		}
		if (trim($info['content']) == '') {
			$this -> error = L('CONTENT_EMPTY');
			return false;
		}
		$attachmentObj = M('attachment', '', $this -> moduleName);
		// 远程上传
		if (R('saveremote')) {
			$info['content'] = $attachmentObj -> remote($info['content']);
		}
		// 获取已上传附件
		$attachments = $attachmentObj -> getAttachments($info['content']);
		$this -> create($info);
		$rs = $isAdd?$this -> add():$this -> update();
		if ($rs) {
			$attachmentObj -> setContentId($attachments, $info['id']);
			$attachmentObj -> check($attachments, $info['id']);
			$rs = $info['id'];
		}
		return $rs;
	}
	// 删除
	public function del() {
		$selids = R('selids');
		if (!empty($selids)) {
			$where = strstr($selids, ',')?"id IN ($selids)":"id=$selids";
			if (!$this -> where($where) -> delete()) {
				$this -> error = L('OPERATE_FAIL');
				$rs = false;
			} else {
				$obj = M('attachment', '', $this -> moduleName);
				$obj -> del(array("module=" . $this -> moduleName, strstr($selids, ',')?"contentid IN ($selids)":"contentid=$selids"));
				$rs = true;
			}
		} else {
			$this -> error = L('NOPARAM');
			$rs = false;
		}
		return $rs;
	}
	public function listInfo($param = array()) {
		$page = $this -> param('page', $param);
		$pageSize = $this -> param('num', $param, 8);
		$where = array('starttime<=' . TIME, array('endtime>=' . TIME, 'endtime=0', 'logic' => 'OR'));
		$data = $this -> getList($page, $pageSize, $where, 'starttime DESC');
		if (is_array($data)) {
			if ($pageSize === 1) {
				$data['url'] = Url :: getContentUrl('announcement', $data['id']);
			} else {
				foreach($data as $k => $v) {
					$v['url'] = Url :: getContentUrl('announcement', $v['id']);
					$data[$k] = $v;
				}
			}
		}
		return $data;
	}
}
