<?php
namespace admin\Controller;
use Think\Controller;
class MsgController extends CommonController{
	public function lists(){

		$key = I('request.key','','trim');
		if ($key)
		{
			$key_type = I('request.key_type',0,'intval');
			if ($key_type=='1')
			{
				$map['content'] = array('like','%'.$key.'%');
			}
			if ($key_type=='2')
			{
				$map['uid'] = intval($key);
			}
		}
		$sort=' id desc';
		$list=D('Msg')->get_list($map,true,$sort,10);
		$this->assign('lists',$list);
		$this->display();
	}
	
	public function add(){
		if(IS_POST)
		{
				$data = D("Msg");
				if (!$array=$data->create()){
					$this->error($data->getError());
				}
				else
				{
					$array['uid'] = session('uu.uid');
					$msgid=$data->add($array);
				 	if ($array['receiver']=='2')//指定会员
					{
						$uname=explode("\r\n",$array['receiver_by']);
						foreach ($uname as $u)
						{
							$user=D('User')->get_user_one($u,false,3);
							if (empty($user)){
							continue;
							}
							D('UserMsg')->update_user_msg($user['uid']);
						}
					}
					$this->success('保存完成',RU('msg/lists')); 	
				}
		}
		else
		{
		 	$this->display();
		}
	}
	public function edit(){
		if(IS_POST)
		{
				$data = D("Msg");
				if (!$array=$data->create()){
					$this->error($data->getError());
				}
				else
				{
					$data->save();
					if ($array['receiver']=='2')//指定会员
					{
						$uname=explode("\r\n",$array['receiver_by']);
						if (!empty($uname))
						{
							foreach($uname as $u)
							{
								$user=D('User')->get_user_one($u,false,3);
								if (empty($user)){
								continue;
								}
								D('UserMsg')->update_user_msg($user['uid']);
							}
						}
					}
					$this->success('保存完成');				
				}
		}
		else
		{
			$id=I('get.id','','intval');
			if ($id)
			{
				$data = M("Msg");
				$map['id']=$id;
				$show=$data->where($map)->find();
				$this->assign('show',$show);
				$this->display();
			}
			else
			{
			$this->error('非法请求');
			}
		}
	}
	
	public function delete(){
	
		$ids = I('request.id');
		$ids = is_array($ids)?implode(",",$ids):$ids;
		if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/",$ids))
		{
			
			$map['msg_id']  = array('IN',$ids);
			$map['read']  = 0;
			M("UserMsg")->where($map)->delete();
			$s=M("Msg")->delete($ids);
			$this->success("成功删除{$s}条数据");
		}
		else
		{
		$this->error('请选择要删除的信息！');
		}
	
 	}
}
?>