<?php
namespace model;
/**
 * Class element
 * @package model
 */
class message extends \model\element
{
	/**
	 * @param array|string $elecfg 配置数据或者配置element名称
	 */
	public function __construct($elecfg='adm_message')
    {
		parent::__construct($elecfg);
	}

    /**
     * 添加一条记录
     * @param array $users 用户ID数组
     * @param bool $isSendSiteMsg 是否发送站内消息
     * @param array $data 参考 adm_message 表的字段描述
     * @return bool
     */
	function send($users,$data,$isSendSiteMsg=true){
	    $users = array_unique($users);
		$default = [
			'amsg_type'=> 0,
			'amsg_from'=> getOpuser(),
			'amsg_title'=> "",
			'amsg_body'=> '',
			'amsg_url'=> '',
			'amsg_urltitle'=> '',
			'amsg_file'=> '',
			'amsg_send_mail'=> 0,
			'amsg_send_sms'=> 0,
			'create_time'=> getNowTime(),
			'update_time'=> getNowTime()
		];
		$data = array_merge($default,$data);
		if(empty($users) || empty($data['amsg_title'])){
			exisJson(300);
			return false;
		}
        $users = array_unique($users);
        $this->db->Begin();
			$saveData = $this->formartSaveData($data);
			$this->db->insert($this->table,$saveData);
			$key = $this->db->id();
			foreach($users as $userid){
			    if(!empty($userid)){
    				$this->db->insert('adm_user_link_msg',[
    					'aul_au_id'=>$userid,
    					'aul_amsg_id'=>$key,
    					'aul_type'=>$data['amsg_type']
    				]);
			    }
			}
        $this->db->End();
		
		//发站内消息
		if($isSendSiteMsg){
			socketSendCall($users,'getServerMessage()');
		}
		
		//发邮件
		if($data['amsg_send_mail']){
			$tomail = $this->db->select('adm_user', 'au_email', ['au_id'=>$users, 'au_email[!]'=>'']);
			if(!empty($tomail))
			{
			    if(!isset(\mvc::$cfg['mailSendServer']['cc']) || empty(\mvc::$cfg['mailSendServer']['cc'])){
    			    //array_push($tomail,'wuyanyan@gsp.cn');
    			    array_push($tomail,'daiff@gsp.cn');
			    }else{
			       $arr = explode(',',\mvc::$cfg['mailSendServer']['cc']); 
			       foreach($arr as $v){
			           array_push($tomail,$v);
			       }
			    }
			    $title = $data['amsg_title'].'('.lg('系统邮件不要回复').')';
				$email = new \model\email();
				$tomail = array_unique($tomail);
				$res = $email->send(implode(',', $tomail), $title, $data['amsg_body']);
				if(isset($res['ok']) && !empty($res['ok'])){
				    errorLog([$tomail,$title,$data,$res],'SENDMAIL_SUCCESS');
				}else{
				    errorLog([$tomail,$title,$data],'SENDMAIL_ERROR');
				}
			}
		}

		//发短信
		if($data['amsg_send_sms']){
			//mailSend($users,$data);
		}

		return $key;
	}
	function update($msgId,$data){
	    $this->db->update($this->table,$data,['amsg_id'=>$msgId]);
	}
	    

	/**
	 * 虚拟删除记录
	 * @param string|int|array $ids, id集数组或字符串，字符串用 , 号分隔
	 * @return bool
	 */
	function virtDeleteRows($userid,$msgids){
	    if(empty($msgids)) return 402;
        if(!is_array($msgids)){
            $msgids = explode(',',$msgids);
        }
		if($this->db->has('adm_message',['amsg_type'=>1, 'amsg_event'=> 0,'amsg_id'=>$msgids])){
			$result = 402;
		}else{
			//$this->db->update('adm_user_link_msg',['aul_delete'=>1],['aul_au_id'=>$userid,'aul_amsg_id'=>$msgids]);
			$this->db->begin();
			$this->db->delete('adm_user_link_msg',['aul_au_id'=>$userid,'aul_amsg_id'=>$msgids]);
			foreach ($msgids as $msgId){
    			$st = $this->db->query("select * from adm_message where amsg_id =".$msgId." and not exists(select 1 from adm_user_link_msg where aul_amsg_id=".$msgId.")");
    			if($row = $st->fetch()){
    			    if($row['amsg_file']){
    			        @unlink($row['amsg_file']);
    			    }
        			$this->db->delete('adm_message',['amsg_id'=>$msgId]);
    			}
			}
			$this->db->end();
			$result = 200;
		}
		return $result;
	}	

	/**
	 * 批量设置为已读
	 * @param string|int|array $ids, id集数组或字符串，字符串用 , 号分隔
	 * @return bool
	 */
	function readRows($userid,$msgids){
        if(!is_array($msgids)){
            $msgids = explode(',',$msgids);
        }
		$this->db->update('adm_user_link_msg',['aul_isread'=>1,'aul_read_time'=>getNowTime()],['aul_au_id'=>$userid,'aul_amsg_id'=>$msgids]);
	}	

    /**
     * 取未读消息统计
     * @param int $userid 用户ID
     * @return int
     */
	function getNoReadMessageCountByUserid($userid){
		$where = [
			'aul_type'=>0,
			'aul_au_id'=>$userid,
			'aul_isread'=>0,
			'aul_delete'=>0,
		];
		return $this->db->count('adm_user_link_msg',$where);
	}
	
    /**
     * 取未处理任务统计
     * @param int $userid 用户ID
     * @return int
     */
	function getNoReadTaskCountByUserid($userid){
		$table = 'adm_message(msg)';
		$join['[>]adm_user_link_msg(lnk)'] = [
			'msg.amsg_id' => 'aul_amsg_id'
		];
		$where = [
			'amsg_type'=>1,
			'aul_au_id'=> $userid,
			'amsg_event'=>0,
			'amsg_delete'=>0,
			'aul_delete'=>0,
		];
		return $this->db->count($table,$join,'amsg_id',$where);
	}

	/**
     * 未读预警消息数
     * @param int $userid 用户ID
     * @return int
     */
	function getNoReadWarnMessageCountByUserid($userid){
		$where = [
			'aul_type'=>3,
			'aul_au_id'=>$userid,
			'aul_isread'=>0,
			'aul_delete'=>0,
		];
		return $this->db->count('adm_user_link_msg',$where);
	}
	
	
    /**
     * 设置为已读
     * @param int $userid 用户ID
     * @param int $msgid 消息ID
     * @return int
     */
	function setReaded($userid,$msgid){
		$where = [
			'aul_au_id'=>$userid,
			'aul_amsg_id'=>$msgid
		];
		return $this->db->update('adm_user_link_msg',['aul_isread'=>1,'aul_read_time'=>getNowTime()],$where);
	}
}