<?php
namespace app\controller;

require_once app()->getRootPath().'vendor/autoload.php';
use app\BaseController;
use Neoxygen\NeoClient\ClientBuilder;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Log;

class CommonController extends BaseController
{

    // checkIsExistSession
    public function checkIslogin()
    {
        return Request::session('name') ?? false;
    }


    /**
     * Connect Neo4j
     * return Object
     */
    private  function connectNeo4j()
    {
        $client = ClientBuilder::create()
            //->addConnection('default', 'http', '59.110.24.172', 7474, true, 'neo4j', 'jm@123')
            ->addConnection('default', 'http', '120.46.136.62', 7474, true, 'neo4j', 'neo4j-pwd')
            ->setAutoFormatResponse(true)
            ->setDefaultTimeout(200)
            ->build();
        return $client;
    }

    private  function connectNeo4jWesternMedicine()
    {
        $client = ClientBuilder::create()
            ->addConnection('default', 'http', '124.70.100.133', 7474, true, 'neo4j', 'neo4j-pwd')
            ->setAutoFormatResponse(true)
            ->setDefaultTimeout(200)
            ->build();
        return $client;
    }


    /**
     * Create Node
     * @param $node  string
     * @param $label string
     * @param $data  array
     */
    public  function createNode($node , $label , $data)
    {
        $client     = $this->connectNeo4jWesternMedicine();
        $str		= json_encode($data , JSON_UNESCAPED_UNICODE);
        $singleData = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9]*)":/' ,'$1:' , $str); 	 // 替换key引号
        $query  	= "CREATE (". $node . ":" . $label . $singleData . ") RETURN $node";
        $query      = stripslashes($query);
        return $client->sendCypherQuery($query);
    }



    public function getRelationshipsByLable()
    {
        $client = $this->connectNeo4jWesternMedicine();
        $query  = "MATCH p=()-[r:SubordinateDepartment]->() RETURN p";
        $result   = $client->sendCypherQuery($query)->getResult();
        return $result;
    }



    /**
     * Select SingleNode
     * @param $node  string
     * @param $label string
     * @param $field string
     * @param $value string
     * return array
     */
    public  function getNodes($tag , $node , $label , $skip , $limit , $field = '' , $value = '' , $fields = [])
    {
        $client = $tag == 'zy' ? $this->connectNeo4j() : $this->connectNeo4jWesternMedicine();
        if($field) {
            $query  = "match (". $node . ":" . $label .")"."where $node . $field =~ '.*".$value.".*' ". " RETURN $node";
//			$result = $client->sendCypherQuery($query)->getResult()->getSingleNode();
//			return $result->getProperties($fields);
            $data = $client->sendCypherQuery($query)->getResult();
        } else {
            $query = "match (". $node . ":" . $label .") RETURN $node skip $skip limit $limit";
            $data  = $client->sendCypherQuery($query)->getResult();
        }

        foreach ($data->getNodes() as $key => $node){
            $datas[] = ['id' => $node->getId()];
        }

        $list   = array_column($p = $data->getTableFormat() , 'n');
        foreach ($list as $k => $value) {
            $list[$k]['id'] = $datas[$k]['id'];
        }

        $query1 = "MATCH (n:".$label.") RETURN count(n) as count";
        $count  = $client->sendCypherQuery($query1)->getResult()->getTableFormat();
        $list   = ['list' => $list , 'count' => $count[0]['count']];
        return $list;
    }


    // getNodeById
    public function getNodeById($zsk , $id , $tag = '')
    {
        $client = $zsk == 'zy' ? $this->connectNeo4j() : $this->connectNeo4jWesternMedicine();
        $query  = "MATCH (n) WHERE id(n)=$id RETURN n";
        $result = $client->sendCypherQuery($query)->getResult()->getSingleNode();
        if($tag) {
            return $result->getLabels();
        }
        $detail = $result->getProperties();
        $detail['id'] = $id;
        return $detail;
    }



    // set node
//	public  function setNode($node , $label , $filed , $value , $whereField = '', $whereValue = '', $tag = 2)
//	{
//		//  match(userd:Userd) where userd.name = "中文4" set userd.name = "修改测试" return userd;
//		$client = $this->connectNeo4j();
//
//		if(1 == $tag) {
//			$query  = "match (". $node . ":" . $label .") where ".$node.".".$whereField."='$whereValue' set $node.$filed='$value' RETURN $node";
//		} else {
//
//			$query  = "match (". $node . ":" . $label .") set $node.$filed='$value' RETURN $node";
//		}
//		return $client->sendCypherQuery($query);
//	}

//MATCH (r)
//WHERE id(r) = 501
//SET r.test = "testtest"

    public function setNode($query , $tag = 'zy')
    {
        $client = $tag == 'zy' ? $this->connectNeo4j() : $this->connectNeo4jWesternMedicine();
        $result = $client->sendCypherQuery($query);
        return $result;
    }


    // delete node
    public  function deleteNode()
    {

    }


    // remove node
    public function removeNode()
    {

    }


    public function checkPhone($phone)
    {
        return preg_match("/^1[3456789]{1}\d{9}$/", $phone) ?? false;
    }


    /**
     * Json Success
     */
    public function _json_succ($data = [] , $code = 0 , $msg = 'Success')
    {
        return json(
            [
                'code' => $code ,
                'msg'  => $msg  ,
                'data' => $data
            ]
        );
    }

    /**
     * Json error
     */
    public function _json_error($msg = '' , $code = 1 , $data = null)
    {
        return json(
            [
                'code' => $code ,
                'msg'  => $msg  ,
                'data' => $data
            ]
        );
    }



    /**
     * 发送短信
     */
    public function curlSmsSend($mobile , $code)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send.json");

        curl_setopt($ch, CURLOPT_HTTP_VERSION  , CURL_HTTP_VERSION_1_0 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);

        curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD  , 'api:key-194cc0004de341090bbbce1c14a27c8f');

        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => $mobile,'message' => '验证码：'.$code.'【铁壳测试】'));

        $res = curl_exec( $ch );
        curl_close( $ch );
        return $res;
    }


    /**
     * 订单号
     */
    protected function createOrderNum()
    {
        return date('Ymd') . str_pad(random_int(1 , 99999), 5 , '0' , STR_PAD_LEFT);
    }




    // ----------------------------------------------- 翻译模块 -----------------------------------------

    /**
     * 获取api调取验证token
     * 返回格式：string(93) "{"errcode":0,"msg":"success","data":{"authtoken":"03364a56aef9fbf63e0479d670e7fc4bef3f6dd9"}}"
     */
    protected function getAuthToken()
    {
        $authtoken = Cache::get('authtoken') ?? '';
        if( ! $authtoken ) {
            $params   = config('translate.user');
            $url      = config('translate.request_url.get_authtoken_url');
            $response = $this->curlPostRequest($url , $params);
            if( ! $response) {
                return $this->_json_error('请求失败！');
            }

            $result    = json_decode($response , true);
            $authtoken = $result['data']['authtoken'];
            /**
             * 设置缓存
             */
            Cache::set('authtoken' , $authtoken , config('translate.expire.authtoken_expire'));
            return $authtoken;
        }
        return $authtoken;
    }


    /**
     * 获取企业/个人信息
     */
    protected function profile()
    {
        $url = config('translate.request_url.get_profile_url');
        $response = $this->curlGetRequest($url);

        Log::info(__FUNCTION__.': ' . $response);

        if( ! $response) {
            return false;
        }
        $result = json_decode($response , true);
        return $result ?? '';
    }


    /**
     * curl get 请求
     */
    protected function curlGetRequest($url)
    {
        $authtoken = $this->getAuthToken();
        $curl_con  = curl_init();

        curl_setopt($curl_con, CURLOPT_URL , $url);
        curl_setopt($curl_con, CURLOPT_HEADER, false);
        curl_setopt($curl_con, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($curl_con, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_con, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_con, CURLOPT_FOLLOWLOCATION, true);             // 解决curl返回301

        curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                "Content-Type: application/json;charset=utf-8",
                "Authorization: Token $authtoken"
            )
        );

        $res    = curl_exec($curl_con);
        $status = curl_getinfo($curl_con);

        curl_close($curl_con);

        if (isset($status['http_code']) && 200 == $status['http_code']) {
            return $res;
        } else {
            return false;
        }
    }


    /**
     * curl post 请求
     */
    protected function curlPostRequest($url , $params , $authtoken = '')
    {
        $data     = json_encode($params , JSON_UNESCAPED_UNICODE);
        $curl_con = curl_init();

        curl_setopt($curl_con, CURLOPT_URL , $url);
        curl_setopt($curl_con, CURLOPT_HEADER, false);
        curl_setopt($curl_con, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl_con, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl_con, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_con, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl_con, CURLOPT_FOLLOWLOCATION, true);             // 解决curl返回301
        if($authtoken) {
            curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                    "Content-Type: application/json;charset=utf-8" ,
                    "Authorization: Token $authtoken"
                )
            );
        } else {
            curl_setopt($curl_con, CURLOPT_HTTPHEADER , array(
                    "Content-Type: application/json;charset=utf-8"
                )
            );
        }

        $res    = curl_exec($curl_con);
        $status = curl_getinfo($curl_con);
        curl_close($curl_con);

        if (isset($status['http_code']) && 200 == $status['http_code']) {
            return $res;
        } else {
            return false;
        }
    }

}
