<?php 
namespace Common\Model;
use Think\Model;
class UserPmsModel extends Model
{
	public function add_pms($data='')
	{
		$send_uid=$data['send_uid'];
		$to_uid=$data['to_uid'];
		$msg=$data['msg'];
		$alias=$this->get_pms_alias($send_uid,$to_uid);
		$pms=$this->get_pms_one($alias,2);
		$data['alias']=$alias;
		$data['send_uid']=intval($send_uid);
		$data['to_uid']=intval($to_uid);
		if (empty($pms))
		{
			$pmsid=$this->add($data);
		}
		$data['pid']=$pmsid?$pmsid:$pms['id'];
		$data['msg']=$msg;
		$data['addtime']=time();
		M('UserPmsChat')->add($data);
		//设置收件人未读
		$read['id']=$data['pid'];
		$read['to_read']=0;
		$this->save($read);
	}
	//获取消息
	public function get_list($map='',$page=false,$num='',$myuid='')
	{
		$limit=$num?$num:10;
		$sort="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']);
				if ($v['send_uid']==$myuid){
				$v['user']=D('User')->get_user_one($v['to_uid'],true,1);
				}else{
				$v['user']=D('User')->get_user_one($v['send_uid'],true,1);
				}				
				$v['reply']=D('UserPmsChat')->get_one($v['id']);
				$v['addtime_str']=daterange($v['reply']['addtime']);
				$list[]=$v;
			}
		$return['list']=$list;
		$return['count']=$page?$count:count($list);
		$return['page']=$page_str;
		//print_r($return);
		return $return;
	}
	//设置消息已读未读
	public function set_pms_read($id='',$myuid='',$read='')
	{
		$map['id']=intval($id);
		$pms=$this->get_pms_one($id);
		if ($pms['send_uid']==$myuid)
		{
				$data['send_read']=intval($read);
				if ($read==='')
				{
				$data['send_read']=$pms['send_read']?0:1;
				}
		}
		else
		{
				$data['to_read']=intval($read);
				if ($read==='')
				{
				$data['to_read']=$pms['to_read']?0:1;
				}
		}
		$this->where($map)->save($data);
	}
	//设置会话显示
	public function set_pms_display($id='')
	{
		$data['id']=intval($id);
		$data['send_display']=1;
		$data['to_display']=1;
		$this->save($data);
	}
	//
	public function get_pms_one($v='',$type='1')
	{
		if ($type=='1')
		{
		$map['id']=intval($v);
		}
		if ($type=='2')
		{
		$map['alias']=trim($v);
		}
		$pms=$this->where($map)->find();
		return $pms;
	}
	//获取回话组别名
	public function get_pms_alias($send_uid='',$to_uid='')
	{
		$send_uid=intval($send_uid);
		$to_uid=intval($to_uid);
		$alias="{$send_uid}|{$to_uid}";
		if ($send_uid>$to_uid)
		{
		$alias="{$to_uid}|{$send_uid}";
		}
		return $alias;
		
	}
	//获取详细页的URL
	public function view_url($id)
	{
		return RU('user/pms_view',array('id'=>$id));
	}
}
?>