<?php
namespace app\common\controller;
use think\facade\Cache;
use think\facade\Db;
use app\common\variable\MsgCode;
use app\common\validate\CreateContacts as CreateContactsValidate;
use think\exception\ValidateException;
use app\common\model\PushMessage as PushMessageModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\Company as CompanyModel;
use app\common\model\ImContacts as ImContactsModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\Vip as VipModel;
use app\common\model\VipRuleValue as VipRuleValueModel;
use app\common\model\VipRule as VipRuleModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\model\Jobs as JobsModel;
use XYCms\Im as XYCMSIm;
/**
 * 
 */
class Message extends Base
{
    public static function getList($D=[])
    {
        $where=[];
        $where[]=['uid','=',$D['uid']];
        $where[]=['status','=',1];
        if (isset($D['is_read'])) {
            if ($D['is_read']) {
                $where[]=['is_read','=',1];
            }else{
                $where[]=['is_read','=',0];
            }
        }
        $Data=PushMessageModel::where($where)
            ->whereNull('delete_time')
            ->order('id desc')->paginate(15)->each(function($v){
                return $v;
            });
        if ($Data->items()) {
            return parent::ajaxReturn('',MsgCode::$success,$Data);
        }else{
            return parent::ajaxReturn('暂无数据~',MsgCode::$error);
        }
    }
    public static function getFind($D)
    {
        $where=[];
        $where[]=['msg.id','=',$D['id']];
        $where[]=['msg.uid','=',$D['uid']];
        $where[]=['msg.status','=',1];
        $Data=PushMessageModel::alias('msg')->where($where)
            ->whereNull('msg.delete_time')
            ->join(config('databse.prefix').'push_message_content content','content.mid=msg.id')
            ->field('msg.*,content.content')
            ->find();
        if ($Data) {
            if (!$Data->is_read)
                self::setMessageRead($D);
            return parent::ajaxReturn('',MsgCode::$success,$Data);
        }else{
            return parent::ajaxReturn('消息不存在',MsgCode::$error);
        }
    }
    public static function setMessageRead($D)
    {
        $where=[];
        $where[]=['uid','=',$D['uid']];
        if(!empty($D['id'])){
            $where[]=['id','=',$D['id']];
            $PushMessageModel=PushMessageModel::where($where)->find();
            if ($PushMessageModel) {
                if ($PushMessageModel->is_read)
                    return parent::ajaxReturn();
                $PushMessageModel->is_read=1;
                if ($PushMessageModel->save()) {
                    return parent::ajaxReturn();
                }else{
                    return parent::ajaxReturn('设置已读失败',MsgCode::$error);
                }
            }else{
                return parent::ajaxReturn('消息不存在',MsgCode::$error);
            }
        }else{
            if (PushMessageModel::where($where)->update(['is_read'=>1])) {
                return parent::ajaxReturn();
            }else{
                return parent::ajaxReturn('设置已读失败',MsgCode::$error);
            }
        }
    }
    public static function delMessage($D)
    {
        $where=[];
        $where[]=['id','=',$D['id']];
        $where[]=['uid','=',$D['uid']];
        $PushMessageModel=PushMessageModel::where($where)->find();
        if ($PushMessageModel) {
            $PushMessageModel->is_read=1;
            $PushMessageModel->delete_time=time();
            if ($PushMessageModel->save()) {
                return parent::ajaxReturn();
            }else{
                return parent::ajaxReturn('删除失败',MsgCode::$error);
            }
        }else{
            return parent::ajaxReturn('消息不存在',MsgCode::$error);
        }
    }
    public static function createContacts($D)
    {
        /**
         * 用户验证
         */
        try {
            validate(CreateContactsValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(),MsgCode::$error);
        }
        $Data=[
            'touid'     => $D['touid'],
            'nickname'  => $D['nickname'],
            'headimg'   => $D['headimg'],
            'jobs_id'   => $D['jobs_id'],
            'send'      => [
                'nickname'  => $D['send']['nickname'],
                'headimg'   => $D['send']['headimg']
            ],
            'uid'       => $D['uid']
        ];
        $imObj=null;
        try {
            $imObj=new XYCMSIm;
            $Contacts=$imObj->getContacts($Data);
            if($Contacts)
            	return parent::ajaxReturn('',MsgCode::$success,$Contacts);
        } catch (\think\Exception $e) {
            return parent::ajaxReturn($e->getMessage(),MsgCode::$error);
        }
        $JobsModel=JobsModel::where(['id'=>$D['jobs_id']])->find();
        if($D['role_type']){
        	switch (config('xy_im_setting.company_mode')) {
        		case 1:
            		if(!$D['company_id'])
            			return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);
        		case 2:
		            $ResumeModel=ResumeModel::alias('resume')->where(['resume.uid'=>$D['touid']])
		            ->join('resume_downloaded d','d.resume_id=resume.id AND d.status=1 AND d.company_id='.$D['company_id'],'RIGHT')->field('d.id')->find();
		            if(!$ResumeModel)
		                return parent::ajaxReturn('您需要下载对方简历才能发起聊天',MsgCode::$error);
        			break;
        		case 3:
        			$ret=self::hasImMaxPeople($D);
        			if($ret)
        				return $ret;
        			break;
        	}
        }else{
		    $ResumeModel=ResumeModel::where(['uid'=>$D['uid']])->find();
        	switch (config('xy_im_setting.personal_mode')) {
        		case 1:
            		if(!$ResumeModel)
            			return parent::ajaxReturn('请先完善简历信息',MsgCode::$error);
            		$personal_mode_resume_progress=config('xy_im_setting.personal_mode_resume_progress');
            		if($ResumeModel->progress<$personal_mode_resume_progress)
            			return parent::ajaxReturn('简历完整度低于'.$personal_mode_resume_progress.'%',MsgCode::$error);
            		break;
        		case 2:
		    		$CompanyModel=CompanyModel::where(['uid'=>$D['touid']])->find();
		    		$JobsDeliveryResumeModel=JobsDeliveryResumeModel::where(['company_id'=>$CompanyModel->id,'resume_id'=>$ResumeModel->id])->count();
		    		if(!$JobsDeliveryResumeModel)
            			return parent::ajaxReturn('请先投递简历',MsgCode::$error);
        			break;
        		case 3:
        			$ret=self::hasImMaxPeople($D);
        			if($ret)
        				return $ret;
        			break;
        	}
        }
        try {
            $Contacts=$imObj->createContacts($Data);
            if (!ImContactsModel::where(['uid'=>$D['uid'],'cid'=>$Contacts['id']])->count()) {
                $UserVipModel=UserVipModel::where(['uid'=>$D['uid']])->find();
                $UserVipModel->update_vip=1;
	            $ImContactsModel=new ImContactsModel;
	            $ImContactsModel->cid=$Contacts['id'];
	            $ImContactsModel->uid=$D['uid'];
	            $ImContactsModel->save();
                $PushTaskModel=new PushTaskModel;
                $PushTaskModel->event       =   'IMMessage';
                $PushTaskModel->uid         =   $Data['touid'];
                $PushData=[
                    'nickname'  =>  $Data['send']['nickname'],
                    'jobs_name' =>  $JobsModel?$JobsModel->title:'',
                    'time'      =>  date('Y-m-d H:i:s')
                ];
                $PushTaskModel->data        =   json_encode($PushData,JSON_UNESCAPED_UNICODE);
                Db::startTrans();
                try {
                    $UserVipModel->save();
                    $ImContactsModel->save();
                    $PushTaskModel->save();
                    // 提交事务
                    Db::commit();
                } catch (Exception $e) {
                    //回滚事务
                    Db::rollback();
                }
            }
            return parent::ajaxReturn('',MsgCode::$success,$Contacts);
        } catch (\think\Exception $e) {
            return parent::ajaxReturn($e->getMessage(),MsgCode::$error);
        }
    }
    public static function hasImMaxPeople($D)
    {
    	$where=['is_company'=>$D['role_type'],'level'=>0];
    	$UserVipModel=UserVipModel::where(['uid'=>$D['uid']])->field('company_vip_level,company_vip_time,personal_vip_level,personal_vip_time')->find();
    	if($D['role_type']){
    		if($UserVipModel && $UserVipModel->company_vip_time>time())
    			$where=['is_company'=>$D['role_type'],'level'=>$UserVipModel->company_vip_level];
    	}else{
    		if($UserVipModel && $UserVipModel->personal_vip_time>time())
    			$where=['is_company'=>$D['role_type'],'level'=>$UserVipModel->personal_vip_level];
    	}
    	$VipModel=VipModel::where($where)->field('id')->find();
    	$VipRuleValueModel=VipRuleValueModel::where(['alias'=>'im-max-people'])->field('id,value')->find();
    	if($VipModel && $VipRuleValueModel){
    		$value=$VipRuleValueModel->value;
	    	$VipRuleModel=VipRuleModel::where(['vid'=>$VipModel->id,'rid'=>$VipRuleValueModel->id])->find();
	    	if($VipRuleModel)
    			$value=$VipRuleModel->value;
	    	$ImContactsModel=ImContactsModel::where(['uid'=>$D['uid']])->count();
    		if($ImContactsModel>=$value)
            	return parent::ajaxReturn('同时聊天人数上限为'.$value.'人',MsgCode::$error);
    	}
    	return false;
    }
    public static function getUnreadMessage($uid)
    {
        $where=[];
        $where[]=['uid','=',$uid];
        $where[]=['status','=',1];
        $where[]=['is_read','=',0];
        $count=PushMessageModel::where($where)->whereNull('delete_time')->count();
        return parent::ajaxReturn('',MsgCode::$success,['message_count'=>$count]);
    }
}