<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2017/11/22
 * Time: 19:24
 */

namespace App\Http\Controllers;

use ClassPreloader\Config;
use function GuzzleHttp\Psr7\str;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use RedisDB;
use Carbon\Carbon;

function CheckActive($menus, &$arr, $url)
{
    for ($i = 0; $i < count($menus); $i++) {
        $menu = $menus[$i];
        array_push($arr, $i);

        if (isset($menu->href) && ($menu->href == $url || ($menu->href == '/' && $url == '//')))
            return true;
        if (isset($menu->childs) && count($menu->childs) > 0) {
            $ret = CheckActive($menu->childs, $arr, $url);
            if ($ret)
                return $ret;
        }
        array_pop($arr);
    }
    return false;
}

function createMenuReal($menus, $active, $level)
{
    $subclass = ($level == 0) ? 'nav-second-level' : 'nav-third-level';

    $ret = '';
    for ($ii = 0; $ii < ($level == 0 ? 1 : 2); $ii++) {
        for ($i = 0; $i < count($menus); $i++) {
            $menu = $menus[$i];
            $act = (count($active) > $level && $active[$level] == $i) ? true : false;
            $actclass = $act ? ' class="active"' : '';
            $actmenu = $act ? ' in' : '';

            if (isset($menu->childs) && count($menu->childs) > 0) {
                if ($ii != 0 && $level > 0)
                    continue;
                $ret .= '<li' . $actclass . '><a><i class="'
                    . $menu->class . '"></i><span class="nav-label">'
                    . $menu->title . '</span><span class="fa arrow"></span></a>'
                    . '<ul class="nav ' . $subclass . ' collapse' . $actmenu . '">'
                    . createMenuReal($menu->childs, $act ? $active : [], $level + 1)
                    . '</ul></li>';
            } else {
                if ($ii != 1 && $level > 0)
                    continue;
                $ret .= '<li' . $actclass . '><a href="' . $menu->href . '"><i class="' .
                    $menu->class . '"></i><span class="nav-label">' . $menu->title . '</span></a></li>';
            }
        }
    }

    return $ret;
}

function createMenu($menus, $url)
{
    $actives = [];
    $ret = CheckActive($menus, $actives, $url);
    if (!$ret)
        $actives = [];
    return createMenuReal($menus, $actives, 0);
}

function Crumbs($menus, $uri)
{
    $actives = [];
    CheckActive($menus, $actives, $uri);
    $ret = '';
    foreach ($actives as $k => $v) {
        if ($k == count($actives) - 1) {
            $ret .= '<li class="active"><a>' . $menus[$actives[0]]->childs[$actives[1]]->title . '</a></li>';
        } else {
            $ret .= '<li><a href="#">' . $menus[$actives[0]]->title . '</a></li>';
        }
    }
    return $ret;
}

class MessageController extends Controller
{
    private function templateData(Request $request, $id, $viewid)
    {
        $uri = '/' . $request->path();
        $paths = [["title" => "消息管理系统", "href" => '/database/']];
        $username = $request->user->email;
        $useremail = $request->user->email;
        $menuconfig = DB::table('config')->where('config_id', $this->getConfigId())->first();
        $menus = [];
        if ($menuconfig && !($menus = json_decode($menuconfig->config_data)))
            $menus = [];


        $referer = $this->get_referer($request);
        $data = [
            'id' => $id,
            'title' => '消息管理系统',
            'header' => $request->user->header,
            'uri' => $uri,
            'paths' => $paths,
            'username' => $username,
            'useremail' => $useremail,
            'menus' => $menus,
            'options' => '[]',
            'referer' => $referer,
        ];
        return view($viewid, $data);
    }

    public function index(Request $request)
    {
        $uri = '/' . $request->path();
        $paths = [["title" => "首页", "href" => '/database/']];
        $username = $request->user->email;
        $useremail = $request->user->email;
        $menuconfig = DB::table('config')->where('config_id', $this->getConfigId())->first();
        $menus = [];
        if ($menuconfig && !($menus = json_decode($menuconfig->config_data)))
            $menus = [];


        $referer = $this->get_referer($request);
        $data = [
            'header' => $request->user->header,
            'uri' => $uri,
            'paths' => $paths,
            'username' => $username,
            'useremail' => $useremail,
            'menus' => $menus,
            'options' => '[]',
            'referer' => $referer,
        ];
        return view('index', $data);
    }

    public function message(Request $request, $id = 0)
    {
        return $this->templateData($request, $id, 'message');
    }

    public function info(Request $request, $id = 0)
    {
        return $this->$id($request, $id, 'common');
    }

    public function get_referer($request)
    {
        // echo $request->headers->get('referer') . "\n";
        $pos = strpos($request->headers->get('referer'), 'info');
        $referer = 0;
        if ($pos === false)
            $referer = 0;
        else
            $referer = 1;
        // echo "referer:" . $referer . "\n";
        return $referer;
    }


    //-------------------------------模块-------------------------------

    // 消息模板列表
    private function templatelist(Request $request, $id, $viewid)
    {
        Csrf($request);
        //获取权限
        $perms_arr = ['template_check','template_create','template_edit'];
        $res_perm = $this->getUserPerms($request,$perms_arr);
        $template_check = $res_perm['template_check'];
        $template_create = $res_perm['template_create'];
        $template_edit = $res_perm['template_edit'];

//        $template_check = $template_create = $template_edit =true;

        //搜索
        $search_desc = $request->input('search_desc');
        $search_channel = $request->input('search_channel');
        $search_keyword = $request->input('search_keyword');

        $cnt = DB::connection('message');
        //自动发送模板数据
        //1.首次进页面无搜索条件
        if($search_desc==null && $search_channel==null && $search_keyword == null)
        {
            $info = $cnt->table('lie_msg_tpl')->where("status",'0')->where('source_type','1')->orderBy('tpl_id','desc')->paginate(20);
            $search_channel = 0;
            $search_desc = '';
        }else//2.有搜索条件
        {
            //渠道里没有0,所以如果没选,将此条件剔除掉
            if(0==$search_channel)
            {
                $info = $cnt->table('lie_msg_tpl')->where('source_type','1')->where("status",'0')->where('ex_str','like',"%$search_desc%")->where('description','like',"%$search_keyword%")->orderBy('tpl_id','desc')->paginate(20);
            }else
            {
                $info = $cnt->table('lie_msg_tpl')->where('source_type','1')->where("status",'0')->where('channels','like',"%$search_channel%")->where('description','like',"%$search_keyword%")->where('ex_str','like',"%$search_desc%")->orderBy('tpl_id','desc')->paginate(20);
            }
        }

        //构建model
        foreach ($info as $tpl)
        {
            //将消息渠道从 数字字符串转化为汉字字符串 用于用户展示
            $tpl->show_channels_str = $this->changeNumberStrToChineseStr(['站内信','短信','邮箱','微信通知','钉钉消息'],$tpl->channels);

            //取出渠道站内信和邮件title 放到info中
            $inner_title = $cnt->table('lie_msg_channel_tpl')->select('title')
                ->where('tpl_id',$tpl->tpl_id)->where('channel_type',1)->first();
            $email_title = $cnt->table('lie_msg_channel_tpl')->select('title')
                ->where('tpl_id',$tpl->tpl_id)->where('channel_type',3)->first();
            $tpl->title = '-';
            if(!empty($inner_title->title))
            {
                $tpl->title = $inner_title->title;
            }else if(!empty($email_title->title))
            {
                $tpl->title = $email_title->title;
            }
        }
        $msg_channels=[
            '全部',
            '站内信',
            '短信',
            '邮件',
            '微信通知',
            '钉钉通知'
        ];

        $data=[
            'title'=>'asd',
            'id'=>$id,
            'info'=>$info,
            'msg_channels'=>$msg_channels,
            'search_desc'=>$search_desc,
            'search_channel'=>$search_channel,
            'search_keyword'=>$search_keyword,

            'template_check'=>$template_check,
            'template_create'=>$template_create,
            'template_edit'=>$template_edit
        ];
        return view($viewid, $data);
    }

    // 人工发送历史消息列表
    private function manualhistorylist(Request $request, $id, $viewid)
    {
        Csrf($request);
        //获取权限
        $perms_arr = ['manualhistorylist_check','manualmessage_edit','manualmessage_send'];
        $res_perm = $this->getUserPerms($request,$perms_arr);
        $manualhistorylist_check = $res_perm['manualhistorylist_check'];
        $manualmessage_edit = $res_perm['manualmessage_edit'];
        $manualmessage_send = $res_perm['manualmessage_send'];

        $conditions = $request->input();
        if(!empty($conditions['page']) && !empty($conditions['limit'])){
            $items = DB::connection('message')->table('lie_msg_log as ml')
                ->leftjoin('lie_msg_tpl as mt','ml.tpl_id','=','mt.tpl_id')
                ->select('ml.log_id','ml.title','mt.description','ml.channel_type','ml.actual_send_time','ml.obj_user')
                ->where(function($query) use($conditions){
                    if(!empty($conditions['msg_tpl_description']))
                    {
                        $query->where('mt.description','like','%'.$conditions['msg_tpl_description'].'%');
                    }
                    if(!empty($conditions['start_time']))
                    {
                        $query->where('ml.actual_send_time','>=',strtotime($conditions['start_time']));
                    }
                    if(!empty($conditions['end_time']))
                    {
                        $query->where('ml.actual_send_time','<=',strtotime($conditions['end_time'])+86400);
                    }
                    if(!empty($conditions['msg_channels']))
                    {
                        $query->where('ml.channel_type',$conditions['msg_channels']);
                    }
                })
                ->groupBy('mt.tpl_id')
                ->orderBy('ml.log_id','desc')
                ->paginate($conditions['limit'],['*'],'page',$conditions['page'])->toArray();

            foreach ($items['data'] as &$item){
                $item = objectToArray($item);
                $item['actual_send_time_str'] = !empty($item['actual_send_time'])?Carbon::createFromTimestamp(strval($item['actual_send_time']))->toDateTimeString():'';
                $item['channel_type_str'] = Config('msgconfig.msg_channels')[$item['channel_type']];
            }
            unset($item);
            return json_encode(['code'=>0,'count'=>$items['total'],'msg'=>'success','data'=>$items['data']]);
        }

        $data=[
            'title'=>'asd',
            'id'=>$id,
            'info'=>[],

            'manualhistorylist_check'=>$manualhistorylist_check,
            'manualmessage_edit'=>$manualmessage_edit,
            'manualmessage_send'=>$manualmessage_send
        ];

        return view($viewid, $data);
    }

    // 所有历史消息
    private function allhistorylist(Request $request, $id, $viewid)
    {
        Csrf($request);
        $perms_arr = ['allhistorylist_check'];
        $res_perm = $this->getUserPerms($request,$perms_arr);
        $allhistorylist_check = $res_perm['allhistorylist_check'];

        $conditions = $request->input();
        if(!empty($conditions['page']) && !empty($conditions['limit'])){
            $items = DB::connection('message')->table('lie_msg_log as ml')
                ->leftjoin('lie_msg_tpl as mt','ml.tpl_id','=','mt.tpl_id')
                ->select('ml.log_id','ml.status','ml.obj_user','ml.source_type','ml.tpl_id','ml.channel_type','ml.create_time','ml.expect_send_time','ml.actual_send_time','ml.title','ml.content','ml.wechat_tpl_id','mt.ex_str')
                ->where(function($query) use($conditions){
                    if(!empty($conditions['msg_tpl_desc']))
                    {
                        $query->where('mt.ex_str','like','%'.$conditions['msg_tpl_desc'].'%');
                    }
                    if(!empty($conditions['start_time']))
                    {
                        $query->where('ml.actual_send_time','>=',strtotime($conditions['start_time']));
                    }
                    if(!empty($conditions['end_time']))
                    {
                        $query->where('ml.actual_send_time','<=',strtotime($conditions['end_time'])+86400);
                    }
                    if(!empty($conditions['user_account']))
                    {
                        $query->where('ml.obj_user','like','%'.$conditions['user_account'].'%');
                    }
                    if(!empty($conditions['msg_channels']))
                    {
                        $query->where('ml.channel_type',$conditions['msg_channels']);
                    }
                    if(!empty($conditions['msg_status']))
                    {
                        $query->where('ml.status',$conditions['msg_status']);
                    }
                })
//                ->groupBy('ml.log_id')  //todo:这里要改一下  想下怎么改   用mysql作groupby+分页
                ->orderBy('ml.log_id','desc')
                ->paginate($conditions['limit'],['*'],'page',$conditions['page'])->toArray();

            foreach ($items['data'] as &$item){
                $item = objectToArray($item);
                $item['create_time_str'] = !empty($item['create_time'])?Carbon::createFromTimestamp(strval($item['create_time']))->toDateTimeString():'';
                $item['actual_send_time_str'] = !empty($item['actual_send_time'])?Carbon::createFromTimestamp(strval($item['actual_send_time']))->toDateTimeString():'';
                $item['status_str'] = Config('msgconfig.msg_status')[$item['status']];
                $item['channel_type_str'] = Config('msgconfig.msg_channels')[$item['channel_type']];
                $item['msg_tpl_str'] = $item['ex_str'];
            }
            unset($item);
            return json_encode(['code'=>0,'count'=>$items['total'],'msg'=>'success','data'=>$items['data']]);
        }

        $data=[
            'title'=>'asd',
            'id'=>$id,
            'info'=>[],

            'allhistorylist_check'=>$allhistorylist_check
        ];

        return view($viewid, $data);
    }

    // 新增编辑消息模板
    private function addtemplate(Request $request, $id, $viewid)
    {
        $perms_arr = ['template_create'];
        $res_perm = $this->getUserPerms($request,$perms_arr);
        $template_create = $res_perm['template_create'];

        $rq_tpl_id = $request->input('tpl_id');
        $db = DB::connection('message');

        //消息模板一级分类
        $msg_tpl_cls = $db->table('lie_msg_tpl_classify')->orderby('cls_id','asc')->get();
        $msg_tpl_clses = [];
        foreach ($msg_tpl_cls as $k=>$v){
            $msg_tpl_clses[$v->cls_id] = $v->cls_name;
        }

        //消息模板二级分类
        $msg_tpl_sub_clses = [];

        if(!empty($rq_tpl_id))
        {
            //通过tpl_id找到模板的渠道们 和 描述等
            $info = $db->table('lie_msg_tpl as mt')->select('mt.tpl_id','mt.description','mt.channels','mt.msg_type','mt.creater','mt.source_type','mt.obj_user','mt.ex_str','mtsc.sub_cls_id','mtsc.sub_cls_name','mtsc.cls_id','mtc.cls_name')
                ->leftjoin('lie_msg_tpl_sub_classify as mtsc','mt.sub_cls_id','=','mtsc.sub_cls_id')
                ->leftjoin('lie_msg_tpl_classify as mtc','mtc.cls_id','=','mtsc.cls_id')
                ->where('tpl_id',$rq_tpl_id)->first();

            //获取消息模板二级分类
            if (!empty($info->cls_id)){
                $msg_tpl_sub_cls = $db->table('lie_msg_tpl_sub_classify')->select('sub_cls_id','sub_cls_name','cls_id')
                    ->where('cls_id',$info->cls_id)->get();
                foreach ($msg_tpl_sub_cls as $k=>$v){
                    $msg_tpl_sub_clses[$v->sub_cls_id] = $v->sub_cls_name;
                }
            }
            //通过找到的 channels 去渠道模板表里 把每个channel找出来
            $tpl_channels_arr = explode(',',$info->channels);
            $channel_tpls = [];
            foreach ($tpl_channels_arr as $channel_type)
            {
                $channel_tpl_obj = $db->table('lie_msg_channel_tpl')->where('tpl_id',$info->tpl_id)->where('channel_type',$channel_type)->first();

                //将channel_tpl_id赋给正确的变量中
                if($channel_type==1)
                {
                    $inner_chn_tpl_id = $channel_tpl_obj->channel_tpl_id;
                }elseif($channel_type==2)
                {
                    $sms_chn_tpl_id = $channel_tpl_obj->channel_tpl_id;
                }elseif($channel_type==3)
                {
                    $email_chn_tpl_id = $channel_tpl_obj->channel_tpl_id;
                }elseif($channel_type==4)
                {
                    $wechatNotify_chn_tpl_id = $channel_tpl_obj->channel_tpl_id;
                    //将head 和 tail从content中解析出来
                    $channel_tpl_obj->content = json_decode($channel_tpl_obj->content,true);
                }else{
                    $ding_chn_tpl_id = $channel_tpl_obj->channel_tpl_id;
                }
                $channel_tpls[$channel_type] = $channel_tpl_obj;
            }
            $info->channel_tpls = $channel_tpls;
        }

        $data=[
            'title'=>'asd',
            'id'=>$id,
            'info'=>!empty($info)?$info:(object)null,
            'inner_chn_tpl_id'=>!empty($inner_chn_tpl_id)?$inner_chn_tpl_id:'',
            'sms_chn_tpl_id'=>!empty($sms_chn_tpl_id)?$sms_chn_tpl_id:'',
            'email_chn_tpl_id'=>!empty($email_chn_tpl_id)?$email_chn_tpl_id:'',
            'wechatNotify_chn_tpl_id'=>!empty($wechatNotify_chn_tpl_id)?$wechatNotify_chn_tpl_id:'',
            'ding_chn_tpl_id'=>!empty($ding_chn_tpl_id)?$ding_chn_tpl_id:'',
            'tpl_channels_arr'=>!empty($tpl_channels_arr)?$tpl_channels_arr:[],
            'template_create' => $template_create,
            'msg_tpl_clses'=>$msg_tpl_clses,
            'msg_tpl_sub_clses'=>$msg_tpl_sub_clses
        ];

        return view($viewid, $data);
    }

    // 添加手动发送消息(会创建模板)
    private function sendmanualmessage(Request $request, $id, $viewid)
    {
        Csrf($request);

        $perms_arr = ['manualmessage_send'];
        $res_perm = $this->getUserPerms($request,$perms_arr);
        $manualmessage_send = $res_perm['manualmessage_send'];

        //为所有历史消息的操作类型赋值
        $op_type = '';
        if(empty($request['op_type']))
        {
            $op_type = 2;
        }else
        {
            $op_type = $request['op_type'];
        }
        $rq_log_id = $request->input('log_id');
        //发送人工消息改变了模板的选择时会传过来tpl_id
        $rq_tpl_id = $request->input('tpl_id');
        $db = DB::connection('message');
        $isContainInner = '';
        $isContainSMS = '';
        $isContainEmail = '';
        $isContainWechatNotify = '';

        //编辑时传过来log_id  选择模板时传过来tpl_id
        if(!empty($rq_log_id) || !empty($rq_tpl_id))
        {
            //1.编辑
            if(!empty($rq_log_id))
            {
                $log_id = $rq_log_id;
                $info = $db->table('lie_msg_log')->select('tpl_id','obj_user','expect_send_time')->where('log_id',$log_id)->first();
            }else//2.选择模板
            {
                $info = (object)null;
                $info->tpl_id = $rq_tpl_id;
                $info->obj_user = '';
                $info->expect_send_time = '';
            }

            //通过tpl_id找到模板的渠道们 和 描述
            $desc_and_channels = $db->table('lie_msg_tpl')->select('description','ex_str','channels','msg_type')->where('tpl_id',$info->tpl_id)->first();
            $info->desc = $desc_and_channels->description;
            $info->ex_str = $desc_and_channels->ex_str;
            $info->channels_str = $this->changeNumberStrToChineseStr(['站内信','短信','邮箱','微信通知'],$desc_and_channels->channels);
            $info->channels = $desc_and_channels->channels;
            $info->msg_type = $desc_and_channels->msg_type;

            //通过找到的 channels 去渠道模板表里 把每个channel找出来
            $tpl_channels_arr = explode(',',$info->channels);
            $channel_tpls = [];
            foreach ($tpl_channels_arr as $channel_type)
            {
                $channel_tpl_obj = $db->table('lie_msg_channel_tpl')->where('tpl_id',$info->tpl_id)->where('channel_type',$channel_type)->first();
                if($channel_type==4)
                {
                    //将head 和 tail从content中解析出来
                    $channel_tpl_obj->content = json_decode($channel_tpl_obj->content,true);
                }
                $channel_tpls[$channel_type] = $channel_tpl_obj;
            }
            $info->channel_tpls = $channel_tpls;

            //判断包含的消息渠道(用于展示消息渠道)(利用之前分割字符串得到的数组)
            $isContainInner = in_array('1',$tpl_channels_arr);
            $isContainSMS = in_array('2',$tpl_channels_arr);
            $isContainEmail = in_array('3',$tpl_channels_arr);
            $isContainWechatNotify = in_array('4',$tpl_channels_arr);
        }

        //找出所有模板(给选择模板用)
        $all_msg_tpl = $db->table('lie_msg_tpl')->select('tpl_id','ex_str','description')->get();

        if(empty($info))
        {
            $info = (object)null;
            $info->tpl_id = '';
            $info->obj_user = '';
            $info->actual_send_time = '';
            $info->expect_send_time = '';
            $info->desc = '';
            $info->ex_str = '';
            $info->channels_str = '';
            $info->channels ='';
            $info->channel_tpls = [];
            $info->msg_type = '';
        }

        //消息类型枚举
        $msg_type = [
            '请选择',
            '公告',
            '活动',
            '新闻',
            '其他'
        ];

        $data=[
            'title'=>'asd',
            'id'=>$id,
            'info'=>$info,
            'msg_type'=>$msg_type,
            'all_msg_tpl'=>$all_msg_tpl,
            'isContainInner'=>$isContainInner,
            'isContainSMS'=>$isContainSMS,
            'isContainEmail'=>$isContainEmail,
            'isContainWechatNotify'=>$isContainWechatNotify,

            'manualmessage_send'=>$manualmessage_send,
            'op_type'=>$op_type
        ];

        return view($viewid, $data);
    }



    //--------------------------------------------inner methods-----------------------------------------

    //数字字符串转为对应中文字符串  eg:1,2,3-->站内信,短信,邮件
    /*
     * return: 会返回一个跟传入数字字符串对应的汉字字符串,不对数据源造成影响
     * param 1:对比源:用于作对比及提取汉字
     * param 2:目标数字字符串(默认用','分割)
     */
    private function changeNumberStrToChineseStr($compareArr,$numberStr)
    {
        $chineseStr = '';
        $tpl_channels_arr = explode(',',$numberStr);
        if(count($tpl_channels_arr)>0 && count($compareArr)>0)
        {
            for ($i=0;$i<count($tpl_channels_arr);$i++)
            {
                for($j=0;$j<count($compareArr);$j++)
                {
                    if($tpl_channels_arr[$i]-1==$j)
                    {
                        $chineseStr .= $compareArr[$j].',';
                        break;
                    }
                }
            }
        }
        return $chineseStr;
    }

    private function getUserPerms(Request $request,$perms_arr)
    {
        $perms_str = implode(',',$perms_arr);
        $uid = $request->user->userId;

        $bid = "";
        $perm_url = "";

        //区分环境
        $current_domain = $_SERVER['HTTP_HOST'];
        if($current_domain === Config('msgconfig.domain_local'))
        {
            $bid = Config('msgconfig.perm_bid_local');
            $perm_url = Config('msgconfig.perm_domain_local');
        }
        elseif ($current_domain === Config('msgconfig.domain_sz'))
        {
            $bid = Config('msgconfig.perm_bid_sz');
            $perm_url = Config('msgconfig.perm_domain_sz');
        }
        elseif ($current_domain === Config('msgconfig.domain_release'))
        {
            $bid = Config('msgconfig.perm_bid_release');
            $perm_url = Config('msgconfig.perm_domain_release');
        }

        $url = $perm_url."/api/check/$uid/$bid/?perms=$perms_str";
        $res = json_decode(curl($url),true);
        if(!$res['retcode'])
        {
            return $res['data']['perms'];
        }
    }

    //根据当前域名获取config_id
    private function getConfigId()
    {
        $current_domain = $_SERVER['HTTP_HOST'];

        if($current_domain === Config('msgconfig.domain_local'))
        {
            return Config('msgconfig.config_id_local');
        }
        elseif ($current_domain === Config('msgconfig.domain_sz'))
        {
            return Config('msgconfig.config_id_sz');
        }
        elseif ($current_domain === Config('msgconfig.domain_release'))
        {
            return Config('msgconfig.config_id_release');
        }
    }
}