<?php
namespace model\user;
use \model;
/**
 * Class userpowerMod
 * @author
 * @copyright
 */
class users extends \model
{

	/**
     * @method 分页
     * @param  $sql 将要执行的 SQL语句
     * @param  $pages  {page: 2 , pagesize: 3, recordCount: 0}
     * @return {recordCount: 11
                pageCount: 4
                limit: " limit 3,3"
                page: 2
                pagesize: 3}
     */
    public function page($sql,$pages)
    {
       if(empty($pages['recordCount'])){
           $this->db->query($sql);
		   $row = $this->db->query("SELECT FOUND_ROWS() as count")->fetch();
           $pages['recordCount'] = (int) $row['count'];
       }
       if(empty($pages['pageSize'])) $pages['pageSize'] = 20;
       if(empty($pages['page'])) $pages['page'] = 1;
       $pages['pageCount'] = ceil($pages['recordCount'] / $pages['pageSize']);
       $begin = ($pages['page']-1) * $pages['pageSize'];
       $pages['limit'] = sprintf(' limit %d,%d', $begin, $pages['pageSize']);
       return $pages;
    }

    private $scorEtype = [
         '每日登录' => ['score' => 1],
         '点击新产品快报'=> ['score' => 3],
         '反馈型号通用型' => ['score' => 10],
         '反馈错误型号' => ['score' => 10],
         '反馈新车型型号' => ['score' => 30],
    ];


    /**
     * MD5密码
     * @return string
     */
    public function pass($value)
    {
        return md5(substr($value,-3).md5($value.substr($value,0,3)).'^8mR3Hc7&98s5*62Q/');
    }

    public function getNoticeById()
    {
        return $this->db->get('news', ['news_is_allow','news_remark'], ['news_cate_id'=>0, 'ORDER'=>['news_id'=>'desc']]);
    }

    public function addNotice($data)
    {
        return $this->update('news',['news_remark' => $data['news_remark'],'news_is_allow'=>$data['news_is_allow']],['news_id'=>1]);
    }

    /**
     * 添加短信CODE
     * @return array
     */
    public function addSmsCode($mb,$code)
    {
        $time = date('Y-m-d h:i:s', time());
        $data = [
            'sms_mb'=>$mb,
            'sms_code'=>$code,
            'sms_create_time'=>$time
        ];
        return $this->db->insert('sms',$data);
    }

    /**
     * 获取最近一条短信CODE
     * @return array
     */
    public function getSmsCode($mb)
    {
        return $this->db->get('sms', '*', ['sms_mb'=>$mb, 'ORDER'=>['sms_id'=>'DESC']]);
    }

    /**
     * 删除短信CODE
     * @return array
     */
    public function delSmsCode($mb)
    {
        $sql = sprintf("delete from sms where sms_mb='%s'",$mb);
        return $this->db->query($sql);
    }

    public function getScoreByUid($uId)
    {
		 return $this->db->get('user', 'u_score', ['u_id'=>$uId]);
    }
    /**
     * @param $uId
     * @param $page
     * @param $limit
     * @return array|成功赋值并返回true
     */
    public function getScoreByUidList($param,$pages)
    {
        $where = '1=1';
        if(!$param['u_id']){
            return [
                'pages' => $pages,
                'list' => [],
            ];
        }else{
            $where = sprintf(" us_u_id=%d",$param['u_id']);
        }
        $type = $this->getType();
        $sql = sprintf("select * from user_score where %s order by us_create_time desc",$where);
        $pages = $this->page($sql, $pages);
        $sql .= $pages['limit'];
        $result = $this->db->query($sql)->fetchAll();
        foreach ($result as &$value){
            $value['us_type'] = $type[$value['us_type']]['title'];
        }
        return [
            'pages' => $pages,
            'list' => $result
        ];
    }

    public function getScoreType()
    {
        return $this->scorEtype;
    }

    public function getType()
    {
        $type = [];
        array_walk(\mvc::$cfg['DEFINE'],function ($value,$key) use(&$type){
            if(strpos($key,'SCORE_') !==false){
                $type[$key] = $value;
            }
        });
        return $type;
    }

    /**
     * 更新用户积分
     * @param $data['us_type'] 类型 可用 $this->getScoreType() 获取全部
     * @param $data['us_u_id'] 用户ID
     * @param $data['us_ue_id'] 纠错ID
     * @param  $data['us_score'] 积分
     * @param  $data['us_remark'] 说明
     * @param string $rules 默认加法 可传+ -
     * @param string $dateTime 时间字段
     * @return bool true成功返回 false 失败
     */
    public function updateUserScore($data,$rules = '+',$dateTime = '')
    {
        if(!empty($dateTime)){
            if( $this->db->get('user_score', 'us_u_id', ['us_u_id'=>$data['us_u_id'], 'us_type'=>$data['us_type'], 'us_create_time'=>$dateTime])){
                return false;
            }
        }
        if(!in_array($rules,['+','-'])){
            return false;
        }
        $time  = date('Y-m-d H:i:s',time());
        $type = [];
        array_walk(\mvc::$cfg['DEFINE'],function ($value,$key) use(&$type){
            if(strpos($key,'SCORE_') !==false){
                $type[$key] = $value;
            }
        });
        if(empty($data['us_type'])){
            $us_score = $rules.$data['us_score'];
        }else{
            $us_score = $rules.($type[$data['us_type']]['value'] ?: 0);
        }
        $datas = [
            'us_type' => $data['us_type'],
            'us_au_id' => $data['us_au_id'] ?: 0,
            'us_u_id' => $data['us_u_id'],
            'us_ue_id' => $data['us_ue_id'] ?: 0,
            'us_score' => $us_score,
            'us_remark' => $data['us_remark'],
            'us_create_time' => $time
        ];
        $this->db->Begin();
        $this->db->insert('user_score',$datas);
        if($rules == '-'){
            $sql = sprintf("update user set u_score=u_score%d where u_id=%d",$datas['us_score'],$data['us_u_id']);
        }else{
            $sql = sprintf("update user set u_score=u_score+%d where u_id=%d",$datas['us_score'],$data['us_u_id']);
        }
        $this->db->query($sql);
        $this->db->End();
        return true;
    }

    /**
     * 添加用户
     * @return array
     */
    public function updatePass($mb,$password)
    {
        $data['u_password'] = $password;
		$data['u_password_time'] = getNowTime();
        return $this->db->update('user',$data,["u_mb"=>$mb]);
    }

    /**
     * 通过手机号得到用户记录
     * @return array
     */
    public function getRowByMb($mb)
    {
        return $this->db->get('user', '*', ['u_mb'=>$mb]);
    }

  
    public function errorList($param, $pages)
    {
        /*$where = ' where 1=1 ';
        if(!empty($param['mobile']))$where .= sprintf(" and ue_mb like '%%%s%%'",$param['mobile']);
        if(!empty($param['ue_status'])){
            $temp = $param['ue_status'] == 1 ? '未读': ($param['ue_status'] == 2 ? '未处理' : ($param['ue_status'] == 3 ? '已处理': $param['ue_status'] == 4)  ? '已处理-加积分':'无法处理问题');
            $where .= sprintf(" and ue_status='%s'",$temp);
            //var_dump($where);exit();
        }
        $sql = sprintf("select * from user_error left join gsp_product on ue_p_id = p_id %s order by ue_create_time desc",$where);
        $pages = $this->page($sql, $pages);
        $sql .= $pages['limit'];
        $result = $this->db->query($sql)->fetchAll();
        foreach ($result as &$value){
            $value['ue_cause'] = mb_substr($value['ue_cause'], 0, 30, 'utf8').'...';
            if(empty($value['ue_image'])){
                $value['ue_image'] = "";
            }else{
                $value['ue_image'] =  \mvc::$cfg['SELF_UPLOADS_URL'].'/'.$value['ue_image'];
            }
            $value['ue_user_info'] = json_decode($value['ue_user_info'],true);
            if(is_array($value)){
                $value['ue_user'] = '真实姓名:'.$value['ue_user_info']['truename'].'</br>';
                $value['ue_user'] .= '性别:'.($value['ue_user_info']['sex'] == 1 ? '男' :'女').'</br>';
                $value['ue_user'] .=  '公司:'.$value['ue_user_info']['company'].'</br>';
                $value['ue_user'] .=  '微信:'.$value['ue_user_info']['wx'].'</br>';
            }
            unset($value['ue_user_info']);
        }
        return [
            'list' => $result,
            'pages' => $pages,
        ];*/
    }

    public function getUserErrorById(int $id)
    {
        return $this->db->get('user_error', '*', ['ue_id'=>$id]);
    }

    public function updateStatuss($param,$status)
    {
        return $this->db->update('user_error',['ue_status' => $status,'ue_adm_id'=>$param['us_au_id'],'ue_update_time' => date('Y-m-d H:i:s',time())],["ue_id"=>$param['us_ue_id']]);
    }

    /**
     * @param $ue_status_remark 备注
     * @param $param
     * @param $status
     * @return 成功
     */
    public function updateStatus($ue_status_remark,$param,$status)
    {
        $time = getNowTime();
		if(!empty($param['us_ue_id']))
		{
            $data = $this->getUserErrorById($param['us_ue_id']);
			$param['us_u_id'] = $data['ue_u_id'];
            //把已处理加积分改为其它状态
            if($data['ue_status'] == '已处理-加积分' && $status != '已处理-加积分'){
				echo 1;
                $type = $this->db->get('user_score', 'us_type', ['us_ue_id'=>$param['us_ue_id'], 'us_u_id'=>$param['us_u_id'], 'ORDER'=>['us_id'=>'DESC']]);
                if($type){
                    $param['us_type'] = $type;
                    $param['us_remark'] = '状态改变减去积分';
                    $this->updateUserScore($param,'-');
                }
            }
            //把已处理-加积分改为已处理加积分，积分有可能存在变化
            if($data['ue_status'] == '已处理-加积分' && $status == '已处理-加积分'){
                $type = $this->db->get('user_score', 'us_type', ['us_ue_id'=>$param['us_ue_id'], 'us_u_id'=>$param['us_u_id'], 'ORDER'=>['us_id'=>'DESC']]);
                if($type){
                    $param['us_type'] = $type;
                    $temp = $param;
                    $param['us_remark'] = '状态改变减去积分';
					
                    $this->updateUserScore($param,'-');
                    $this->updateUserScore($temp);
                }
            }
            //把不是已处理加积分的改为已处理加积分
            if($data['ue_status'] != '已处理-加积分' && $status == '已处理-加积分'){
                $this->updateUserScore($param);
            }
        }
		$this->db->update('user_error',['ue_status_remark' => $ue_status_remark,'ue_status' => $status,'ue_adm_id'=>getOpuser(),'ue_done_time'=> $time,'ue_update_time' => $time],["ue_id"=>$param['us_ue_id']]);
		return [];
    }


   

    /**
     * @param $update
     * @param $id
     * @return 成功
     */
    public function updateUserBehaviorLog($update,$id)
    {
//        $updateArr = array();
//        foreach ($update as $key => $value){
//            if($key !== 'is_car'){
//                $updateArr[] = sprintf("%s = CONCAT('%s',%s)",$key,$value,$key);
//            }else{
//                $updateArr[] = sprintf("%s = '%s')",$key,$value);
//            }
//        }
//        var_dump($updateArr);exit();

        return $this->db->update('user_behavior_log',$update,['id'=>$id]);
    }

	 /**
     * 添加用户
     * @return array
     */
    public function addUser($data)
    {
        $this->db->Begin();
		$data['u_password_time'] = getNowTime();
        $result = $this->db->insert('user',$data);
        $uId = $this->db->id();
        $flag = $this->db->insert('user_link_role',[
            'ult_u_id' => $uId,
            'ult_ur_id' => 26
        ]);
        $this->db->End();
        return true;
    }


    /**
     * @param $data
     * @return mixed
     */
    public function addUserBehaviorLog($data)
    {
        $result = [
            'date' => $data['date'],
            'time' => $data['time'],
            'u_id' => $data['u_id'],
            'mobile' => $data['mobile'],
            'ip' => $this->getIp(),
            'interface' => $data['interface'],
            'content' => $data['content'],
            'remark' => empty($data['remark'])? '': $data['remark'],
            'new_code' => $data['new_code'],
            'part_category' => $data['part_category'],
            'is_car' => $data['is_car'],
            'session_id' => $data['session_id'],
        ];
        $temp = $this->getIpLookup($result['ip']);
        $result['ip_province'] = $temp['2'];
        $result['ip_city'] = $temp['3'];
        $this->db->insert('user_behavior_log',$result);
        return $this->db->id();
    }

    private function getIp()
	{
        $realip = '';
        $unknown = 'unknown';
        if (isset($_SERVER)){
            if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                foreach($arr as $ip){
                    $ip = trim($ip);
                    if ($ip != 'unknown'){
                        $realip = $ip;
                        break;
                    }
                }
            }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){
                $realip = $_SERVER['REMOTE_ADDR'];
            }else{
                $realip = $unknown;
            }
        }else{
            if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){
                $realip = getenv("HTTP_CLIENT_IP");
            }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){
                $realip = getenv("REMOTE_ADDR");
            }else{
                $realip = $unknown;
            }
        }
        $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
        return $realip;
    }

    private function getIpLookup($ip = '')
	{
        if(empty($ip)){
            $ip = $this->getIp();
        }
        $ip2region = new \Ip2Region();
        $info = $ip2region->memorySearch($ip);
        return explode('|',$info['region']);
    }


    /**
     * @param $uid
     * @return array|成功赋值并返回true|null
     */
    public function getUserByUid($uid)
    {
        return $this->db->get('user', '*', ['u_id'=>$uid]);
    }


    /**
     * 编辑会员表信息
     * @param array $data  带key为u_id 的数组
     * @return array
     */
    public function edit(array $data):array 
    {
        $uId = $data['u_id'];
        if(is_numeric($data['u_score'])){
            $score = $this->db->get('user', 'u_score', ['u_id'=>$uId]);
            if($score != $data['u_score']){
                if(empty(trim($data['ue_remark']))){
                    return LibFc::ReturnData(false,'修改积分必须填写备注');
                }
                $rule = '+';
                $scores = $data['u_score'] - $score;
                if($data['u_score'] < $score){
                    $rule = '-';
                    $scores = $score - $data['u_score'];
                }
                $param = [
                    'us_type' => '',
                    'us_au_id' => $_SESSION['user']['user_id'],
                    'us_u_id' => $data['u_id'],
                    'us_ue_id' =>  0,
                    'us_score' => $scores,
                    'us_remark' => $data['ue_remark'],
                ];
                $this->updateUserScore($param,$rule);
            }
        }
        unset($data['ue_remark']);
        unset($data['us_score']);
        unset($data['u_id']);
        if($data['u_role_id']){
            $this->db->delete('user_link_role',["ult_u_id"=>$uId]);
            $this->db->insert('user_link_role',['ult_u_id'=>$uId,'ult_ur_id'=>$data['u_role_id']]);
        }
        unset($data['u_role_id']);
        return $this->set('user',$data,sprintf(' and u_id=%d',$uId));
    }

    /**
     * 添加用户查询访问次数
     * @param $type string 类型 vin/num/model/param
     * @return array
     */
    public function addAccess($type)
    {
        $ua_date = date('Ymd');
        $u_id = $_SESSION['cnuser']['u_id'];
        if(empty($u_id)) 
            return false;

        $row = $this->db->get('user_access', '*', ['ua_u_id'=>$u_id, 'ua_date'=>$ua_date]);
        if(empty($row)){
            $data = [
                'ua_u_id'=>$u_id,
                'ua_date'=>$ua_date,
                'ua_vin'=> 0,
                'ua_number'=> 0,
                'ua_model'=>0,
                'ua_param'=>0
            ];
            $data['ua_'.$type] = 1;
            $this->db->insert('user_access',$data);
        }else{
            $data['ua_'.$type] = $row['ua_'.$type]+1;
            $this->db->update('user_access',$data, ['ua_u_id'=>$u_id, 'ua_date'=>$ua_date]);
        }
        return true;
    }
    /**
     * 是否允许访问
     * @param $type string 类型 vin/num/model/param
     * @return array
     */
    public function isAllowAccess($type)
	{
		$u_id = $_SESSION['cnuser']['u_id'];
        if(empty($u_id)) return false; 
		if(!\p::fieldhas('Z000', $type)) return false;
        $ua_date = date('Ymd');
        $row = $this->db->get('user_access', '*', ['ua_u_id'=>$u_id, 'ua_date'=>$ua_date]);
		return ($row['ua_'.$type] < \p::fieldval('Z000', $type.'_limit'));
    }

	/**
     * 是否允许访问
     * @param $type string 类型 vin/num/model/param
     * @return array
     */
    public function isAllowAccessEn($type)
	{
		$u_id = $_SESSION['cnuser']['u_id'];
        if(empty($u_id)) return false; 
		if(!\p::fieldhas('Y000', $type)) return false;
        $ua_date = date('Ymd');
        $row = $this->db->get('user_access', '*', ['ua_u_id'=>$u_id, 'ua_date'=>$ua_date]);
		return ($row['ua_'.$type] < \p::fieldval('Y000', $type.'_limit'));
    }
   
	public function unbindWx($uid)
	{
		$this->db->update('user', ['u_wx_unionid'=>'', 'u_wx_info'=>''], ['u_id'=>$uid]);
		return [];
	}


	  /**
     * 登录
     * @return array
     */
    public function loginByAny($type, $dataArr)
    {
		$filed = ['u_id', 'u_mb', 'u_status','u_project_ids'];
		if($type == 'pass')
		{
			$filed[] = 'u_password';
		    $row = $this->db->get('user', $filed, ['u_mb'=>$dataArr['mb']]);
			if(!empty($row) && strcmp($row['u_password'],$this->pass($dataArr['pass']))===0){
				if(!empty($dataArr['u_wx_info'])) $this->bindWx($row['u_id'], $dataArr['u_wx_info']);
				return $row;
			}elseif(!empty($row) && strcmp($row['u_password'],$this->pass($dataArr['pass']))!==0) {
				return ['msg' => '密码错误', 'code'=>0];
			}else {
				return ['msg' => '账号不存在', 'code'=>0];
			}
		}
		else if($type == 'weixin')
		{
			$where = [
			   'u_wx_unionid'=>$dataArr['unionid']
		    ];
			$row = $this->db->get('user', $filed, $where);
			if(!empty($row)) return $row;
			return ['msg' => '尚未绑定账号', 'code'=>0];
		}
    }

	public function bindWx($uid, $u_wx_info)
	{
		$wxArr = json_decode(base64_decode($u_wx_info), true);
		if(!empty($wxArr['unionid']))
		{
			$this->db->Begin();
			$this->db->update('user', ['u_wx_unionid'=>$wxArr['unionid'], 'u_wx_info'=>json_encode($wxArr)], ['u_id'=>$uid]);
			$this->db->update('user', ['u_wx_unionid'=>'', 'u_wx_info'=>''], ['u_id[!]'=>$uid, 'u_wx_unionid'=>$wxArr['unionid']]);
			$this->db->End();
			return true;
		}
		return ['msg' => '绑定失败', 'code'=>0];
	}

	public function getHistory($uid, $type)
	{
		$arr = [];
		if(!empty($uid))
		{
			switch($type)
			{
				case 'vin': 
					$sql = sprintf("select distinct left(content, 17) as val, max(remark) info from user_behavior_log where u_id=%d and interface='vin号' group by val order by id desc limit 10", $uid);
					$arr = $this->db->query($sql)->fetchAll();
					//if(!empty($rows)) $arr = array_column($rows, 'val');
				break;
                case 'gsp':
                    $sql = sprintf("select distinct content as val, max(remark) info from user_behavior_log where u_id=%d and interface='GSP No.' group by val order by id desc limit 10", $uid);
					$arr = $this->db->query($sql)->fetchAll();
                break;
                case 'oe':
                    $sql = sprintf("select distinct content as val, max(remark) info from user_behavior_log where u_id=%d and interface='OE No.' group by val order by id desc limit 10", $uid);
					$arr = $this->db->query($sql)->fetchAll();
                break;
			}
		}
		return $arr;
	}

	public function setUserScore($dataArr)
	{
		$row = $this->db->get('user', '*', ['u_id'=>$dataArr['u_id']]);
		if(!empty($row) && $row['u_score'] != $dataArr['u_score'])
		{
			if(empty(trim($dataArr['ue_remark']))){
				return LibFc::ReturnData(false,'修改积分必须填写备注');
			}
			$rule = '+';
			$scores = $dataArr['u_score'] - $row['u_score'];
			if($dataArr['u_score'] < $row['u_score']){
				$rule = '-';
				$scores = $row['u_score'] - $dataArr['u_score'];
			}
			$datetime = getNowTime();
			$opuser = getOpuser();
			$param = [
				'us_type' => '',
				'us_au_id' => $opuser,
				'us_u_id' => $dataArr['u_id'],
				'us_ue_id' =>  0,
				'us_score' => $scores,
				'us_remark' => $dataArr['ue_remark'],
			];
			$this->updateUserScore($param,$rule);
		}
		return [];
	}

	public function changeUserStatus($uids, $dataArr)
	{
		$set = [
			'u_status'=>$dataArr['u_status'],
			'u_adm_au_id'=>getOpuser(),
			'u_update_time'=>getNowTime()
		];
		if(!empty($dataArr['u_remark']))
			$set['u_remark'] = $dataArr['u_remark'];
		$this->db->update('user', $set, ['u_id'=>$uids]);
		return [];
	}


	public function changeUserPower($uids, $roleIds)
	{
		$this->db->begin();
		$this->db->delete('user_link_role',['ult_u_id'=>$uids]);      
		foreach($uids as $uid)
		{
			foreach($roleIds as $role)
			{
				$this->db->insert('user_link_role', ['ult_u_id'=>$uid, 'ult_ur_id'=>$role]);
			}
		}
	    $this->db->end();
		return [];
	}

	
	//加入访问日志，含访问限制检测
	public function addUseLehaviorLog($param, $from)
	{
		$u_id = $_SESSION['cnuser']['u_id'];
		$u_mb = $_SESSION['cnuser']['u_mb'];
		$date = date('Ymd');
		if($from == 'en')
		{
			$interfaceArr = [
				'engspnum'=>'GSP No.',
				'enoenum'=>'OE No.',
				'enmodel'=>'车型',
			];
			$pwcode = 'Y000';
			$type = $param['type'];
			if(empty($u_id) || !\p::fieldhas($pwcode, $type)) 
				return ['isAllow'=>false, 'isAllowTitle'=>'No access'];

			$access = $this->db->get('user_access', '*', ['ua_u_id'=>$u_id, 'ua_date'=>$date]);
			if(empty($access))
			{
				$this->db->insert('user_access', ['ua_u_id'=>$u_id,'ua_date'=>$date]);
			}
			switch($type)
			{
				case 'engspnum': 
				case 'enoenum': 
					$unikey = ['number'=>formatNum($param['number'])];
					$content = $param['number'];
				break;
				case 'enmodel': 
					$fileds = ['mk_name','mm_name','mm_disp','year','mm_drive_type','mm_fuel','mm_kw','mm_hp','mm_body','pcat_name','cat_name'];
					$unikey = [];
					foreach($fileds as $filed)
					{
						if(!empty($param[$filed]))
							$unikey[] = trim($param[$filed]);
					}
					$content = implode(' ', $unikey);
				break;
			}

			//查询当天是否查询过
			$unikey['type'] = $type;
			$unikey = md5(json_encode($unikey));
			$chk = $this->db->get('user_behavior_log', 'id', ['u_id'=>$u_id, 'date'=>$date, 'from'=>$from, 'unikey'=>$unikey]);
			if(!empty($chk))
				return ['isAllow'=>true, 'isAllowTitle'=>''];

			if($access['ua_'.$type] >= \p::fieldval($pwcode, $type.'_limit'))
			{
				return ['isAllow'=>false, 'isAllowTitle'=>'Number of queries limit exceeded.'];
			}
			
			$ip = $this->getIp();
			$ipArr = $this->getIpLookup($ip);
			$logArr = [
				'date' =>$date,
				'time' =>date('H:i:s'),
				'u_id' =>$u_id,
				'mobile' =>$u_mb,
				'ip' => $ip,
				'interface' =>$interfaceArr[$type],
				'content' => $content,
				'remark' => empty($param['remark'])? '': $param['remark'],
				'new_code' =>  empty($param['new_code'])? '': $param['new_code'],
				'part_category' =>  empty($param['part_category'])? '': $param['part_category'],
				'is_car' =>  empty($param['is_car'])? '': $param['is_car'],
				'session_id' => session_id(),
				'ip_province'=>$ipArr['2'],
				'ip_city'=>$ipArr['3'],
				'unikey'=>$unikey,
				'from'=>$from
			];
			$this->db->insert('user_behavior_log', $logArr);
			$this->db->update('user_access',['ua_'.$type=>raw('ua_'.$type.'+1')], ['ua_u_id'=>$u_id,'ua_date'=>$date]);
			//用户地区统计
			$this->addSiteTj($from, 'ip', $ip);
			
			//查询车型+号码 国际目录 一天超过50次的发消息给admin gsp.admin
			$row = $this->db->get('user_access', ['ua_enoenum', 'ua_engspnum', 'ua_enmodel'], ['ua_u_id'=>$u_id,'ua_date'=>$date]);
			$count = (int) $row['ua_enoenum'] + $row['ua_engspnum'] + $row['ua_enmodel'];
			if($count == 50)
			{
				$ip = $this->getIp();
				$time = getNowTime();
				$msg = [
					'amsg_type'=> 3,
					'amsg_title'=> '国际目录查询预警',
					'amsg_body'=> $u_mb.'使用IP: '.$ip.'在'.$time.'查询达到'.$count.'次',
					'amsg_url'=> '',
					'amsg_urltitle'=>'',
				];
				makeOne(\model\message::class)->send(\mvc::$cfg['warnMsgUser'], $msg);
			}
			return ['isAllow'=>true, 'isAllowTitle'=>''];
		}
		else if($from == 'cn')
		{
			$isAllowTitle = '';
			$interfaceArr = [
				'vin'=>'vin号',
				'number'=>'号码',
				'param'=>'参数',
				'model'=>'车型',
			];
			
			$pwcode = 'Z000';
			if(!empty($param['vin']))
			{
				$param['type'] = 'vin';
				$isAllowTitle = 'VIN查询';
				$unikey = ['vin'=>formatNum($param['vin'])];
				$content = $param['vin'];
			}
			else if(empty($param['vin']) && !empty($param['mod3_id']))
			{
				$param['type'] = 'model';
				$isAllowTitle = '车型查询';
				$unikey = ['model'=>formatNum($param['mod3_id'])];
				$sql = sprintf("select * from m_cn_model where mod3_id =%d", $param['mod3_id']);
				$data = $this->db->query($sql)->fetchAll();
				$content = $data[0]['make_name'].' '.$data[0]['mod2_name'].' '.$data[0]['mod3_name'];
			}
			else if(!empty($param['number']))
			{
				$param['type'] = 'number';
				$isAllowTitle = '号码查询';
				$unikey = ['number'=>formatNum($param['number'])];
				$content = $param['number'];
			}
			else if(!empty($param['ppv']))
			{
				$param['type'] = 'param';
				$isAllowTitle = '参数查询';
				$unikey = $param['ppv'];
				$content = $param['content'];
			}

			$type = $param['type'];
			if(empty($u_id) || !\p::fieldhas($pwcode, $type)) 
				return ['isAllow'=>false, 'isAllowTitle'=>'无权查询权限'];

			$access = $this->db->get('user_access', '*', ['ua_u_id'=>$u_id, 'ua_date'=>$date]);
			if(empty($access))
			{
				$this->db->insert('user_access', ['ua_u_id'=>$u_id,'ua_date'=>$date]);
			}
			//查询当天是否查询过
			$unikey['type'] = $type;
			$unikey = md5(json_encode($unikey));
			$chk = $this->db->get('user_behavior_log', 'id', ['u_id'=>$u_id, 'date'=>$date, 'from'=>$from, 'unikey'=>$unikey]);
			if(!empty($chk))
				return ['isAllow'=>true, 'isAllowTitle'=>$isAllowTitle];

			if($access['ua_'.$type] >= \p::fieldval($pwcode, $type.'_limit'))
			{
				return ['isAllow'=>false, 'isAllowTitle'=>$isAllowTitle];
			}
			
			$ip = $this->getIp();
			$ipArr = $this->getIpLookup($ip);
			$logArr = [
				'date' =>$date,
				'time' =>date('H:i:s'),
				'u_id' =>$u_id,
				'mobile' =>$u_mb,
				'ip' => $ip,
				'interface' =>$interfaceArr[$type],
				'content' => $content,
				'remark' => empty($param['remark'])? '': $param['remark'],
				'new_code' =>  empty($param['new_code'])? '': $param['new_code'],
				'part_category' =>  empty($param['part_category'])? '': $param['part_category'],
				'is_car' =>  empty($param['is_car'])? '': $param['is_car'],
				'session_id' => session_id(),
				'ip_province'=>$ipArr['2'],
				'ip_city'=>$ipArr['3'],
				'unikey'=>$unikey,
				'from'=>$from
			];
			$this->db->insert('user_behavior_log', $logArr);
			$this->db->update('user_access',['ua_'.$type=>raw('ua_'.$type.'+1')], ['ua_u_id'=>$u_id,'ua_date'=>$date]);
			//用户地区统计
			$this->addSiteTj($from, 'ip', $ip);
			return ['isAllow'=>true, 'isAllowTitle'=>''];
		}
		return ['isAllow'=>false, 'isAllowTitle'=>'Number of queries limit exceeded.'];
	}

	//加入数据统计  $val1 int|array 为数组时，多条记录
	public function addSiteTj($site, $type, $val1, $val2='', $val3 = [], $month = '', $count = 1)
	{
		$val1s = is_array($val1)? $val1: [$val1];
		if(empty($month)) $month = date('Ym');
		foreach($val1s as $val1)
		{
			if($type == 'ip' && empty($val3) && !empty($val1))
			{
				$temp = $this->getIpLookup($val1);
				$val3 = [
					'country'=>!empty($temp[0])? $temp[0]: 'unknown',
					'province'=>!empty($temp[2])? $temp[2]: 'unknown',
				];
				if($site == 'cn' && empty($val2)){
					$val2 = $val3['country'] == '中国'? $val3['province']: $val3['country'];
				}else if($site == 'en' && empty($val2)){
					$val2 = $val3['country'];
				}
			}
			$val3 = is_array($val3)? json_encode($val3, JSON_UNESCAPED_UNICODE): '[]';
			$where = [
				'st_month'=>$month,
				'st_site'=>$site,
				'st_type'=>$type,
				'st_val1'=>$val1,
				'st_val2'=>$val2
			];
			$chk = $this->db->get('gsp_site_tj', ['st_count', 'st_val3'], $where);
			if(!empty($chk)){
				$this->db->update('gsp_site_tj', ['st_count'=>$chk['st_count']+1, 'st_val3'=>$val3], $where);
			}else{
				$addArr = [
					'st_month'=>$month,
					'st_site'=>$site,
					'st_type'=>$type,
					'st_val1'=>$val1,
					'st_val2'=>$val2,
					'st_count'=>$count > 0? $count: 1,
					'st_val3'=>$val3,
				];
				$this->db->insert('gsp_site_tj', $addArr);
			}
		}
		return true;
	}
	
	//将老的统计数据纳入到新统计中
	public function formatOldToTj()
	{
		ini_set('memory_limit', \mvc::$cfg['bigtable_memory_limit']);
		set_time_limit(0);
		$this->db->begin();
		$sql = "SELECT DATE_FORMAT(`date`, '%Y%m') `month`, `ip`, `from`, COUNT(*) total FROM user_behavior_log GROUP BY `month`, ip, `from` ORDER BY DATE";
		$rows = $this->db->query($sql)->fetchAll();
		foreach($rows as $row)
		{
			$this->addSiteTj($row['from'], 'ip', $row['ip'], '', [], $row['month'], $row['total']);
		}
		$this->db->end();
		echo 'ok';
	}


    public function collect($u_id,$cate_id)
    {
        $old = $this->db->get('user',['u_id','u_mycate_ids'],['u_id'=>$u_id]);
        if($old){
           $oldcate = explode(',',$old['u_mycate_ids']);
           if (in_array($cate_id, $oldcate)) {
            // 如果值在数组中，删除它
                $index = array_search($cate_id, $oldcate);
                if ($index !== false) {
                    unset($oldcate[$index]);
                }
            } else {
                // 如果值不在数组中，添加它
                $oldcate[] = $cate_id;
            }
            // 重新索引数组
            $oldcate = array_filter(array_values($oldcate));
            $this->db->update('user',['u_mycate_ids'=>implode(',',$oldcate)],['u_id'=>$u_id]);
        }
        return true;
    }
}