<?php
namespace Cmbc\Api;

use Cmbc\Setting;

abstract class Core
{
	protected $param = array();
	protected $data = array();
	protected $setting = null;
	protected $error = array();
	protected $method = 'post';
	abstract protected function init();
	abstract public function request($request, $tool = false);
	abstract public function response($response);

	public function __construct(Setting $setting)
	{
		$this->setting = $setting;
		$this->init();
		$appid = explode('|', $this->setting->getAppId());
		$this->param['appId'] = $appid[0];
		$this->param['mhtSubAppId'] = $appid[1];
		//$this->param['mhtSubMchId'] = $this->setting->getSubMchId();
	}

	protected function setParam($key, $default = false, $isMust = true)
	{
		if (!$this->data) {
			$this->setError('param data is not exists');
		} else {
			if (!isset($this->data[$key]) && $default) {
				$this->data[$key] = $default;
			}
			if (isset($this->data[$key])) {
				if (!$this->data[$key] || $this->data[$key] == 0) {
					if ($default) {
						$this->data[$key] = $default;
					}
				}
				if ($isMust == true && !$this->data[$key] && $this->data[$key] != 0) {
					$this->setError('param data ['.$key.'] is not value');
				}
				$this->param[$key] = $this->data[$key];
			}
		}

		return $this;
	}

	protected function createSignature($type = 'MD5')
	{
		ksort($this->param);
		$signature_string = '';
		foreach ($this->param as $k => $v) {
			if ($v || $v == 0) {
				$signature_string .= $k . '=' . $v . '&';
			}
		}
		$signature_string = substr($signature_string, 0, -1);
		$method = strtoupper($type);
		$secret = $method($this->setting->getAppSecret());
		return $method($signature_string . '&' . $secret);
	}

	protected function curl()
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $this->api);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		if ($this->method == 'post' && $this->param) {
			curl_setopt($curl, CURLOPT_POST, 1);

			$string = '';
			foreach ($this->param as $k => $v) {
				if ($v || $v == 0) {
					$string .= $k . '=' . $v . '&';
				}
			}
			$string = substr($string, 0, -1);

			//\Dever::log('招商银行支付请求' . '||' . $this->api . '||' . $string, 'pay');
			curl_setopt($curl, CURLOPT_POSTFIELDS, $string);
		}
		
		$data = curl_exec($curl);
		curl_close($curl);
		parse_str($data, $result);
		if (isset($result['responseCode']) && $result['responseCode'] == 'A002') {
			# 失败
			$this->setError($result['responseMsg']);
			return false;
		}
		return $result;
	}

	protected function setError($msg)
	{
		$this->error[] = $msg;
	}

	protected function getError()
	{
		$number = count($this->error);
		if ($number > 0) {
			$msg = $this->error[0];
			return $msg;
		}
		return false;
	}
}