<?php
namespace Pay\Yspay;
use Dever;
header("Content-Type:text/html;charset=utf-8");
Class Sign
{
	private $key = "o5ho739mgrphdm28g5rwx1nw";
	private $accesser_id = '2d9081bd7db8ad75017dbbe68981314f';
	private $url = 'https://yinshangpai.chinaums.com/self-contract-nmrs/interface/autoReg/';
	private $sign_type = 'SHA-256';
	private $test = 2;
	
	/*
	0-银联卡（1）
	1-全民付（86）
	2-POS通（68）
	4-营销联盟（40）
	8-公共支付-通用（9）
	16-代付业务（74）
	21-统一会员卡（37）
	in1-APP支付（in1）
	in2-H5支付（in2）
	in3-公众号支付（in3）
	in4-小程序支付（in4）
	*/
	private $product_id = array('8');
	private $document_type = array
	(
		'idcard_front' => ['document_type' => '0001','document_name' => '身份证正面'],
		'idcard_back' => ['document_type' => '0011','document_name' => '身份证反面'],
		'license' => ['document_type' => '0002','document_name' => '营业执照'],
		'tax' => ['document_type' => '0003','document_name' => '税务登记证'],
		'door' => ['document_type' => '0005','document_name' => '门头照'],
		'hand_idcard' => ['document_type' => '0007','document_name' => '手持身份证自拍照'],
		'open' => ['document_type' => '0006','document_name' => '开户许可证'],
		'bank_fount' => ['document_type' => '0025','document_name' => '银行卡正面照'],
		'bank_back' => ['document_type' => '0026','document_name' => '银行卡反面照'],
		'house_pic' => ['document_type' => '0015','document_name' => '室内照片'],
		'screen_pic' => ['document_type' => '0034','document_name' => '商户网站/APP截图'],
	);

	public function update($id, $name, $data)
    {
        $cash = Dever::param('cash', $data);
        $sign = Dever::db('pay/yspay_sign')->find($id);
        if ($cash && $cash > 0) {
            $this->account_check($sign, $cash);
        }
    }

	# 计划任务
	public function cron_api()
	{
		$where['step'] = '4,5';
		$data = Dever::db('pay/yspay_sign')->getData($where);
		if ($data) {
			foreach ($data as $k => $v) {
				$this->check($v);
			}
		}
		return 'ok';
	}

	# 获取合同链接
	public function getAgreement_api($sign_id)
	{
		$sign = Dever::db('pay/yspay_sign')->find($sign_id);
		return $this->agreement($sign, false);
	}

	# 获取当前状态
	public function getStatus_api($sign_id)
	{
		$sign = Dever::db('pay/yspay_sign')->find($sign_id);
		return $this->check($sign);
	}

	# 获取最新一条日志
	public function getLog($sign_id, $status)
	{
		if ($status == 1) {
			return '签约已完成';
		}
		$sign = Dever::db('pay/yspay_sign')->find($sign_id);
		if ($sign) {
			$log = Dever::db('pay/yspay_sign_log')->find(array('merchant_id' => $sign['merchant_id']));
			if ($log) {
				$date = date('Y-m-d H:i', $log['cdate']);
				$step = Dever::db('pay/yspay_sign_log')->config['step'][$log['step']];
				return $date . '<br />' . $step . '<br />' . $log['desc'];
			} else {
				return '待签约提审';
			}
		} else {
			return '待签约提审';
		}
	}

	# 获取日志列表
	public function getLogList($sign_id)
	{
		$sign = Dever::db('pay/yspay_sign')->find($sign_id);
		if (!$sign) {
			return Dever::timeline('填写资料');
		}
		$result = array();
		
		$log = Dever::db('pay/yspay_sign_log')->select(array('merchant_id' => $sign['merchant_id']));
		if ($log) {
			foreach ($log as $k => $v) {
				if ($v['step'] == 4) {
					//$v['response'] = Dever::json_decode($v['response']);
					$url = $this->agreement($sign, false);
					$v['desc'] .= '  <a href="'.$url.'" target="_blank">点此打开</a>  <a style="cursor:pointer" data-clipboard-text="'.$url.'" class="clipboard">复制链接</a>';
				}
				$date = date('Y-m-d H:i', $v['cdate']);
				$name = '';
				if ($v['admin_id'] > 0) {
					$admin = Dever::db('manage/admin')->find($v['admin_id']);
					if ($admin) {
						$name = '[' . $admin['username'] . ']&nbsp;&nbsp;';
					}
				}
				$result[] = $date . '&nbsp;&nbsp;' . $name . ''. $v['desc'];
			}
		}

		if ($sign['step'] == -1) {
			$url = Dever::url('pay/yspay/sign.handle?sign_id=' . $sign['id'] . '&json=1');
			$result[] = '<a href="javascript:;" onclick="load(\''.$url.'\')">点此上传资料</a>';
		}

		$result = Dever::timeline('签约记录', $result);
		return $result;
	}

	# 统一处理接口
	public function handle_api($sign_id)
	{
		$sign = Dever::db('pay/yspay_sign')->find($sign_id);
		if (!$sign) {
			Dever::alert('档案资料未上传');
		}
		$sign['merchant'] = Dever::db('pay/yspay_merchant')->one($sign['merchant_id']);
		$sign['yspay'] = Dever::db('pay/yspay')->one(array('account_id' => $sign['merchant']['account_id']));
		$this->key = $sign['yspay']['sign_key'];
		$this->accesser_id = $sign['yspay']['sign_accesser_id'];
		$sign['bank_acct_no'] = trim($sign['bank_acct_no']);
		switch($sign['step']) {
			case -1:
				# 提交资料
				return $this->up($sign);
				break;
			case 1:
			case 6:
				if ($sign['bank_acct_type'] == 1) {
					# 对公打款
					return $this->account($sign);
				} else {
					# 签约
					return $this->agreement($sign);
				}
				break;
			case 2:
				# 打款验证
				return $this->account_check($sign);
				break;
			case 4:
			case 5:
				# 验证签约
				return $this->check($sign);
				break;
			case 6:
				# 签约成功，变更签约？
				return '签约已成功，后续可以变更签约';
				return $this->up($sign);
				break;
		}
		return 'ok';
	}

	# 上传图片
	public function upload_api()
	{
		$document_type = $this->document_type;
		$key = Dever::input('key');
		$upload = Dever::json_decode(Dever::input('upload'));
		if ($upload && isset($document_type[$key]) && isset($upload['url'])) {
			$url = md5($upload['url']);
			$sign_pic = Dever::db('pay/yspay_sign_pic')->find(array('key' => $key, 'url' => $url));
			if (!$sign_pic) {
				$pic = $this->pic($upload['url']);
				if ($pic && isset($pic['data']['file_path']) && $pic['data']['file_path']) {
					$insert = array();
					$insert['url'] = $url;
					$insert['document_type'] = $document_type[$key]['document_type'];
					$insert['document_name'] = $document_type[$key]['document_name'];
					$insert['key'] = $key;
					$insert['path'] = Dever::json_encode($pic['data']);
					Dever::db('pay/yspay_sign_pic')->insert($insert);
				}
			}
		}
		return 'ok';
	}

	#3.2  详细采集档案资料上传接口
	private function up($sign)
	{
		$service = 'complex_upload';
		$data['remark'] = '线上支付商户';
		$data['accesser_user_id'] = $sign['id'];
		if ($sign['reg_mer_type'] == 1) {
			$sign['reg_mer_type'] = '00';
		} elseif ($sign['reg_mer_type'] == 2) {
			$sign['reg_mer_type'] = '01';
		} elseif ($sign['reg_mer_type'] == 3) {
			$sign['reg_mer_type'] = '02';
		}
		$data['reg_mer_type'] = $sign['reg_mer_type'];#注册类型
		$data['legal_name'] = $sign['name'];#法人姓名
		$data['legal_idcard_no'] = $sign['idcard'];#法人身份证号
		$data['legal_mobile'] = $sign['mobile'];#法人手机号
		$data['legal_card_deadline'] = $sign['card_deadline'] == '长期' ? '9999-12-31' : date('Y-m-d',$sign['card_deadline']);#证件截止代表日期
		$data['shop_name'] = $sign['merchant']['name'];#商户名称
		if ($sign['bank_acct_type'] == -1) {
			$data['bank_acct_type'] = 0;
			$data['bank_acct_name'] = $sign['name'];#开户账号名称
		} else {
			$data['bank_acct_type'] = 1;
			$data['bank_acct_name'] = $sign['company_name'];#开户账号名称
		}

		$data['bank_acct_no'] = $sign['bank_acct_no'];#开户行账号
		$data['mccCode'] = $sign['mccCode'];

		$area = explode(',', $sign['area']);
		$data['shop_province_id'] = $area[0]/10000;
		$data['shop_city_id'] = $area[1]/100;
		$data['shop_country_id'] = $area[2];
		$sign_area = explode(',',$sign['area']);
		$data['shop_lic'] = $sign['license_number'];#营业执照号
		$bank = $this->bank_list($sign_area[0]/10000, $sign['bank_acct_noname']);
		if($bank && isset($bank['branchBankList']) && $bank['branchBankList']){
			$bank['branchBankList'] = $bank['branchBankList'][0];
			$in['where_id'] = $sign['id'];
			$in['bank_no'] = $bank['branchBankList']['code'];
			$in['shop_addr_ext'] =  $bank['branchBankList']['bankBranchName'];
			Dever::db('pay/yspay_sign')->update($in);
			$data['bank_no'] = $bank['branchBankList']['code'];
			$data['shop_addr_ext'] = $bank['branchBankList']['bankBranchName'];
		} else {
			return $this->log(1, $sign, '开户行行号不存在');
		}
		if ($sign['reg_mer_type'] == '00' && $sign['bank_acct_type'] != '1') {
			return $this->log(1, $sign, '账户类型不正确1');
		}
		if ($sign['legalmanHomeAddr']) { 
			$data['legalmanHomeAddr'] = $sign['legalmanHomeAddr'];
		} 
		$document_type = $this->document_type;

		foreach ($document_type as $k => $v) {
			if (isset($sign[$k]) && $sign[$k]) {
				$sign[$k] = Dever::pic($sign[$k]);
				$url = md5($sign[$k]);
				$sign_pic = Dever::db('pay/yspay_sign_pic')->find(array('key' => $k, 'url' => $url));
				if (!$sign_pic) {
					$pic = $this->pic($sign[$k]);
					if ($pic && isset($pic['data']['file_path']) && $pic['data']['file_path']) {
						$insert = array();
						$insert['url'] = $url;
						$insert['document_type'] = $v['document_type'];
						$insert['document_name'] = $v['document_name'];
						$insert['key'] = $k;
						$insert['path'] = Dever::json_encode($pic['data']);
						Dever::db('pay/yspay_sign_pic')->insert($insert);
						$data['pic_list'][] = array('document_name' => $v['document_name'], 'document_type' => $v['document_type'] , 'file_path'=> $pic['data']['file_path'], 'file_size'=>$pic['data']['file_size']);
					}
				} else {
					$pic = Dever::json_decode($sign_pic['path']);
					$data['pic_list'][] = array('document_name' => $sign_pic['document_name'], 'document_type' => $sign_pic['document_type'] , 'file_path'=> $pic['file_path'], 'file_size'=>$pic['file_size']);
				}
			}
		}
		$ids = $this->product_id;
		$data['product'] = array();
		foreach ($ids as $k => $v) {
			$data['product'][$k] = ['product_id' => $v]; 
		}
		$result = $this->get($service, $data);
		if ($result && $result['code'] == 1 && isset($result['data']['ums_reg_id']) && $result['data']['ums_reg_id']) {
			$update = array();
			$update['where_id'] = $sign['id'];
			$sign['ums_reg_id'] = $update['ums_reg_id'] = $result['data']['ums_reg_id'];
			Dever::db('pay/yspay_sign')->update($update);
			$this->log(1, $sign, '资料上传成功', $data, $result['data'], $result['request_seq']);
			if ($data['bank_acct_type'] == 1) {
				return $this->account($sign);
			} else {
				return $this->agreement($sign);
			}
		} else {
			$this->log(1, $sign, $result['msg'], $data, $result['data'], $result['request_seq']);
		}
		return Dever::input('json') == 1 ? 'reload' : $result;
	}

	# 3.7  发起对公账户验证交易接口
	public function account($sign)
	{
		$step = 2;
		$service = 'request_account_verify';
		$data['ums_reg_id'] = $sign['ums_reg_id'];
		$data['company_account'] = $sign['bank_acct_no'];
		$result = $this->get($service, $data);
		if ($result && $result['code'] == 1 && isset($result['data']['request_seq']) && $result['data']['request_seq']) {
			$update = array();
			$update['where_id'] = $sign['id'];
			$update['step'] = $step;
			$update['clear'] = true;
			Dever::db('pay/yspay_sign')->update($update);
			$this->log($update['step'], $sign, '公户打款成功', $data, $result['data'], $result['request_seq']);
		} else {
			$this->log($step, $sign, $result['msg'], $data, $result['data'], $result['request_seq']);
		}
		return Dever::input('json') == 1 ? 'reload' : $result;
	}

	# 3.6  对公账户认证接口
	public function account_check($sign, $num)
	{
		$step = 3;
		$trans_amt = $num;
		$service = 'company_account_verify';
		$data['ums_reg_id'] = $sign['ums_reg_id'];
		$data['company_account'] = $sign['bank_acct_no'];
		$data['trans_amt'] = $trans_amt;
		$result = $this->get($service, $data, $sign['ums_reg_id']);
		if ($result && $result['code'] == 1 && isset($result['data']['request_seq']) && $result['data']['request_seq']) {
			$update = array();
			$update['where_id'] = $sign['id'];
			$update['step'] = $step;
			$update['clear'] = true;
			Dever::db('pay/yspay_sign')->update($update);
			$this->log($update['step'], $sign, '公户对账成功', $data, $result['data'], $result['request_seq']);
			return $this->agreement($sign);
		} else {
			$this->log($step, $sign, $result['msg'], $data, $result['data'], $result['request_seq']);
		}
		return $result;
	}

	# 3.3  前台签约接口
	public function agreement($sign, $log = true)
	{
		$step = 4;
		$service = 'agreement_sign';
		$data['ums_reg_id'] = $sign['ums_reg_id'];
		$data['pcOrH5'] = 'H5';
		$result = $this->get($service, $data);
		if ($result && $result['code'] == 1 && isset($result['data']['url']) && $result['data']['url']) {
			
			$update = array();
			$update['where_id'] = $sign['id'];
			$update['step'] = $step;
			$update['url'] = $result['data']['url'];
			$update['clear'] = true;
			Dever::db('pay/yspay_sign')->update($update);
			if ($log) {
				$this->log($update['step'], $sign, '请复制链接进行合同签署', $data, $result['data'], $result['request_seq']);
			} else {
				return $update['url'];
			}
		} else {
			$this->log($step, $sign, $result['msg'], $data, $result['data'], $result['request_seq']);
		}
		return Dever::input('json') == 1 ? 'reload' : $result;
	}

	# 3.4  入网状态查询接口
	public function check($sign)
	{
		$step = 5;
		$service = 'apply_qry';
		$data['ums_reg_id'] = $sign['ums_reg_id'];
		$result = $this->get($service, $data, $sign['ums_reg_id']);
		if ($result && $result['code'] == 1 && isset($result['data']['apply_status'])) {
			if ($result['data']['apply_status'] == '03') {
				$step = 6;
			}
			$update = array();
			$update['where_id'] = $sign['id'];
			$update['step'] = $step;
			$update['clear'] = true;
			if ($result['data']['apply_status'] == '03' && isset($result['data']['mer_no']) && $result['data']['mer_no']) {
				$mid = $result['data']['mer_no'];
				Dever::db('pay/yspay_merchant')->update(array('merchant_id' => $sign['merchant_id'], 'mid' => $mid));
			}
			Dever::db('pay/yspay_sign')->update($update);
			$this->log($update['step'], $sign, $result['data']['apply_status_msg'], $data, $result['data'], $result['request_seq']);
		} else {
			$this->log($step, $sign, $result['data']['apply_status_msg'], $data, $result['data'], $result['request_seq']);
		}
		return $result;
	}

	private function encrypt($data)
	{
		$res = bin2hex(openssl_encrypt($data, 'DES-EDE3', $this->key, OPENSSL_RAW_DATA));
		return $res;
	}

	private function decrypt($data)
	{
		return openssl_decrypt(pack('H*',$data), 'DES-EDE3', $this->key, OPENSSL_RAW_DATA);
	}

	private function get($service, $data)
	{
		$accesser_id = $this->accesser_id;
		$sign_type = $this->sign_type;
		$param = $data;
		$param['service'] = $service;
		$param['sign_type'] = $sign_type;
		$param['accesser_id'] = $accesser_id;
		$param['request_date'] = date('YmdHis');
		$param['request_seq'] = Dever::order();
		$sign_data = json_encode($param, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
		$send['json_data'] = $this->encrypt($sign_data);
		$send['sign_data'] = hash('sha256', $sign_data);
		$send['accesser_id'] = $accesser_id;
		$url = $this->url;

		$result = array();
		$result['request_seq'] = $param['request_seq'];
		$result['code'] = 2;
		$result['msg'] = '请求失败';
		$result['data'] = array();

		if ($service == 'agreement_sign') {
			$result['code'] = 1;
			$result['msg'] = '请求成功';
			$result['data']['url'] = $url . '?' . http_build_query($send);
			return $result;
		}
		if ($this->test != 1) {
			$response = Dever::curl($url, $send, 'post');
		} else {
			# 数据模拟
			$response = $this->data($service, $param);
		}
		$result['data'] = $response;

		if ($response) {
			$response = Dever::json_decode($response);
			if (isset($response['res_code']) && ($response['res_code'] == '0000' || $response['res_code'] == '1446')) {
				$result['code'] = 1;
				$result['msg'] = '请求成功';
				$result['data'] = $response;
			} elseif (isset($response['res_msg']) && $response['res_msg']) {
				$result['code'] = 2;
				$result['msg'] = $response['res_msg'];
				$result['data'] = $response;
			} elseif (isset($response['apply_status_msg']) && $response['apply_status_msg']) {
				$result['code'] = 2;
				$result['msg'] = $response['apply_status_msg'];
				$result['data'] = $response;
			}
		}
		
		return $result;
	}

	private function data($service, $data)
	{
		$result = array();
		$result['res_code'] = '0000';
		$result['res_msg'] = 'ok';
		$result['request_seq'] = $data['request_seq'];

		if ($service == 'pic_upload') {
			$result['file_path'] = $data['request_seq'];
			$result['file_type'] = 'jpg';
			$result['file_size'] = strlen($result['file_path']);
		} elseif ($service == 'complex_upload') {
			$result['ums_reg_id'] = $data['request_seq'];
		} elseif ($service == 'agreement_sign') {
			$result['url'] = 'https://www.baidu.com/';
		} elseif ($service == 'apply_qry') {
			$result['apply_status'] = '03';
			$result['apply_status_msg'] = '入网成功（最终成功状态）';
		} elseif ($service == 'branch_bank_list') {
			$result['branchBankList'][] = array('code' => '308100005607', 'bankBranchName' => '招商银行股份有限公司北京天通苑支行');
		}

		return Dever::json_encode($result);
	}

	private function pic($pic)
	{
		$service = 'pic_upload';
		if ($pic) {
			$pic_base64 = $this->test != 1 ? file_get_contents($pic) : 'content';

			if ($pic_base64) {
				$temp = explode('?', $pic);
				if ($temp) {
					$one = pathinfo($temp[0]);
				} else {
					$one = pathinfo($pic);
				}
				$data['pic_base64'] = "data:image/".$one['extension'].";base64,".base64_encode($pic_base64);
				$result = $this->get($service, $data);
				return $result;
			}
		}
		return false;
	}

	# 查询支行
	private function bank_list($areaCode, $key)
	{
		$service = 'branch_bank_list';
		$data['areaCode'] = $areaCode;
		$data['key'] = $key;
		$result = $this->get($service,$data);
		return $result['data'];
	}

	# 记录日志
	private function log($step, $sign, $msg, $request = array(), $response = array(), $request_seq = '')
	{
		if (!$sign) {
			return $msg;
		}
		$data['step'] = $step;
		$data['merchant_id'] = $sign['merchant_id'];
		$data['desc'] = $msg;
		$info = false;
		if ($step == 4 || $step == 5) {
			$info = Dever::db('pay/yspay_sign_log')->find($data);
		}
		
		$admin = Dever::load('manage/auth.info');
		if ($admin) {
			$data['admin_id'] = $admin['id'];
		}
		if ($request_seq) {
			$data['request_seq'] = $request_seq;
		}
		if ($request) {
			$data['request'] = Dever::json_encode($request);
		}
		if ($response) {
			if (is_array($response)) {
				$response = Dever::json_encode($response);
			}
			$data['response'] = $response;
		}
		if ($info) {
			$data['where_id'] = $info['id'];
			Dever::db('pay/yspay_sign_log')->update($data);
		} else {
			Dever::db('pay/yspay_sign_log')->insert($data);
		}
		
		return $msg;
	}
}