<?php
namespace Addons\QyWechat;

use Services\Service;
use Models\BaseModel as Model;

class Helper extends Service
{
    //获取域名
	public function get_http_server_name(){
		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
		return  $http_type.$_SERVER['SERVER_NAME'];
	}
	
	//获取指定长度（$len）字符串
	public function getRandStr(int $len,int $index = 0,string $baseStr=""){
        $chars = array(
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
			'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
			'0','1','2','3','4','5','6','7','8','9'
			);
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = $baseStr.base_convert($index, 10, 36);
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
	
		/**
	 * 获取指定日期段内每一天的日期
	 * @date 2017-02-23 14:50:29
	 *
	 * @param $startdate
	 * @param $enddate
	 *
	 * @return array
	 */
	function getDateRange($startdate, $enddate) {
		$stime = strtotime($startdate);
		$etime = strtotime($enddate);
		$datearr = [];
		while ($stime <= $etime) {
			$datearr[] = date('Y-m-d', $stime);//得到dataarr的日期数组。
			$stime = $stime + 86400;
		}
		return $datearr;
	}
	
	/**
	 * 设置返回头
	 * @param $key
	 * @param $value
	 * @return array
	 */
	function set_header($key=null,$value=null){
		static $header=[];
		if($key)$header[$key]=$value;
		return $header;
	}
	
	/**
     * import css js image out of pub director
     * @param $path
     * @param bool $refresh
     * @return mixed|string
     */
    public function import($path){
        $ext = substr(strrchr($path, '.'), 1);
        $source_path= __DIR__.'/View/'.ltrim($path,'/\\');

        if(($ext == 'html'||$ext == 'php')&&is_file($source_path)){
            include($source_path);
            return;
        }
        if(  is_file($source_path)){
            $pub_son_path ="tempassets/".basename(__DIR__)."/".ltrim($path,'/\\');
            $publish_path=pub_path($pub_son_path);
            $param='';
            //文件如果被改变就重新发布
            if(!is_file($publish_path)|| filemtime($source_path) > filemtime($publish_path)){
                $this->set_header('X-Accel-Buffering','no'); // 刷新缓存
                $this->set_header("Expires","Mon, 26 Jul 1997 05:00:00 GMT");
                $this->set_header("Cache-Control","no-cache, must-revalidate");
                $this->set_header("Pragma: no-cache");
                is_dir(dirname($publish_path)) or mkdir(dirname($publish_path),0751,true);
                copy($source_path,$publish_path);

            }
            $param='?t='.time();
            $url=get_host($pub_son_path);
            if($ext == 'js'){
                return "<script src='{$url}{$param}'></script>";
            }elseif ($ext == 'css'){
                return '<link rel="stylesheet" type="text/css" href="'.$url.'" media="all" />';
            }else{
                return $url;
            }
        }

        return '';

    }
	
	public function get_user_by_userid($wid,$userid){
		$user = (new \Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$userid])->get_model_array();
		return $user;
	}
	public function get_user_by_id($wid,$user_id){
		$user = (new \Model('qy_user_list'))->find(['wid'=>$wid,'id'=>$user_id])->get_model_array();
		return $user;
	}

	public function get_et_by_userid($wid,$userid){
		$et = (new \Model('qy_externalcontact_list'))->find(['wid'=>$wid,'external_userid'=>$userid])->get_model_array();
		return $et;
	}
	
	public function get_group_chat($wid,$chatid){
		$groupchat = (new \Model('qy_et_groupchat'))->find(['wid'=>$wid,'chat_id'=>$chatid])->get_model_array();
		return $groupchat;
	}
	
	public function get_radar($id){
		$record = (new \Model('qy_radar_list'))->find($id)->get_model_array();
		return $record;
	}
	public function get_et_tags($wid){
		$tagArr = [];
		$tagRes = (new \Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all();
		foreach($tagRes as $tagres){
			$tags = json_decode($tagres->tags,1);
			foreach($tags as $tag){
				$tagArr[$tag['id']] = $tag['name'];
			}
			
		}
		return $tagArr;
	}
	
	function filterEmoji($str){
	  $str = preg_replace_callback( '/./u',
		  function (array $match) {
			return strlen($match[0]) >= 4 ? '' : $match[0];
		  },
		  $str);
	   return $str;
	}
	
	function add_way_arr(){
		return [
			0 => '未知来源',
			1 => '扫描二维码',
			2 => '搜索手机号',
			3 => '名片分享',
			4 => '群聊',
			5 => '手机通讯录',
			6 => '微信联系人',
			7 => '来自微信的添加好友申请',
			8 => '安装第三方应用时自动添加的客服人员',
			9 => '搜索邮箱',
			201 => '内部成员共享',
			202 => '管理员/负责人分配'
		];
	}

	public static function get_userid($user_id){
		$userid = array();
		if(!$user_id){
			return '';
		}
		if(is_array($user_id)){
			foreach ($user_id as $k => $val) {
				$user_list = (new Model('qy_user_list'))->find(['id'=>$val]);
				$userid[] = $user_list->userid;
			}
		}else{
			$user_list  = (new Model('qy_user_list'))->find(['id'=>$val]);
			$userid[] = $user_list->userid;
		}
		return $userid;
	}
}
