<?php
namespace app\common\model;

use app\hander\HelpHander;
use GatewayClient\Gateway;
use think\Db;
use think\Exception;
use think\Model;
use tools\Qxsms;

class Message extends Model
{

    public function add($type,$busId,$busType,$userId,$orgId,$context,$sms=0){
        $data = [
            'type' => $type,
            'bus_id' => $busId,
            'bus_type' => $busType,
            'user_id' => $userId,
            'org_id' => $orgId,
            'context' => $context,
            'status' => 0,
            'create_time' => date('Y-m-d H:i:s')
        ];
        $ret = Db::name('message')->insert($data);
        if($ret){
            try{
                // websocket推送
                Gateway::$registerAddress = config('app.gateway_register_ip');
                if(Gateway::isUidOnline($userId)){ // 在线发送消息
//                    Gateway::sendToUid($userId, json_encode(['type'=>'msgcount','data'=>[],'msg'=>'']));
                }

                if($sms == 1){
//                    $this->sendsms($userId,$context);
                }else{
                    //TODO:: 需要加队列执行耗时较多的极光推送和短信
                    if($type == 2||$type == 1){
                        // 短信推送
//                        $this->sendsms($userId,$context);
                    }
                    if($type == 3 && $busType == 12){ //工资审批提醒
                        // 短信推送
//                        $this->sendsms($userId,$context);
                    }
                }

                // 极光推送
                $extras = array(); // 额外参数
//                send_jpush([(string)$userId],$context,$extras);
            }catch (\Exception $e){
                trace('error:'.$e->getMessage());
            }
        }

        return $ret?true:false;
    }

    private function sendsms($userId,$content){
        $phone = Db::name('user')->where('id',$userId)->value('phone');
        $turn = Db::name('sms_config')->where('type',1)->value('value');
        if($phone && $turn){
            $qxsms = new Qxsms(config('app.sms_config'));
            $content = "【基建中心】".$content;
            $ret = $qxsms->send($phone,$content);
            return $ret;
        }
        return true;
    }

    public function lists($page,$size,$userId,$orgId,$type,$context,$status){
        $map[] = ['user_id','=',$userId];
        $map[] = ['org_id','=',$orgId];
        if($context != ''){
            $map[] = ['context','like','%'.$context.'%'];
        }
        if($type > 0){
            $map[] = ['type','=',$type];
        }
        if($status > 0){
            $map[] = ['status','=',$status];
        }
        $lists = $this
            ->where($map)
            ->page($page,$size)
            ->order('id desc')
            ->select();
        foreach ($lists as $k=>$v){
            if($v['bus_type'] == 2){
                $applyid = Db::name('apply_record')->where('del',0)->where('id',$v['bus_id'])->value('apply_id');
                $lists[$k]['bus_id'] = $applyid?$applyid:0;
            }
        }
        $total = $this->where($map)->count();
        $data = [
            'total' => $total,
            'list' => $lists?$lists->toArray():[]
        ];
        return $data;
    }

    // 消息未读数量
    public function selUnreadNum($userId,$orgId){
        $map[] = ['user_id','=',$userId];
        $map[] = ['org_id','=',$orgId];
        $map[] = ['status','=',0];
        $total = $this->where($map)->count();
        return $total;
    }

    // 标记为已读
    public function updataStatus($id,$userId){
        $ret = Db::name('message')->where('id',$id)->where('user_id',$userId)->where('status',0)->setField('status',1);
        if($ret){
            // websocket推送
            Gateway::$registerAddress = config('app.gateway_register_ip');
            if(Gateway::isUidOnline($userId)){ // 在线发送消息
                Gateway::sendToUid($userId, json_encode(['type'=>'msgcount','data'=>[],'msg'=>'']));
            }
        }
    }

    // 全部已读
    public function batcheUpdateStatus($type,$userId){
        $map[] = ['status','=',0];
        $map[] = ['user_id','=',$userId];
        if($type > 0){
            $map[] = ['type','=',$type];
        }
        Db::name('message')->where($map)->setField('status',1);

        if($type == 0){
            //工作动态报送未读的改成已读
            Db::name('work_news_receiver')->where('user_id',$userId)->where('is_read',0)->update([
                'is_read' => 1,
                'read_time' => date('Y-m-d H:i:')
            ]);
        }


    }

    // 删除
    public function batcheDelete($ids,$userId){
        Db::name('message')->where('id','in',$ids)->where('user_id',$userId)->delete();
    }

    // 系统消息通知列表
    public function selMessageByOrg($page,$size,$userId){
        $map[] = ['type','=',4];
        $map[] = ['user_id','=',$userId];
        $lists = $this
            ->where($map)
            ->page($page,$size)
            ->order('id desc')
            ->select();
        return $lists?$lists->toArray():[];
    }

    public function queryNewsList($userId,$orgId){
        $data = [
            [
                'id' => 0,
                'name' => '公告通知',
                'cate' => 1,
                'type' => 0,
                'title' => '',
                'nums' => 0
            ],
            [
                'id' => 0,
                'name' => '流程审批',
                'cate' => 2,
                'type' => 0,
                'title' => '',
                'nums' => 0
            ],
            [
                'id' => 0,
                'name' => '工作提醒',
                'cate' => 3,
                'type' => 0,
                'title' => '',
                'nums' => 0
            ],
            [
                'id' => 0,
                'name' => '工作汇报',
                'cate' => 5,
                'type' => 0,
                'title' => '',
                'nums' => 0
            ],
            [
                'id' => 0,
                'name' => '党建纪检',
                'cate' => 6,
                'type' => 0,
                'title' => '',
                'nums' => 0
            ],
            [
                'id' => 0,
                'name' => '系统消息',
                'cate' => 4,
                'type' => 0,
                'title' => '',
                'nums' => 0
            ],
        ];
        foreach ($data as $k=>$v){
            if($v['cate'] == 4){
                $org = 0;
            }else{
                $org = $orgId;
            }
            $info = Db::name('message')
                ->where('type',$v['cate'])
                ->where('org_id',$org)
                ->where('user_id',$userId)
                ->order('id desc')
                ->field('id,context as title,create_time')
                ->find();
            if($info){
                $data[$k]['title'] = $info['title'];
                $data[$k]['id'] = $info['id'];
                $data[$k]['title'] = $info['title'];
                $nums = Db::name('message')
                    ->where('type',$v['cate'])
                    ->where('org_id',$org)
                    ->where('status',0)
                    ->where('user_id',$userId)
                    ->count();
                $data[$k]['nums'] = $nums;
                $data[$k]['type'] = $nums > 0 ? 1 : 0;
            }
        }
        return $data;
    }

    // 工作提醒列表
    public function selMessageWork($page,$size,$userId,$orgId){
        $map[] = ['type','=',3];
        $map[] = ['user_id','=',$userId];
        $map[] = ['org_id','=',$orgId];
        $lists = $this
            ->where($map)
            ->page($page,$size)
            ->order('id desc')
            ->select();
        $lists = $lists?$lists->toArray():[];
        foreach ($lists as $k=>$v){
            if($v['bus_type'] == 2){
                $lists[$k]['bus_id'] = Db::name('apply_record')->where('del',0)->where('id',$v['bus_id'])->value('apply_id');
            }
        }
        return $lists;
    }

    // 工作通知列表
    public function queryWorkNotice($page,$size,$userId,$orgId){
        $map[] = ['type','=',2];
        $map[] = ['user_id','=',$userId];
        $map[] = ['org_id','=',$orgId];
        $map[] = ['bus_type','=',2];
        $lists = Db::name('message')
            ->where($map)
            ->field('create_time as mcreate_time,type,bus_id')
            ->page($page,$size)
            ->order('id desc')
            ->select();
        $lists = $lists?$lists:[];
        foreach ($lists as $k=>$v){
            $info = Db::name('apply_record')
                ->alias('ar')
                ->join('apply a','a.id = ar.apply_id')
                ->join('user_info ui','ui.user_id = a.user_id')
                ->where('ar.id',$v['bus_id'])
                ->where('ar.del',0)
                ->field('ui.name as userName,a.create_time,a.apply_sn,ar.apply_id,ar.status,a.title as applyTitle,ar.type as arType,ar.id as arId')
                ->find();
            $lists[$k]['userName'] = $info['userName'];
            $lists[$k]['applySn'] = $info['apply_sn'];
            $lists[$k]['applyId'] = $info['apply_id'];
            $lists[$k]['status'] = $info['status'];
            $lists[$k]['applyTitle'] = $info['applyTitle'];
            $lists[$k]['arType'] = $info['arType'];
            $lists[$k]['createTime'] = $info['create_time'];
            $lists[$k]['arId'] = $info['arId'];
            $lists[$k]['workLogId'] = 0;
            $lists[$k]['contentOne'] = '';
            $lists[$k]['cate'] = 1;
//            if($info['arType'] == 2||$info['arType'] == 8){
//                $lists[$k]['cate'] = 1;
//            }else{
//                $lists[$k]['cate'] = 2;
//            }
            unset($lists[$k]['bus_id']);
        }
        return $lists;
    }

    // 工作汇报列表
    public function selMessageReport($page,$size,$userId,$orgId){
        $map[] = ['type','=',5];
        $map[] = ['user_id','=',$userId];
        $map[] = ['org_id','=',$orgId];
        $lists = $this
            ->where($map)
            ->page($page,$size)
            ->order('id desc')
            ->select();
        $lists = $lists?$lists->toArray():[];
        foreach ($lists as $k=>$v){
            $reportType = Db::name('work_report_receiver')
                ->alias('wrr')
                ->join('work_report wr','wr.id = wrr.work_report_id')
                ->where('wrr.id',$v['bus_id'])
                ->value('wr.work_type_id');
            $lists[$k]['report_type'] = $reportType;
        }

        return $lists;
    }

}