<?php
namespace app\bsadmin\controller;
use think\facade\View;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Validate;
use app\bsadmin\model\Config as ConfigModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\model\PushMessage as PushMessageModel;
use app\common\model\PushMessageContent as PushMessageContentModel;
use app\common\model\PushQueue as PushQueueModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\User as UserModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserWx as UserWxModel;
use XYCms\Sms;
use XYCms\Email;
class Message extends Base
{
	public function index()
	{
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['key']) {
                switch($G['search_type']){
                    case 'uid':
                        $where[]=['msg.uid','=',$G['key']];
                        break;
                }
            }
            if ($G['status']!='all') {
                $where[]=['msg.status','=',$G['status']];
            }
            if ($G['is_read']!='all') {
                $where[]=['msg.is_read','=',$G['is_read']];
            }
            $Data=PushMessageModel::alias('msg')->where($where)
                ->join('user_info user_info','user_info.uid = msg.uid')
                ->field('msg.*,user_info.nickname,user_info.headimg')
                ->order('msg.id desc')->paginate($G['pageSize'])->each(function($v){
                    $v->delete_time=$v['delete_time']?date('Y-m-d H:i',$v['delete_time']):'';
                    $v->nickname=base64_decode($v['nickname']);
                    $v->headimg=config('web.imgurl').$v['headimg'];
                    $v->content='';
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
        	$msgType=StatusAliasModel::getSelect('message/type');
        	View::assign('msgType',$msgType);
            return View::fetch();
        }
	}
	public function queueList()
	{
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['status']!='all') {
                $where[]=['msg.status','=',$G['status']];
            }
            $Data=PushQueueModel::where($where)
                ->withoutField('content')
                ->order('status asc,id desc')->paginate($G['pageSize'])->each(function($v){
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
	}
    public function pushList()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['key']) {
                switch($G['search_type']){
                    case 'uid':
                        $where[]=['msg.uid','=',$G['key']];
                        break;
                }
            }
            if ($G['status']!='all') {
                $where[]=['msg.status','=',$G['status']];
            }
            if ($G['type']!='all') {
                $where[]=['msg.type','=',$G['type']];
            }
            $Data=PushTaskModel::alias('msg')->where($where)
                ->join('user_info user_info','user_info.uid = msg.uid','LEFT')
                ->field('msg.*,user_info.nickname,user_info.headimg')
                ->order('msg.id desc')->paginate($G['pageSize'])->each(function($v){
                    $v->nickname=base64_decode($v['nickname']);
                    $v->headimg=$v['headimg']?config('web.imgurl').$v['headimg']:'';
                    $v->data=json_decode($v['data'],true);
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            $msgType=StatusAliasModel::getSelect('message/type');
            View::assign('msgType',$msgType);
            return View::fetch();
        }
    }
	public function sendMessage()
	{
        if (request()->isPost()) {
            $D=request()->post();
            $rule =   [
                'crowd'             => 'require',
                'title'             => 'require',
                'desc'              => 'length:0,50',
                'content'           => 'require',
            ];
            $msg  =   [
                'crowd.require'     => '请选择接收人群',
                'title.require'     => '请输入标题',
                'desc.length'       => '描述请控制在50个字以内',
                'content.require'   => '请输入内容',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            if ($D['crowd']=='appoint') {
                $TaskList=[];
                $msgData=json_encode(['title'=>$D['title'],'desc'=>$D['desc'],'content'=>$D['content']],JSON_UNESCAPED_UNICODE);
                foreach ($D['user_list'] as $k => $v) {
                    $TaskList[]=[
                        'uid'       =>  $v,
                        'client'    =>  $D['client']?implode(',', $D['client']):null,
                        'event'     =>  'sendSiteMsg',
                        'data'      =>  $msgData
                    ];
                }
                $PushTaskModel=new PushTaskModel;
                if ($PushTaskModel->saveAll($TaskList)) {
                    return $this->ajaxReturn('发送成功');
                }else{
                    return $this->ajaxReturn('保存失败，请重试',-100);
                }
            }else{
                $sum=0;
                switch ($D['crowd']) {
                    case 'all':
                        $sum=UserModel::where(['status'=>1])->count();
                        break;
                    case 'company':
                        $sum=UserInfoModel::where(['role_type'=>1])->count();
                        break;
                    case 'personal':
                        $sum=UserInfoModel::where(['role_type'=>0])->count();
                        break;
                    case 'mp':
                        $sum=UserWxModel::where(['subscribe'=>1])->whereNotNull('wx_openid')->count();
                        break;
                    case 'mobile':
                        $sum=UserModel::where(['status'=>1])->whereNotNull('mobile')->count();
                        break;
                    case 'email':
                        $sum=UserModel::where(['status'=>1])->whereNotNull('email')->count();
                        break;
                }
                $PushQueueModel=new PushQueueModel;
                $PushQueueModel->crowd      =   $D['crowd'];
                $PushQueueModel->client     =   $D['client']?implode(',', $D['client']):null;
                $PushQueueModel->title      =   $D['title'];
                $PushQueueModel->desc       =   $D['desc'];
                $PushQueueModel->content    =   $D['content'];
                $PushQueueModel->sum        =   $sum;
                if ($PushQueueModel->save()) {
                    return $this->ajaxReturn('创建队列成功');
                }else{
                    return $this->ajaxReturn('保存失败，请重试',-100);
                }
            }
        }else{
            return View::fetch();
        }
	}
	public function getMessageContent($id)
	{
		$Find=PushMessageContentModel::where(['mid'=>$id])->find();
		if ($Find) {
            return $this->ajaxReturn('',0,$Find);
		}else{
            return $this->ajaxReturn('消息不存在',-100);
		}
	}
	public function setStatus($id,$status)
	{
		$Find=PushMessageModel::where(['id'=>$id])->find();
		if ($Find) {
			$Find->status=$status;
			if ($Find->save()) {
	            return $this->ajaxReturn();
			}else{
            	return $this->ajaxReturn('保存失败，请重试',-100);
			}
		}else{
            return $this->ajaxReturn('消息不存在',-100);
		}
	}
	public function setIsRead($id,$is_read)
	{
		$Find=PushMessageModel::where(['id'=>$id])->find();
		if ($Find) {
			$Find->is_read=$is_read;
			if ($Find->save()) {
	            return $this->ajaxReturn();
			}else{
            	return $this->ajaxReturn('保存失败，请重试',-100);
			}
		}else{
            return $this->ajaxReturn('消息不存在',-100);
		}
	}
    public function setMessage()
    {
        $Data=ConfigModel::getList([['ctype','in',['xycms_message','xy_getui','xy_email']]]);
        View::assign('Data',$Data);
        View::assign('ctype','xycms_message');
        return View::fetch('setting/message');
    }
    public function sendSmsMessage()
    {
        if (request()->isPost()) {
            $D=request()->post();
            $rule =   [
                'mobile'            => 'require|mobile',
                'content'           => 'require',
            ];
            $msg  =   [
                'mobile.require'    => '请输入接收人',
                'mobile.mobile'     => '手机号错误',
                'content.require'   => '请输入内容',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            try {
                $Sms=new Sms;
                $Sms->phone=$D['mobile'];
                $Sms->msg=$D['content'];
                $ret=$Sms->sendSms();
                return $this->ajaxReturn('发送成功');
            } catch (\think\Exception $e) {
                return $this->ajaxReturn($e->getMessage(),-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function sendEmail()
    {
        if (request()->isPost()) {
            $D=request()->post();
            $rule =   [
                'email'             => 'require|email',
                'title'             => 'require',
                'content'           => 'require',
            ];
            $msg  =   [
                'email.require'    => '请输入接收人',
                'email.email'     => '邮箱错误',
                'title.require'    => '请输入标题',
                'content.require'   => '请输入内容',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            try {
                $Email=new Email;
                $name=config('web.name');
                $ret=$Email->init($D['email'],$name,$D['title'],$D['content']);
                if ($ret===true) {
                    return $this->ajaxReturn('发送成功');
                }else{
                    return $this->ajaxReturn($ret,-100);
                }
            } catch (\think\Exception $e) {
                return $this->ajaxReturn($e->getMessage(),-100);
            }
        }else{
            return View::fetch();
        }
    }
}
