<?php
// +----------------------------------------------------------------------
// | 奇乐自媒体内容管理系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com
// +----------------------------------------------------------------------
// | 官方论坛：http://bbs.qilecms.com
// +----------------------------------------------------------------------
// | Author:奇乐网络
// +----------------------------------------------------------------------
// | 版权说明：本产品为免费版，使用请保留底部版权
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\controller;
use think\Db;
class Message extends Base
{
	public function index(){
      $alias = '';        //需要别名时写别名，不需要的时候留空 
      $defaultOrder = 'create_time desc';  //默认排序
//消息类型 
          $param = $this->request->param();
           if($param['type'] >= '0' ){
             $type = $param['type'];
              $defaultWhere ='type = '.$param['type'];  //默认wher
        }else{
             $type  = ''; 
             $defaultWhere = '';
        }

     $this->assign('type',$type);

    //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where   = $SearchFormData['where'];
      $order   = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];

//组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'title', //字段名
                  'name'    =>'消息标题', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],
                  [
                  'field'   =>'from_username',
                  'name'    =>'发信人',
                  'alias'   => $alias,
                  ],
                  [
                  'field'   =>'to_username',
                  'name'    =>'收信人',
                  'alias'   => $alias,
                  ]
     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'创建时间',  //标签显示名称
                  'field'        =>'create_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ],

              ];
//单个字段筛选
    $customSingleField =[
                            [
                             'name'=>'状态',
                             'field' => 'is_read', 
                             'data'  => [ 0 =>'未读',1=>'已读'],
                             'alias'=>$alias,
                            ]
                       ]; 
// 组件字段组筛选
    $groupData = [
               
              ];
     $orderData   = [
               
               ];  

     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);


     $lists = DB::name('message')->where($where)->order($order)->paginate($pageNum);
     $list = $lists->toArray()['data'];

     foreach($list as $k=>$v){
          $m['uid'] = $v['from_uid'];
          $fromUser = model('user')->infoData($m);
          $list[$k]['from_username'] = $fromUser['username'];
          $map2['uid'] = $v['to_uid'];
          $toUser = model('user')->infoData($map2);
          $list[$k]['to_username'] = $toUser['username'];

     }
     $page = $lists->render();
     $this->assign('page', $page);
     $this->assign('list', $list);

     return $this->fetch();
	}
//增加
  public function add(){
    $param = $this->request->param(); 
    if($this->request->isPost()){   

        //验证
        $rule =[
          'title'=>'require',
          'content'=>'require',
        ];
        $msg= [
         'title.require' =>'消息标题不能为空',
         'content.require' =>'消息内容不能为空',
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }
         //表单数据
          $data['title'] = $param['title'];
          $data['type'] = $param['type'];
          $data['content'] = $param['content'];
		      $data['create_time'] = time();
          $data['from_uid'] = $param['type'];
          if($param['type'] ==1){
          	//群发通知
          	  $data['remark'] = '系统消息';
              //通知用户组识别
              if(is_array($param['level_id'])){
                   $data['level_id'] = implode(',',$param['level_id']);
                   $where = "level_id IN (".$data['level_id'].")";
                   $UserLevel = model('UserLevel')->where($where)->select();
                   $arr =[];
                   foreach($UserLevel as $v){
                       array_push($arr,$v['level_name']); 
                   }
                   $userGroupName = implode(',',$arr);
              }else{
                   $data['level_id']  = $param['level_id'];
                   $where['level_id'] = $data['level_id'];
                   $UserLevel = model('UserLevel')->where($where)->find();
                   $userGroupName= $UserLevel['level_name'];
                   
              }
               $data['remark'] = ''.$userGroupName.'';
               model('message')->addData($data);
			         return success_json('通知群发成功'); 
          }else{
          	//发私信
            
              $arrs = explode("\n",$param['to_username']);
              $arr = [];
              foreach($arrs as $k=>$v){
                 $where['username'] = trim($v);
                 $res = model('user')->infoData($where);
                 if(empty($res)){
                  return error_json('用户名'.trim($v).'不存在');
                 }
                 $arr[] = trim($v);
              }

              $data['from_uid'] = 0;   
              $map[] = ['username','IN',$arr];
              $map[] = ['status','=',1];
              $users = model('user')->listData($map);

              foreach($users as $user){
              	  $data['to_uid'] = $user['uid'];
                  model('message')->addData($data);
			            
              }         
               return success_json('私信发送成功'); 
          }

        


 
   }else{
   	     $UserLevel = model('UserLevel')->getUserLevelList();
   	     $this->assign('UserLevel',$UserLevel);
         return $this->fetch();
   }      
  }
  public function edit(){
    $param = $this->request->param();
    if($this->request->isPost()){

        //验证
        $rule =[
          'title'=>'require',
          'content'=>'require',
        ];
        $msg= [
         'title.require' =>'消息标题不能为空',
         'content.require' =>'消息标题不能为空',
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }
    
        //表单数据       
          $data['title'] = $param['title'];
          $data['level_id'] = $param['level_id'];
          $data['type'] = $param['type'];
          $data['content'] = $param['content'];
          $data['status'] = !empty($param['status'])?1:0;
          $where['id'] = $param['id'];
          $res = model('message')->editData($data,$where);
          return success_json('编辑成功'); 
    }else{
         $rule = model('message')->getRuleInfoById($param['id']);
         $this->assign('rule',$rule);
         return $this->fetch();


    }  
  }
  public function del(){
      $param = $this->request->param();
     if(!$param['mid']){  return error_json('请求参数错误');    }

     $res= model('message')->delData("mid",$param['mid']);
       if($res){
         return success_json('删除成功');
       }else{
         return error_json($res);
       }
    }
      

}