<?php 
namespace Common\Model;
use Think\Model;
class UserMsgModel extends Model
{
	//更新会员系统消息，如果没有则插入
	public function update_user_msg($uid='',$systype='1')
	{
		$map['systype']=intval($systype);
		$msglist=D('Msg')->where($map)->select();
		foreach($msglist as $msg)
		{
			
			if ($this->chenk_user_msg_empty($msg['id'],$uid))
			{
				$data['msg_id']=$msg['id'];
				$data['send_uid']=$msg['uid'];
				$data['to_uid']=$uid;
				$data['addtime']=$msg['addtime'];
				$data['msg']=$msg['msg'];
				$this->add($data);
			}
		}
	}
	//检查系统消息是否存在
	public function chenk_user_msg_empty($msg_id='',$to_uid='')
	{
		$map['msg_id']=intval($msg_id);
		$map['to_uid']=intval($to_uid);
		$info=$this->where($map)->find();
		if (empty($info))
		{
			return true;
		}
		return false;
	}
	//获取消息
	public function get_user_msg_one($id='')
	{
		$map['id']=intval($id);
		$info=$this->where($map)->find();
		$info['msg']=uu_strip_tags($info['msg']);
		$info['addtime_str']=daterange($info['addtime']);
		$info['sysimg']=$this->get_sysimg();
		return $info;
	}
	//获取列表
	public function get_list($map='',$page=false,$num='')
	{
		$limit=$num?$num:10;
		$sort="`read` asc,id DESC";
		if ($page)
		{
		$count      = $this->where($map)->count();
		$Page		= pager($count,$limit);
		$limit      = $Page->firstRow.','.$Page->listRows;
		$page_str   = $Page->fshow();
		}
		$result = $this->where($map)->order($sort)->limit($limit)->select();
		foreach ($result as $key => $v){
				$v['url']=$this->view_url($v['id']);
				$v['addtime_str']=daterange($v['addtime']);
				$v['sysimg']=$this->get_sysimg();
				$list[]=$v;
			}
		$return['list']=$list;
		$return['count']=$page?$count:count($list);
		$return['page']=$page_str;
		//print_r($return);
		return $return;
	}
	//设置消息已读未读
	public function set_msg_read($id='',$uid='',$read='')
	{
		$map['id']=intval($id);
		$msg=$this->get_user_msg_one($id);
		$data['read']=$msg['read']?0:1;
		if ($read)
		{
		$data['read']=intval($read);
		}
		$this->where($map)->save($data);
	}
	//系统消息图片
	public function get_sysimg()
	{
		return __ROOT__.'/'.C('UU_IMG_AVATAR_DIR').'sys.jpg';
	}
	//获取详细页的URL
	public function view_url($id)
	{
		return RU('user/msg_view',array('id'=>$id));
	}
}
?>