package com.yonge.toolset.thirdparty.eseal.provider;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;

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

public class BytedancePlugin implements InitializingBean, DisposableBean {

	@Value("${eseal.bytedance.projectid:E6894439939350463244}")
	public String projectId = "E6894439939350463244";

	@Value("${eseal.bytedance.projectSecret:F%#1*#3^z61GEvH0Nf2N1u68v!vvU5n9C^3RE!z3Q^H$UD3521625&&q!H43QnNf}")
	public String projectSecret = "F%#1*#3^z61GEvH0Nf2N1u68v!vvU5n9C^3RE!z3Q^H$UD3521625&&q!H43QnNf";

	@Value("${eseal.bytedance.apisUrl:http://sandbox.letsign.com}")
	public String apisUrl = "http://sandbox.letsign.com";

	public static String getName() {
		return "ByteDance";
	}

	@Override
	public void afterPropertiesSet() throws Exception {

	}

	@Override
	public void destroy() throws Exception {

	}

	/**
	 * 创建用户账户(个人)
	 * @param userId 用户编号
	 * @param realName 姓名
	 * @param idcard 身份证号码
	 * @param mobile 手机号码
	 * @return 账户唯一标识
	 * @throws IOException 
	 */
	public String createUserAccount(String userId, String realName, String idcard, String mobile) throws IOException {
		String path = "/open-api/certification/noUser/person3/";
		String url = apisUrl + path;
		Map<String, Object> params = new HashMap<String, Object>();

		// 基础参数
		params.put("appCode", projectId);
		params.put("timestamp", "" + System.currentTimeMillis());
		params.put("version", "v1");

		// 业务参数
		params.put("personOpenCode", userId);
		params.put("personMobile", mobile);
		params.put("personName", realName);
		params.put("personIdCard", idcard);

		// token
		String token = generateToken(params, projectSecret);
		params.put("token", token);

		params.put("personIdCardFrontFile", "");
		params.put("personIdCardBackFile", "");

		String result = HttpUtil.postForHttp(url, params);
		System.out.println(result);

		JSONObject jsonObject = JSONObject.parseObject(result);
		if (jsonObject.getInteger("code") == 0) {
			return userId;
		}
		throw new ThirdpartyException("创建个人账户失败:{}", jsonObject.getString("description"));
	}

	/**
	 * 创建用户账户(企业)
	 * @param orgName  机构名称
	 * @param organCode 统一社会信用代码
	 * @return e签宝账户唯一标识
	 */
	public String createOrganAccount(String orgName, String organCode) {

		return null;
	}

	/**
	 * 文件上传
	 * @param contractFile 协议文件
	 * @param userId 用户账号
	 * @return
	 * @throws IOException
	 */
	public String uploadFile(File contractFile, String userId) throws IOException {
		String path = "/open-api/contract/opt/upload";
		String url = apisUrl + path;
		Map<String, Object> params = new HashMap<String, Object>();

		// 基础参数
		params.put("appCode", projectId);
		params.put("timestamp", "" + System.currentTimeMillis());
		params.put("version", "v1");

		// 业务参数
		params.put("companyOpenCode", "");
		params.put("personOpenCode", userId);
		params.put("signType", 1);
		params.put("canRefuse", 0);

		// token
		String token = generateToken(params, projectSecret);
		params.put("token", token);

		params.put("contractFile", contractFile);

		String result = HttpUtil.postForHttp(url, params);
		System.out.println(result);

		JSONObject jsonObject = JSONObject.parseObject(result);
		if (jsonObject.getInteger("code") == 0) {
			return (String) JSONPath.eval(jsonObject, "$.data.contractCode");
		}
		throw new ThirdpartyException("上传文件失败:{}", jsonObject.getString("description"));
	}

	/**
	 * 企业PDF摘要签署（印章图片）
	 * @param sealData 电子印章数据
	 * @param srcPdfPath 源文件
	 * @param destPdfPath 签名后的目标文件
	 * @return
	 */
	public boolean organSign(String sealData, String srcPdfPath, String destPdfPath) {
		return true;
	}

	/**
	 * 用户签名
	 * @param accountId e签宝账户唯一标识
	 * @param sealData 电子印章数据
	 * @param srcPdfPath 平台签名后的源文件
	 * @param destPdfPath 平台、用户都签名后的文件地址
	 * @return
	 */
	public boolean userSign(String accountId, String sealData, String srcPdfPath, String destPdfPath) {

		return true;
	}

	private String generateToken(Map<String, Object> params, String secret) {

		params = SortUtil.sortWithAscII(params);
		String paramsStr = ValueUtil.joinKeyValue(params, "", "", "", true);
		String md5Str = new String(DigestUtils.md5(paramsStr.getBytes()));

		paramsStr = md5Str + secret;

		return DigestUtils.sha1Hex(paramsStr);
	}

	public static void main(String[] args) throws IOException {
		BytedancePlugin plugin = new BytedancePlugin();
		plugin.createUserAccount("1", "高勇", "421125198708123313", "13720176797");
	}

}
