<?php namespace Connect\Lib\Func;
use Dever;
class Base
{
    protected $connect;
    protected $info;
    protected $domain;
    protected $param = array();

    # 设置基本信息
    protected function setting($type, $cate_id, $channel, $param = array())
    {
        $this->connect = Dever::db('info', 'connect')->find($channel['connect_id']);
        if (!$this->connect) {
            return false;
        }
        $this->connect['channel_id'] = $channel['id'];
        $this->connect['host'] = $channel['host'];
        $this->connect['appkey'] = $channel['appkey'];
        $this->connect['appsecret'] = $channel['appsecret'];
        $set = Dever::db('set', 'channel')->select(array('channel_id' => $channel['id']));
        $this->connect['set'] = array();
        if ($set) {
            foreach ($set as $k => $v) {
                $this->connect['set'][$v['key']] = $v['value'];
            }
        }
        $this->info = false;
        if ($cate_id) {
            $this->info = Dever::db($this->type, 'connect')->find(array('type' => $type, 'cate_id' => $cate_id, 'connect_id' => $this->connect['id']));
        }
        if (!$this->info) {
            $this->info = Dever::db($this->type, 'connect')->find(array('type' => $type, 'connect_id' => $this->connect['id']));
            if (!$this->info) {
                return false;
            }
        }
        $this->param = $param;
        return $this;
    }

    # 发起请求
    protected function curl($url = false)
    {
        if (!$url) {
            $url = $this->url();
        }
        $header = $body = array();
        $method = 'get';
        $json = false;
        if ($this->info['method'] == -1) {
            $this->info['method'] = $this->connect['method'];
            $this->info['post_method'] = $this->connect['post_method'];
        }
        if ($this->info['post_method'] == 2) {
            $method = 'file';
        } elseif ($this->info['method'] == 2) {
            $method = 'post';
        }
        if ($this->info['post_method'] == 3) {
            $json = true;
        }

        # 标准请求头
        $this->request($header, 'request_header', array('connect_id' => $this->connect['id']));
        # 标准请求体
        $this->request($body, 'request_body', array('connect_id' => $this->connect['id']));

        if (method_exists($this, 'requestHeader')) {
            $this->requestHeader($header);
        }
        if (method_exists($this, 'requestBody')) {
            $this->requestBody($body);
        }
        $this->sign($body);
        $response = Dever::curl($url, $body, $method, $json, $header)->result();
        $test = Dever::input('test');
        if ($test && $test == 1) {
            $result = array
            (
                'url' => $url,
                'header' => $header,
                'method' => $method,
                'json' => $json,
                'body' => $body,
                'response' => $response,
            );
            echo Dever::json_encode($result);die;
        }
        //$response = '{"code":1,"info":"ok","data":{"order":"Q202401037683854738260576","account":"15810090845","status":1}}';
        //$response = '{"status":0,"msg":"success","order_id":"24013117320741438be7f0b65a","product_id":20005,"price":104.1,"amount":100,"user_order":"C2024013193480488567061"}';
        //$response = '{"status":"0","msg":"success","balance":"100.0000","frozen_balance":"9.9800"}';
        $response = $this->response($response);
        $response['request'] = $body;
        return $response;
    }

    # 处理url
    protected function url()
    {
        if (strstr($this->info['uri'], 'http')) {
            $this->connect['host'] = '';
        }
        $uri = Dever::db('api_uri', 'connect')->select(array('api_id' => $this->info['id']));
        if ($uri) {
            $path = array();
            $param = array();
            foreach ($uri as $k => $v) {
                $v['value'] = $this->value(array(), $v['key'], $v['value']);
                if ($v['type'] == 1) {
                    $path[] = $v['value'];
                } elseif ($v['type'] == 2) {
                    $path[] = $v['key'] . '/' . $v['value'];
                } elseif ($v['type'] == 3) {
                    $path[] = $v['key'] . '=' . $v['value'];
                } elseif ($v['type'] == 4) {
                    $param[] = $v['value'];
                } elseif ($v['type'] == 5) {
                    $param[] = $v['key'] . '=' . $v['value'];
                }
            }
            if ($path) {
                $this->info['uri'] .= implode('/', $path);
            }
            if ($param) {
                if (!strstr($this->info['uri'], '?')) {
                    $this->info['uri'] .= '?';
                }
                $this->info['uri'] .= implode('&', $param);
            }
        }
        return $this->domain = $this->connect['host'] . $this->info['uri'];
    }

    # 获取请求参数
    protected function request(&$data, $table, $where)
    {
        $body = Dever::db($table, 'connect')->select($where);
        if ($body) {
            foreach ($body as $k => $v) {
                $value = $this->value($data, $v['key'], $v['default'], $v['type']);
                if ($value) {
                    $data[$v['key']] = $value;
                }
            }
        }
    }

    # 数据响应格式处理
    protected function response($response)
    {
        if ($this->connect['response_type'] == 1) {
            $response = $this->filter($response);
            return array
            (
                'status' => 1,
                'msg' => 'ok',
                'response' => false,
                'request' => array(),
                'data' => $response,
            );
        }
        if ($this->connect['response_type'] == 2) {
            $response = Dever::json_decode($response);
        } elseif ($this->connect['response_type'] == 3) {
            $response = (array) simplexml_load_string($response);
        } else {
            if (strstr($response, ',')) {
                $response = explode(',', $response);
            } elseif (strstr($response, ' ')) {
                $response = explode(' ', $response);
            } elseif (strstr($response, '|')) {
                $response = explode('|', $response);
            } else {
                $response = explode("\n", $response);
            }
        }
        $msg = '';
        $status = 2;
        if (isset($response[$this->connect['response_code']])) {
            $code = $response[$this->connect['response_code']];
            $code = Dever::db('response_code', 'connect')->find(array('connect_id' => $this->connect['id'], 'value' => $code));
            if ($code && $code['type'] == 1) {
                $status = 1;
            }
        }
        $msg = $response[$this->connect['response_msg']] ?? 'no';
        $data = '';
        if (strstr($this->connect['response_data'], ',')) {
            $temp = explode(',', $this->connect['response_data']);
            foreach ($temp as $k => $v) {
                if (isset($response[$v])) {
                    $data = $response[$v];
                    break;
                }
            }
        } elseif (strstr($this->connect['response_data'], '.')) {
            $temp = explode('.', $this->connect['response_data']);
            $data = isset($response[$temp[0]][$temp[1]]) ? $response[$temp[0]][$temp[1]] : (isset($response[$temp[0]]) ? $response[$temp[0]] : false);
        } else {
            $data = $response[$this->connect['response_data']] ?? $response;
        }
        if ($data) {
            if (method_exists($this, 'responseHandle')) {
                $this->responseHandle($data);
            }
        }
        return array
        (
            'status' => $status,
            'msg' => $msg,
            'response' => $response,
            'request' => array(),
            'data' => $data,
        );
    }

    protected function sign(&$body)
    {
        if ($this->connect['sign_method'] == 1) {
            return;
        }
        if (!$this->connect['sign_name']) {
            $this->connect['sign_name'] = 'signature';
        }
        $sign = array();
        if ($this->info['sign_col']) {
            $col = explode('+', $this->info['sign_col']);
            foreach ($col as $k => $v) {
                $sign[$v] = $this->value($body, $v, $v, 1);
            }
        } elseif ($this->connect['sign_col']) {
            $col = explode('+', $this->connect['sign_col']);
            foreach ($col as $k => $v) {
                $sign[$v] = $this->value($body, $v, $v, 1);
            }
        } else {
            $sign = $body;
        }

        if ($this->connect['sign_appsecret'] && $this->connect['sign_appsecret_location'] == 1) {
            $sign[$this->connect['sign_appsecret']] = $this->connect['appsecret'];
            if (isset($sign['api_product'])) {
                $sign[$this->connect['sign_appsecret']] = sha1($this->connect['appkey'] . '|' . $this->connect['appsecret']);
            }
        }

        if ($this->connect['sign_sort'] == 2) {
            ksort($sign);
        }

        $string = '';
        foreach ($sign as $k => $v) {
            if ($this->connect['sign_empty'] == 2 && !$v) {
                continue;
            }
            if ($this->connect['sign_encode'] == 2 && strstr($v, 'http')) {
                $v = urlencode($v);
                if (isset($body[$k])) {
                    $body[$k] = $v;
                }
            }
            if ($this->connect['sign_type'] == 1) {
                $string .= $v;
            } elseif ($this->connect['sign_type'] == 2) {
                $string .= $k . '=' . $v . '&';
            } elseif ($this->connect['sign_type'] == 3) {
                $string .= $k . $v;
            } elseif ($this->connect['sign_type'] == 4) {
                $string .= $k . $v . '&';
            }
        }

        $sign = rtrim($string, '&');

        if ($this->connect['sign_appsecret'] && $this->connect['sign_appsecret_location'] == 2) {
            if ($this->connect['sign_type'] == 1) {
                $sign .= $this->connect['appsecret'];
            } elseif ($this->connect['sign_type'] == 2) {
                $sign .= '&' . $this->connect['sign_appsecret'] . '=' . $this->connect['appsecret'];
            } elseif ($this->connect['sign_type'] == 3) {
                $sign .= $this->connect['sign_appsecret'] . $this->connect['appsecret'];
            } elseif ($this->connect['sign_type'] == 4) {
                $sign .= '&' . $this->connect['sign_appsecret'] . $this->connect['appsecret'];
            }
        }

        # 如果是ssl 这里需要处理一下，后续处理吧

        if ($this->connect['sign_method'] == 2) {
            $sign = md5($sign);
        } elseif ($this->connect['sign_method'] == 3) {
            $sign = hash("sha256", $sign);
        } elseif ($this->connect['sign_method'] == 4) {
            $sign = sha1($sign);
        }

        if ($this->connect['sign_after'] == 2) {
            $sign = strtoupper($sign);
        } elseif ($this->connect['sign_after'] == 2) {
            $sign = strtolower($sign);
        }

        $body[$this->connect['sign_name']] = $sign;


        return $sign;
    }

    protected function value($data, $key, $value, $type = 1)
    {
        $value = trim($value);

        if ($this->param && isset($this->param[$value])) {
            $value = $this->param[$value];
        } elseif ($data && isset($data[$value])) {
            $value = $data[$value];
        } elseif (isset($this->connect['set'][$value]) && $this->connect['set'][$value]) {
            $value = $this->connect['set'][$value];
        } elseif (isset($this->connect[$value]) && $this->connect[$value]) {
            $value = $this->connect[$value];
        } elseif ($value == 'notify') {
            $value = $this->createNotify($this->param['order_id'] ?? '');
        } elseif ($value == 'api_request') {
            $value = $data;
        } elseif ($value == 'timestamp') {
            $value = \Dever\Helper\Secure::timestamp();
        } elseif ($value == 'nonce') {
            $value = \Dever\Helper\Secure::nonce();
        } elseif ($value == 'token') {
            $value = $this->token(1, 'token');
        } elseif ($value == 'ticket') {
            $value = $this->token(2, 'ticket');
        } elseif ($a = strstr($value, '{') || strstr($value, '(')) {
            if ($a) {
                $func = function ($r) use($data) {
                    return $this->value($data, $r[1], $r[1]);
                };
                $value = preg_replace_callback('/{(.*?)}/', $func, $value);
            }
            $value = '$value = '.$value.';';
            eval($value);
        }

        if (!$value) {
            $key = trim($key);
            return Dever::input($key);
        }

        if ($type == 1 || $type == 100) {
            $value = (string) $value;
        } elseif ($type == 2 || $type == 200) {
            $value = (float) $value;
        } elseif ($type == 3 && is_array($value)) {
            $value = Dever::json_encode($value);
        } elseif ($type == 4) {
            $value = $this->encrypt($value);
        } elseif ($type == 300 && is_array($value)) {
            $value = Dever::json_decode($value);
        } elseif ($type == 400) {
            $value = $this->decrypt($value);
        }

        return $value;
    }

    protected function service($data)
    {
        # 转换处理
        $convert = Dever::db('convert', 'connect')->select(array('connect_id' => $this->connect['id']));

        $param = array();
        if ($convert) {
            if (isset($data[0])) {
                foreach ($data as $k1 => $v1) {
                    foreach ($convert as $k => $v) {
                        if (isset($data[$k1][$v['before']])) {
                            $param[$k1][$v['after']] = $data[$k1][$v['before']];
                        }
                    }
                }
            } else {
                foreach ($convert as $k => $v) {
                    if (isset($data[$v['before']])) {
                        $param[$v['after']] = $data[$v['before']];
                    }
                }
            }
        } else {
            $param = $data;
        }

        # 具体业务处理，这里先不做
        //Dever::load('channel/lib/service')->act($this->channel['id'], $this->info['service_id'], $this->type, $this->info['id'], $param);
        return $param;
    }

    protected function token($id = 1, $type = 'token')
    {
        return '';
        $db = Dever::db($type, 'connect');
        $data['connect_id'] = $connect['id'];
        $data['api_id'] = $api['id'];
        $info = $db->find($data);
        if ($info && time() - $info['mdate'] >= $info['expires']) {
            
        } elseif ($info) {
            return $info['value'];
        }
        $result = $this->init()->curl();
        if (isset($result[$type])) {
            $data['value'] = $result[$type];
            $data['expires'] = '7200';
            if (isset($result['expires'])) {
                $data['expires'] = $result['expires'];
            }
            if ($info) {
                $data['where_id'] = $info['id'];
                $db->update($data);
            } else {
                $db->insert($data);
            }
            return $result[$type];
        }
        return '';
    }

    protected function encrypt($value)
    {
        if ($this->connect['ssl_method'] && $this->connect['ssl_key']) {
            $value = openssl_encrypt($value, $this->connect['ssl_method'], $this->connect['ssl_key'], $this->connect['ssl_option'], $this->connect['ssl_iv']);
            if ($this->connect['ssl_after'] == 2) {
                $value = base64_encode($value);
            }
        }
        
        return $value;
    }

    protected function decrypt($value)
    {
        if ($this->connect['ssl_method'] && $this->connect['ssl_key']) {
            if (is_array($value)) {
                $value = Dever::json_encode($value);
            }
            $value = openssl_decrypt($value, $this->connect['ssl_method'], $this->connect['ssl_key'], $this->connect['ssl_option'], $this->connect['ssl_iv']);
            if ($this->connect['ssl_after'] == 2) {
                $value = base64_decode($value);
            }
        }
        
        return $value;
    }

    protected function public_encrypt()
    {
        $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
            chunk_split($this->nowpayPublickey, 64, "\n") .
            "-----END PUBLIC KEY-----\n";
        $output = '';
        openssl_public_encrypt($this->encryptKey, $output, $publicKey);
        return base64_encode($output);
    }
    
    protected function protected_decrypt($str)
    {
        $priKey = "-----BEGIN RSA protected KEY-----\n" .
            chunk_split($this->protectedKey, 64, "\n") .
            "-----END RSA protected KEY-----\n";
        $output = '';
        openssl_protected_decrypt(base64_decode($str), $output, $priKey);
        return $output;
    }

    protected function filter($data)
    {
        return preg_replace("/<!--[^\!\[]*?(?<!\/\/)-->/","",$data);
    }
}