package com.jeeplus.modules.esignature.service.contract;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.modules.esignature.kinggridserver.KingGridServer;
import com.jeeplus.modules.esignature.utils.HttpRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 合同相关测试（使用模板）接口
 * @author Administrator
 *
 */
public class ContractWithTemplateService {
	public static void main(String[] args) throws IOException {
		String contractid = "template_contractid_test01";
		JSONObject json = generateContract(contractid , KingGridServer.CONTRACT_TPL_CODE);
		System.out.println(json);
		if(json.getInteger("code") == 1){//创建成功
			downFiles(json.getJSONArray("doc_last_urls"), "d:/"+contractid);
		}
		json = signContract(contractid, KingGridServer.SIGNER_CODE);
		if(json.getInteger("code") == 1){//签署成功
			downFiles(json.getJSONArray("record_saved_urls"), "d:/"+contractid);
		}else{
			System.out.println(json);
		}
		
	}
	
	/**
	 * 下载多个文件保存在文件夹
	 * @param urls
	 * @param savePath
	 * @throws IOException
	 */
	public static final void downFiles(JSONArray urls , String savePath) throws IOException{
		for (Object url : urls) {
			downFile((String)url, savePath);
		}
	}
	
	/**
	 * 下载文件保存
	 * @param url
	 * @param savePath
	 * @throws IOException 
	 */
	public static final void downFile(String url , String savePath) throws IOException{
		HttpRequest request = new HttpRequest(url);
		request.send();
		int code = request.getResponseCode();
		if(code==200){
			FileOutputStream fos = null;
			try{
				String fileName = savePath;
				if(!(savePath.endsWith("/")|| savePath.endsWith("\\"))){
					fileName +="/";
				}
				fileName+=request.getDownFileName();
				File file  = new File(fileName);
				file.getParentFile().mkdirs();
				fos = new FileOutputStream(file);
				System.out.println("保存文件至："+fileName);
				request.result(fos);
			}finally{
				if(fos!=null){
					fos.close();
				}
			}
		}else{
			System.out.println("错误信息："+request.resultToString());
		}
	}
	
	
	
	/**
	 * 使用模板创建合同
	 * @throws IOException 
	 */
	public static JSONObject generateContract(String contractid , String contract_tpl_code) throws IOException{
		HttpRequest request = KingGridServer.createHttpRequest("/api/contract/start");
		//{"姓名":"李东长","cardname_ID":"360111198708080899","year":"2018","month":"01","day":"01"}
		JSONObject xml_metadata = new JSONObject(true);
		xml_metadata.put("姓名", "李东长");
		xml_metadata.put("cardname_ID", "360111198708080899");
		xml_metadata.put("year", "2018");
		xml_metadata.put("month", "01");
		xml_metadata.put("day", "01");
		
		
		request.addParam("contract_tlp_code",contract_tpl_code);
		
		request.addParam("doc_metadata",xml_metadata.toJSONString());
		
		//设置合同ID
		request.addParam("contract_id", contractid);
		//设置合同名称参数
		request.addParam("contract_name", "测试合同");
		
		//设置业务编码参数
		request.addParam("biz_id", UUID.randomUUID().toString().replaceAll("-", ""));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//设置业务时间参数
		request.addParam("biz_time", sdf.format(new Date()));
		
		
		request.send();
		return JSONObject.parseObject(request.resultToString());
		
	}
	
	/**
	 * 签署合同
	 * @throws IOException 
	 */
	public static JSONObject signContract(String contractid , String signer_code ) throws IOException{
		HttpRequest request = KingGridServer.createHttpRequest("/api/contract/sign");
		request.addParam("contract_id", contractid);
		request.addParam("biz_id", UUID.randomUUID().toString().replaceAll("-", ""));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//设置业务时间参数
		request.addParam("biz_time", sdf.format(new Date()));
		//设置签署人的编码
		request.addParam("signer_code", signer_code);
		
		request.send();
		return JSONObject.parseObject(request.resultToString());
		
	}
}
