package com.yonge.toolset.thirdparty.lingxinpay;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.yonge.toolset.base.exception.ThirdpartyException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.yonge.toolset.base.exception.ThirdpartyException;
import com.yonge.toolset.utils.http.HttpUtil;

@Service
public class ContractSignService {

	private static final Logger logger = LoggerFactory.getLogger(ContractSignService.class);

	@Value("${teacher.contract.publicKey:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYT5eCY6r8sGWgbiId/VqSZmS6XkBNGMkzUqTIkpkecOzsFBxFXTQmgDeR991YfgqmyOaHsJ/ons/H+e8l+RmHsOm4eErFU+9qXFq+k195YFV1vAR9O7MIG+FR5vmLDuhgimPsgqscWhUrGinc8RUpi5KwClgx7d+d8ZJ4GmkR0QIDAQAB}")
	private String publicKey;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Value("${teacher.contract.contractNo:1164462240733069312}")
	private String contractNo;// 模板协议号

	@Value("${teacher.contract.memberNo:1491663782974988288}")
	private String outMemberNo;// 商户号
	
	@Value("${teacher.contract.notifyUrl:http://www.baidu.com}")
	private String notifyUrl;
	
	@Value("${teacher.contract.apiUrl:http://39.107.15.64:8095}")
	private String apiUrl;

	public boolean signContract(String realName, String idcard, String mobileNo, String serialNo) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("signType", "RSA");
		jsonObject.put("service", "bpotop.zx.contract");
		jsonObject.put("charset", "UTF-8");
		jsonObject.put("version", "1.0");
		jsonObject.put("createTime", sdf.format(new Date()));

		jsonObject.put("outMemberNo", outMemberNo);// 公司商户号
		jsonObject.put("serialNo", serialNo);// 流水号（商户唯一标识）
		jsonObject.put("contractNo", contractNo);// 合同模板号
		jsonObject.put("notifyUrl", notifyUrl);// 返回结果异步通知地址

		JSONObject jsonObject2 = new JSONObject();
		jsonObject2.put("name", realName);
		jsonObject2.put("phone", mobileNo);
		jsonObject2.put("identityId", idcard);
		jsonObject2.put("citizenship", "0");
		jsonObject2.put("signTime", sdf.format(new Date()));
		jsonObject.put("contractSignInfo", jsonObject2);
		String jsonStr = JSONObject.toJSONString(jsonObject);

		try {
			String encryptStr = RSA.encryptPub(jsonStr, publicKey);
			jsonObject.put("sign", encryptStr);
		} catch (Exception e) {
			logger.error("加密失败", e);
			throw new ThirdpartyException("加密失败：{}", e.getMessage());
		}
		logger.info("[合同签署]请求参数：{}", jsonObject.toJSONString());
		try {
			String s = HttpUtil.postForHttp(apiUrl + "/api/signContract", jsonObject.toJSONString(), null);
			logger.info("请求[合同签署]响应参数：{}", s);

			jsonObject = JSONObject.parseObject(s);
			if (StringUtils.equals(jsonObject.getString("return_code"), "T")) {
				return true;
			}

			throw new ThirdpartyException("合同签署失败：{}", jsonObject.getString("content"));

		} catch (IOException e) {
			logger.error("请求[合同签署]接口报错", e);
			throw new ThirdpartyException("请求[合同签署]接口报错：{}", e.getMessage());
		}
	}

	public String querySignContractResult(String serialNo) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("outMemberNo", outMemberNo);
		jsonObject.put("serialNo", serialNo);
		jsonObject.put("contractNo", contractNo);
		try {
			String encryptStr = RSA.encryptPub(JSONObject.toJSONString(jsonObject), publicKey);
			jsonObject.put("sign", encryptStr);
		} catch (Exception e) {
			logger.error("加密失败", e);
			throw new ThirdpartyException("加密失败：{}", e.getMessage());
		}
		jsonObject.put("signType", "RSA");
		jsonObject.put("service", "bpotop.zx.contract");
		jsonObject.put("charset", "UTF-8");
		jsonObject.put("version", "1.0");
		jsonObject.put("createTime", sdf.format(new Date()));
		try {
			String s = HttpUtil.postForHttp(apiUrl + "/api/queryContractInfo", jsonObject.toJSONString(), null);

			logger.info("[合同查询]响应参数：{}", s);

			jsonObject = JSONObject.parseObject(s);
			if (StringUtils.equals(jsonObject.getString("return_code"), "T")) {
				return (String) JSONPath.eval(jsonObject, "$.content.contractUrl");
			}

			//throw new ThirdpartyException("查询合同签署结果失败：{}", JSONPath.eval(jsonObject, "$.content.message"));
		} catch (IOException e) {
			logger.error("请求[合同查询]接口报错", e);
			//throw new ThirdpartyException("请求[合同查询]接口报错：{}", e.getMessage());
		}
		return null;
	}

	public static void main(String[] args) {
		ContractSignService service = new ContractSignService();
		// service.signContract("何亮", "130423199206192818", "17600220933","11");

		service.querySignContractResult("11");
	}
}
