package com.yifu.cloud.plus.v1.ekp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icbc.api.DefaultIcbcClient;
import com.icbc.api.IcbcApiException;
import com.icbc.api.IcbcConstants;
import com.icbc.api.UiIcbcClient;
import com.icbc.api.request.JftApiPayrollQueryDetailRequestV1;
import com.icbc.api.request.JftApiVendorSeparateAccountsBusinessOpenRequestV1;
import com.icbc.api.request.JftUiPayrollComfirmSubmitRequestV1;
import com.icbc.api.response.JftApiPayrollQueryDetailResponseV1;
import com.icbc.api.response.JftApiVendorSeparateAccountsBusinessOpenResponseV1;
import com.yifu.cloud.plus.v1.ekp.config.IcbcConfigProperties;
import com.yifu.cloud.plus.v1.ekp.entity.EkpSocialInfo;
import com.yifu.cloud.plus.v1.ekp.mapper.EkpSocialInfoMapper;
import com.yifu.cloud.plus.v1.ekp.service.IcbcTransactionFlowIssueService;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 聚富通到账通知交易流水查询
 *
 * @author huyc
 * @date 2024-05-23 11:21:56
 */
@Log4j2
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(IcbcConfigProperties.class)
public class IcbcTransactionFlowIssueServiceImpl extends ServiceImpl<EkpSocialInfoMapper, EkpSocialInfo> implements IcbcTransactionFlowIssueService {

	@Autowired
	private IcbcConfigProperties icbcConfigProperties;

	public R submitIcbcTransactionFlow() {
		//应用id 应用方私钥 网关公钥 应用方加密串
		String APP_ID = "11000000000000028685";
		//应用方私钥
		String MY_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQE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xs6PD+esij+ZVMXhHq2rSVKlVW42/wgVGwZdt8VX9ztKiAgqve1BbjNFmcAytb74YSOgFic5Wwl6uglx8LiwdY93ShQY+maVsPhEj8jFjGe2JlMscX8QgzkfxowrOpdlXsMSYgbG0ccBkXWZXbsh8tsUH9g+WNAoGAbQ5avOo0uF603Uts7ZFC0Lia0Vcx499oxGG5s8Js7tBAS6I7bRp5xokQHz/8BRKBL52oWJklpgy+N6oBnU7rFgRGaZBITABedqIWppHtac4ihUyQ+ZPRIfZqpmOXuaFJVmjUkm6zimpD+TOlaX3ZL88fdDX0E3xuBtBwBuxIkH0CgYEAlXyBbG2/fVV/PDUVCAA+aeWstojR1ncDhJmFnENSk5I/y3mh+d+u4ZG3hmVQZfR1EYM+n9wPQ2LxqNpGPA8o4JK/MSfVKun4lBwjkergHzxWJ5AMuYL1DPrOtMPEqrTqOHfVzSZGsz9cMK4tDWETKKFBOM/5oSdGGW3oYvzcS0M=";
		//网关公钥
		String APIGW_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMpjaWjngB4E3ATh+G1DVAmQnIpiPEFAEDqRfNGAVvvH35yDetqewKi0l7OEceTMN1C6NPym3zStvSoQayjYV+eIcZERkx31KhtFu9clZKgRTyPjdKMIth/wBtPKjL/5+PYalLdomM4ONthrPgnkN4x4R0+D4+EBpXo8gNiAFsNwIDAQAB";
		//应用方加密串
		String AES_Key = "8jTKCqZ9035g+HRzpZQqZA==";
		UiIcbcClient client = new UiIcbcClient(APP_ID, IcbcConstants.SIGN_TYPE_RSA2, MY_PRIVATE_KEY,
				IcbcConstants.CHARSET_UTF8);
		JftUiPayrollComfirmSubmitRequestV1 request = new JftUiPayrollComfirmSubmitRequestV1();
		request.setServiceUrl("https://gw.open.icbc.com.cn/ui/jft/ui/payroll/comfirmsubmit/V1");
		JftUiPayrollComfirmSubmitRequestV1.JjftUiPayrolComfirmSubmitRequestV1BizV1 bizContent =
				new JftUiPayrollComfirmSubmitRequestV1.JjftUiPayrolComfirmSubmitRequestV1BizV1();
		bizContent.setAppId(APP_ID);
		//HR系统名称
		bizContent.setAppName("HRO");
		//企业编号
		bizContent.setOutVendorId("020101190");
		//操作类型：1-受理 2-审核
		bizContent.setOprType("1");
		bizContent.setTotalAmt("1000");
		bizContent.setTotalCount("1");
		bizContent.setAppSerialno("WX2");
		bizContent.setLocalFilepath("D:/icbcFile/020101190_WX2_0_20240801.xls");
		bizContent.setFileMdcode(getMdCode("D:/icbcFile/020101190_WX2_0_20240801.xls"));
		bizContent.setFileType("1");
		bizContent.setNotifyUrl(null);
		bizContent.setAppRemark("备注");
		bizContent.setBusinessType(null);
		bizContent.setFileCheckSign(null);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("key",request);
		String a = jsonObject.toJSONString();
		request.setBizContent(bizContent);
		try {
			String result = client.buildPostForm(request);
			if (Common.isNotNull(result)) {
				return R.ok();
			}
		} catch (IcbcApiException e) {
			e.printStackTrace();
			return R.failed();
		}
		return R.ok();
	}

	public R selectIcbcTransactionFlowInfo() {

		DefaultIcbcClient client = new DefaultIcbcClient(icbcConfigProperties.getAppId(), IcbcConstants.SIGN_TYPE_RSA2,
				icbcConfigProperties.getAppPrivateKey(), IcbcConstants.CHARSET_UTF8, IcbcConstants.FORMAT_JSON,
				icbcConfigProperties.getApigwPublicKey(), IcbcConstants.ENCRYPT_TYPE_AES, icbcConfigProperties.getAesKey(), null, null);
		JftApiPayrollQueryDetailRequestV1 request = new JftApiPayrollQueryDetailRequestV1();
		request.setServiceUrl("https://apipcs3.dccnet.com.cn/api/jft/api/payroll/querydetail/V1");
		JftApiPayrollQueryDetailRequestV1.JftApiPayrollQueryDetailRequestV1Biz bizContent = new
				JftApiPayrollQueryDetailRequestV1.JftApiPayrollQueryDetailRequestV1Biz();
		bizContent.setAppId(icbcConfigProperties.getAppId());
		bizContent.setOutVendorId(icbcConfigProperties.getCompanyNo());
		bizContent.setType("2");
		//批次号，appSerialno为空时，必输
		bizContent.setAppBatserialno("21900");
		//内部批次号，组成规则：批次号-顺序号，appBatserialno为空时必输
//		bizContent.setAppSerialno("230921");
		bizContent.setStartId("0");
		bizContent.setEndId("10");
		request.setBizContent(bizContent);
		try {
			JftApiPayrollQueryDetailResponseV1 responseV1 = client.execute(request);
			if (Common.isNotNull(responseV1)) {
				return R.ok();
			}
		} catch (IcbcApiException e) {
			e.printStackTrace();
			return R.failed();
		}
		return R.ok();
	}

	public R businessOpen() {

		//1、网关公钥
		String APIGW_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMpjaWjngB4E3ATh+G1DVAmQnIpiPEFAEDqRfNGAVvvH35yDetqewKi0l7OEceTMN1C6NPym3zStvSoQayjYV+eIcZERkx31KhtFu9clZKgRTyPjdKMIth/wBtPKjL/5+PYalLdomM4ONthrPgnkN4x4R0+D4+EBpXo8gNiAFsNwIDAQAB";
		//2、appid
		String APP_ID = "11000000000000029313";
		//3、密钥对认证方式，公钥在API平台登记，此处为私钥
		String MY_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC96zrfaBT4YOoLErhTaFnv0De1K3ZsZRQDGm3dIF8wHX/Rqg2sz5hfJexMwNgTepHdxrpveq8bog9jny8CtCT2etUD+NKT0gBYx4FzjCy1vtJzO1BqyzqzHA+GMsFQ/CYucRo25SJRv9szJD7d0SlnD0rnJWnbCuK+OgzM1ixCeUKsF/94Fgbo95UeW6EhH8H4VwNNrWRZei+eLfkIoHMSTB9D2g58i5S++/oieLg52MRd35x3pm60ipcGTgLpLi0xJGNB3dDDNA/UG3D7jbpLha3+eX1SaKU3jmTZYyLBFRe4fuY1LJq8gI03KGNHhPsbu1Gn8q9H7pcK3O1JAqStAgMBAAECggEAPiRuCxO/aNYtPppNfd0zMGjtEXa7NRSNy8YmFKi2/MNqQ2xlNRpoPRnni+W9zgHZILwZ3MhD68LHTk2T0EqpnYzrjnUoUf3w5xvAm9JN/toFen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AM8APG6K7ID5Km8CnmnPX/ynBA1kpucIRUDnUwbGcfEbf2ufhPd10dg==";

		String apiUrl= "https://gw.open.icbc.com.cn/api/jft/api/vendor/separate/accounts/business/open/V1";
		String encryptKey = "u1NKBJOMzvkHFvGiKbsq3g==";
			//签名类型为RSA2时，需传入appid，私钥和网关公钥，签名类型使用定值IcbcConstants.SIGN_TYPE_RSA2，其他参数使用缺省值
			DefaultIcbcClient client = new DefaultIcbcClient(APP_ID,"RSA2", MY_PRIVATE_KEY,"UTF-8", "json",APIGW_PUBLIC_KEY,"AES",encryptKey, "", "");
			JftApiVendorSeparateAccountsBusinessOpenRequestV1 request = new JftApiVendorSeparateAccountsBusinessOpenRequestV1();
			//4、根据测试环境和生产环境替换相应ip和端口
			request.setServiceUrl(apiUrl);
			//5、请对照接口文档用bizContent.setxxx()方法对业务上送数据进行赋值
			JftApiVendorSeparateAccountsBusinessOpenRequestV1.JftApiVendorSeparateAccountsBusinessOpenRequestV1Biz bizContent = new JftApiVendorSeparateAccountsBusinessOpenRequestV1.JftApiVendorSeparateAccountsBusinessOpenRequestV1Biz();
			bizContent.setAppId(APP_ID);
			bizContent.setOutVendorId("0202407190000011934");
			bizContent.setOutVendorManagerId("0202407190000011934");
			bizContent.setOutUpperVendorId(APP_ID);
			bizContent.setVendorName("安徽皖信人力资源管理有限公司");
			bizContent.setBizType("01");
			bizContent.setOpenCardType("0");
			bizContent.setBusinessType("02");//开通业务类型
			bizContent.setSubBusinessType("03");//开通业务类型
			bizContent.setBusSwitch("1");//业务开通关闭标志，开通时传1  关闭时传0
			bizContent.setRegistType("1");//注册标识 1 注册+开通业务 2 仅维护业务
			bizContent.setUpperMcardNo("");
			bizContent.setEqfEnsurePhone("");
			request.setBizContent(bizContent);
			JftApiVendorSeparateAccountsBusinessOpenResponseV1 response;
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("key",request);
			String a = jsonObject.toJSONString();
			try {
				response = (JftApiVendorSeparateAccountsBusinessOpenResponseV1)client.execute(request, System.currentTimeMillis()+"");
				if (response.isSuccess()) {
					//6、业务成功处理，请根据接口文档用response.getxxx()获取同步返回的业务数据
					System.out.println("ReturnCode:"+response.getReturnCode());
					System.out.println("response:" + response);
				} else {
					//失败
					System.out.println("ReturnCode:"+response.getReturnCode());
					System.out.println("ReturnMsg:"+response.getReturnMsg());
				}
			} catch (IcbcApiException e) {
				e.printStackTrace();
			}
			return R.ok();
		}

	public String getMdCode(String filePath) {
		try {
			MessageDigest md5Digest = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[8192];

			try (FileInputStream fis = new FileInputStream(filePath)) {
				int bytesRead;
				while ((bytesRead = fis.read(buffer)) != -1) {
					md5Digest.update(buffer, 0, bytesRead);
				}
			}
			byte[] md5Bytes = md5Digest.digest();

			// Convert the byte to hex format
			StringBuilder result = new StringBuilder();
			for (byte md5Byte : md5Bytes) {
				result.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1));
			}

			return result.toString();
		} catch (NoSuchAlgorithmException | IOException e) {
			//Handle the exception according to your requirements
			e.printStackTrace();
			return null;
		}
	}

}
