<?php

use Clouding\Presto\Presto;
class SSdataModel extends CI_Model
{
    public $token="cIP5Fp1BewhNWWDVH90Sksb1QPXctMDhDWXK5ot5ngUzUay3aROj1GzBs6hoBuoo";
    public $groupListUrl ="http://172.22.107.114:8992/open/user-cluster-list";
    public $projectId = 5;
    public $groupListInfo =[];
    public $shushuHost = 'http://172.22.107.114:8992';

    public $sqlUrl = "172.22.107.113:8082";
    public $catalog = 'hive';
    public $schema ="ta";
    function __construct()
    {
//        $this->token =   $this->config->item('ss_token');
//        $this->projectId=   $this->config->item('ss_group_projectId');
//        $this->groupListUrl = $this->config->item('ss_group_list_url');
//        $this->sqlUrl = $this->config->item('ss_db_data_url');
        # code...
    }
    function sendJosnPost($url,$dataArr){
        $data_string = json_encode($dataArr);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    function getGroupList(){
        $dataArr = [
            "clusterCatalog"=>"catalog_cluster",
            "clusterTypes"=>["cluster_by_dynamic_condition","cluster_by_static_condition","cluster_by_result"],
            "pagerHeader"=>["pageNum"=>1,"pageSize"=>1000],
            "projectId"=>$this->projectId,
        ];
        $url = $this->groupListUrl."?token={$this->token}";
        oo::logs()->commlog($dataArr, 'ssGroupList.log');
        $ret = $this->sendJosnPost($url,$dataArr);
        $retData = json_decode($ret,true);
        if(!empty($retData)&&is_array($retData)){
            $this->groupListInfo = $retData['data']['userClusters'];
        }
        return $this->groupListInfo;
    }

    function getUidListByGroupName($cluster_name){
        $presto = new Presto();

        $presto->addConnection([
            'host' => $this->sqlUrl,
            'catalog' => $this->catalog,
            'schema' => $this->schema,
        ]);
        $presto->setAsGlobal();
        $sql = 'select "#account_id" from v_user_'.$this->projectId.' where "#user_id" in (SELECT "#user_id" from user_result_cluster_'.$this->projectId.' where cluster_name=\''.$cluster_name.'\') ';
        $posts = $presto->connection()->query($sql)->get();
        if(!empty($posts)&&is_array($posts)){
            foreach ($posts as $key => $value) {
                if($value[0]){
                    $ret[] = $value[0];
                }
            }
        }
        return $ret;
    }
    function checkRefreshStatusByGroupName($cluster_name){
        $url = "{$this->shushuHost}/open/user-cluster-refresh-progress-by-name?token={$this->token}&projectId={$this->projectId}&clusterName={$cluster_name}";
        $response = file_get_contents($url);
        return $response;
    }

    //根据uid给用户分配分组
    public function updateSGroup($uid){
        if(empty($uid)){
            return false;
        }
        $uGroupArr = [];
        $config = oo::commonOprModel('config')->getUserGroupConfigByCid(5);
        foreach ($config as $v){

            $key = okeys::userListSSGroup($v['groupId']);
            $res = oo::commonOprRedis('statistics')->zScore($key,$uid);

            if($res!==false){
                array_push($uGroupArr,$v['id']);
            }
        }
        $regSSgroup = oo::commonOprModel('member')->regSSgroup($uid);
        if($regSSgroup){
            $uGroupArr = array_merge($uGroupArr,$regSSgroup);
            $uGroupArr = array_filter($uGroupArr);
            $uGroupArr = array_unique($uGroupArr);
        }
        if($uGroupArr){
            $group = implode(',',$uGroupArr);
            oo::commonOprModel('member')->updateUserDynamicsData($uid,["groupId3"=>$group]);
        }else{
            oo::commonOprModel('member')->updateUserDynamicsData($uid,["groupId3"=>"0"]);
        }
        $file =  'deBUG/userShushuGroups/'.date('Ymd') . '.log';//存储文件夹
        self::createDir($file);
        file_put_contents($file, "{$uid}:$group" . PHP_EOL, FILE_APPEND);
    }

    public static function createDir($file){
        $dir = dirname($file);
        if(!is_dir($dir)){
            mkdir($dir, 0777, true);
        }
    }
}