package com.css.txw.sso.controller.thirdparty;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.chainweaver.did.sdk.DidClient;
import org.chainweaver.did.sdk.IDidClient;
import org.chainweaver.did.sdk.model.AccessToken;
import org.chainweaver.did.sdk.model.Proof;
import org.chainweaver.did.sdk.model.VerifiableCredential;
import org.chainweaver.did.sdk.model.VerifiablePresentation;
import org.chainweaver.did.sdk.model.VerifiablePresentation.VerifiablePresentationBuilder;
import org.chainweaver.did.sdk.model.req.ApplyBusinessLicenseExtend;
import org.chainweaver.did.sdk.model.req.LoginExtend;
import org.chainweaver.did.sdk.model.resp.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.css.ggzc.framework.cache.utils.CacheUtils;
import com.css.ggzc.framework.cache.utils.XtcsUtils;
import com.css.ggzc.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.css.ggzc.framework.common.pojo.CommonResult;
import com.css.ggzc.framework.common.pojo.R;
import com.css.ggzc.framework.common.util.gy.GyUtils;
import com.css.ggzc.framework.common.util.json.JsonUtils;
import com.css.ggzc.framework.common.util.object.BeanUtils;
import com.css.ggzc.framework.common.util.servlet.ServletUtils;
import com.css.ggzc.framework.session.SessionUtils;
import com.css.txw.mhzc.pojo.YhxxbDTO;
import com.css.txw.sso.constants.SsoConstants;
import com.css.txw.sso.pojo.domain.oauth2.OAuth2AccessTokenDO;
import com.css.txw.sso.pojo.vo.AuthLoginRespVO;
import com.css.txw.sso.pojo.vo.thirdparty.did.DidCallbackExtendInfo;
import com.css.txw.sso.pojo.vo.thirdparty.did.DidCredentialSubject;
import com.css.txw.sso.pojo.vo.thirdparty.did.DidExtendVcsInfo;
import com.css.txw.sso.pojo.vo.thirdparty.did.DidLoginExtend;
import com.css.txw.sso.pojo.vo.thirdparty.did.QrCodeInfo;
import com.css.txw.sso.service.oauth2.OAuth2TokenService;
import com.css.txw.sso.service.yhxx.YhxxService;

import cn.hutool.core.util.IdUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/did")
@Tag(name = "did接口对接")
@Slf4j
public class DidController {

	/** 请求登录凭证的地址 */
	public static final String XTCS_CODE_TXW_DID_LOGIN_VP_URL = "TXW_DID_LOGIN_VP_URL";
	/** 请求企业实名凭证的地址 */
	public static final String XTCS_CODE_TXW_DID_BUSI_LICE_VP_URL = "TXW_DID_BUSI_LICE_VP_URL";
	/** 登录回调地址 */
	public static final String XTCS_CODE_TXW_DID_LOGIN_CALLBACK_URL = "TXW_DID_LOGIN_CALLBACK_URL";
	/** 企业实名认证回调地址 */
	public static final String XTCS_CODE_TXW_DID_BUSI_LICE_CALLBACK_URL = "TXW_DID_BUSI_LICE_CALLBACK_URL";
	/** DID控制台地址 */
	public static final String XTCS_CODE_TXW_DID_CONSOLE_LOGIN_URL = "TXW_DID_CONSOLE_LOGIN_URL";
	/** DID控制台登录用户名 */
	public static final String XTCS_CODE_TXW_DID_CONSOLE_USERNAME = "TXW_DID_CONSOLE_USERNAME";
	/** DID控制台登录密码 */
	public static final String XTCS_CODE_TXW_DID_CONSOLE_PASSWORD = "TXW_DID_CONSOLE_PASSWORD";

	/** 请求授权的平台的名称 */
	public static final String XTCS_CODE_TXW_DID_AUTH_NAME = "TXW_DID_AUTH_NAME";
	/** 请求授权的平台的英文名称 */
	public static final String XTCS_CODE_TXW_DID_AUTH_EN_NAME = "TXW_DID_AUTH_EN_NAME";
	public static final String XTCS_CODE_TXW_DID_LOGIN_TEMPLATE_ID = "TXW_DID_LOGIN_TEMPLATE_ID";
	
	public static final String XTCS_CODE_TXW_DID_LOGIN_TEMPLATE_VERSION = "TXW_DID_LOGIN_TEMPLATE_VERSION";
	
	
	/**
	 * 运营中心的 DID
	 */
	public static final String XTCS_CODE_TXW_DID_CONSOLE_DIDCODE="TXW_DID_CONSOLE_DIDCODE";
	
	// TXW:DID:REQ:ID: 缓存请求标识前缀
	/** 缓存请求标识前缀 */
	public static final String REQ_ID_PREFIX = "TXW:DID:REQ:ID:";
	
	/**
	 * 缓存用户信息前缀
	 */
	public static final String REQ_USER_DATA_PREFIX = "TXW:DID:USER:Data:";
	/**
	 * 缓存用户did前缀
	 */
	public static final String REQ_USER_DID_PREFIX = "TXW:DID:USER:DID:";
	/**
	 * 缓存did返回的用户信息前缀
	 */
	public static final String REQ_USER_DID_DATA_PREFIX = "TXW:DID:USER:DID:Data:";
	
	public static final String REQ_USER_DID_DLZH_PREFIX = "TXW:DID:USER:DLZH:";
	
	/**
	 * 页面请求
	 */
	public static final String DID_REQ_STATUS_PAGE = "1";
	/**
	 * 扫描请求
	 */
	public static final String DID_REQ_STATUS_QR = "2";
	/**
	 * 返回处理
	 */
	public static final String DID_REQ_STATUS_CALLBACK = "3";
	
	/**
	 * 手机绑定
	 */
	public static final String DID_REQ_PHONE_BIND = "4";
	
	/**
	 * did 认证失败
	 */
	public static final String DID_REQ_STATUS_BUSI_FAILURE = "5";
	public static final String DID_REQ_STATUS_BUSI_FAILURE_MSG_PREFIX = "TXW:DID:BUSI:FAILURE:MSG:";
	/**
	 * 认证成功
	 */
	public static final String DID_REQ_STATUS_BUSI_SUCCESS = "6";
	
	public static final int ERROR_CODE_PARAM = 301001;

	public static final long timeout = 1000 * 60 * 30;
	
    @Resource
    private YhxxService yhxxService;
    
    @Resource
    private OAuth2TokenService oauth2TokenService;
    
	/**
	 * 获取登录二维码内容
	 * 
	 * @name 获取登录二维码内容
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取登录二维码内容")
	@PostMapping("/pub/login/qrcode")
	public CommonResult<QrCodeInfo> getLoginUrlQRCode() {
		return getQrCode(XTCS_CODE_TXW_DID_LOGIN_VP_URL);
	}

	private CommonResult<QrCodeInfo> getQrCode(String xtcsCode) {
		CommonResult<QrCodeInfo> result = CommonResult.success(null);
		String url = XtcsUtils.getXtcs(xtcsCode);
		if (GyUtils.isNull(url)) {
			String msg = String.format("系统参数%s为空！", xtcsCode);
			log.info(msg);
			result.setMsg(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
			return result;
		}
		String reqId = GyUtils.getUuid() + GyUtils.getUuid();
		String tmp = String.format("%s?reqId=%s", url, reqId);
		QrCodeInfo info = QrCodeInfo.builder().reqId(reqId).url(tmp).build();
		String key = String.format("%s%s", REQ_ID_PREFIX, reqId);
		CacheUtils.cacheData(key, DID_REQ_STATUS_PAGE, timeout);
		result.setData(info);
		//缓存里设置登录账户
		key = String.format("%s%s", REQ_USER_DID_DLZH_PREFIX, reqId);
		String yhuuid = SessionUtils.getYhUuid();
		CacheUtils.cacheData(key, yhuuid);
		log.info("key:{},yhuuid:{}",key,yhuuid);
		return result;
	}

	/**
	 * 获取认证二维码内容
	 * 
	 * @name 获取认证二维码内容
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取认证二维码内容")
	@Parameter(name = "request", description = "请求报文")
	@PostMapping("/busilice/qrcode")
	public CommonResult<QrCodeInfo> getBusinessLicenseUrlQRCode() {
		return getQrCode(XTCS_CODE_TXW_DID_BUSI_LICE_VP_URL);
	}

	/**
	 * 获取登录凭证信息
	 * 
	 * @name 获取登录凭证信息
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取登录凭证信息")
	@Parameter(name = "request", description = "请求报文")
	@GetMapping(value = "/pub/getvp/login", produces = "application/json")
	public String getLoginVP(
			@RequestParam(required = false, name = "reqId") String reqId) {
		Response<VerifiablePresentation<DidLoginExtend>> result =Response.SuccessResponse();
//		Map<String,Object> r =new HashMap<>();
		if (GyUtils.isNull(reqId)) {
			String msg = "reqId is null . ";
			log.info(msg);
			result.setMessage(msg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
//			return r;
		}
		String key = String.format("%s%s", REQ_ID_PREFIX, reqId);
		String status = CacheUtils.getCacheData(key);
		log.info("request {}, status :{}",reqId,status);
		if (GyUtils.isNull(status)) {
			String msg = String.format("该请求%s已过期！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
//			return r;
		}
		if (!GyUtils.isEquals(status, DID_REQ_STATUS_PAGE)) {
			String msg = String.format("该请求%s状态不正确，请在页面上重新操作！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		CacheUtils.cacheData(key, DID_REQ_STATUS_QR);
		String consoleUrl = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_LOGIN_URL);
		// 新建客户端
		IDidClient didClient = new DidClient(consoleUrl, DidClient.version15);
		String username = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_USERNAME);
		String pwd = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_PASSWORD);
		// 登录
		Response<AccessToken> login = didClient.login(username, pwd);
		
		log.info("did控制台登录响应：{}", login);
		String url = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_LOGIN_CALLBACK_URL);
		if (GyUtils.isNull(url)) {
			String msg = String.format("系统参数%s为空！", XTCS_CODE_TXW_DID_LOGIN_CALLBACK_URL);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
//			return r;
		}
		String callbackUrl = String.format("%s?reqId=%s", url,reqId);
		String authorizedName = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_AUTH_NAME);
		if (GyUtils.isNull(authorizedName)) {
			String msg = String.format("系统参数%s为空！", XTCS_CODE_TXW_DID_AUTH_NAME);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
//			return r;
		}
		String authorizedNameEn = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_AUTH_EN_NAME);
		if (GyUtils.isNull(authorizedNameEn)) {
			String msg = String.format("系统参数%s为空！", XTCS_CODE_TXW_DID_AUTH_EN_NAME);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
//			return r;
		}
		LoginExtend extend1 = LoginExtend.builder()
				.requestId(reqId)
				.method("POST")
				.callbackUrl(callbackUrl)
				.authorizedName(authorizedName)
				.authorizedNameEn(authorizedNameEn)
				.build();
		DidLoginExtend extend = new DidLoginExtend();
		BeanUtils.copyBean(extend1, extend); 
		List<DidExtendVcsInfo> vcs = new ArrayList<>();
		String did = getXtcs(XTCS_CODE_TXW_DID_CONSOLE_DIDCODE);
//		String issuer = "did:cndid:cndid";
		String tmpid = getXtcs(XTCS_CODE_TXW_DID_LOGIN_TEMPLATE_ID);
//		tmpid = "100752";
		String version =  getXtcs(XTCS_CODE_TXW_DID_LOGIN_TEMPLATE_VERSION);
//		version = "v2";
//		DidExtendVcsInfo vcsInfo = DidExtendVcsInfo.builder()
//				.vctId(tmpid)
//				.vctVersion(version)
//				.issuer(did)
//				.build();
//		vcs.add(vcsInfo);
		DidExtendVcsInfo vcsInfo = DidExtendVcsInfo.builder()
				.vctId("100001")
				.vctVersion("v9")
				.issuer("did:cndid:cndid")
				.build();
		vcs.add(vcsInfo);
//		vcsInfo = DidExtendVcsInfo.builder()
//				.vctId("100000")
//				.vctVersion("v7")
//				.issuer("did:cndid:cndid")
//				.build();
		vcs.add(vcsInfo);
		extend.setVcs(vcs); 
		List<Proof> proofList = new ArrayList<Proof>();
//		VerifiablePresentation<DidLoginExtend> loginvp = new VerifiablePresentation<DidLoginExtend>();
		VerifiablePresentationBuilder<DidLoginExtend> verifiablePresentationBuilder = VerifiablePresentation.builder();
	    verifiablePresentationBuilder.presentationUsage("DID_LOGIN_REQUEST");
	    verifiablePresentationBuilder.proof(proofList);
	    verifiablePresentationBuilder.extend(extend);
	    VerifiablePresentation<DidLoginExtend>  loginvp = verifiablePresentationBuilder.build();
		Response<VerifiablePresentation<DidLoginExtend>> res = didClient.vpSign(loginvp, DidLoginExtend.class);
		log.info("res:{}", res);
		String ret = JsonUtils.toJson(res.getData());
		log.info("ret:{}", ret);

		Response<Boolean> veri = didClient.vpVerify(ret);
		log.info("vpVerify:{}", veri);
//		veri = didClient.vpVerify(ret);
//		r.put("code",200000);
//		r.put("msg","ok");
//		r.put("data", res.getData());
//		log.info("return:{}", JsonUtils.toJson(r));
//		return JsonUtils.toJson(r);
		return JsonUtils.toJson(res);
	}

	private String getXtcs(String xtcsCode) {
		return getXtcs(xtcsCode,null);
	}

	private String getXtcs(String xtcsCode, String prefix) {
		if (GyUtils.isNull(xtcsCode)) {
			return null;
		}
		String code =xtcsCode;
		if (GyUtils.isNotNull(prefix)) {
			code = xtcsCode.replaceFirst("TXW", prefix);
		} 
		return XtcsUtils.getXtcs(code);
	}

	/**
	 * 获取登录凭证信息返回调用
	 * 
	 * @name 获取登录凭证信息返回调用
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取登录凭证信息返回调用")
	@Parameter(name = "request", description = "请求报文")
	@PostMapping(value = "/pub/callback/login", produces = "application/json")
	public String getLoginVPCallback(@RequestParam(required = false, name = "reqId") String reqId,
			@RequestBody Map<String, Object> vpRequestBody) {
		Response<String> result =Response.SuccessResponse();
		result.setCode(200000);
		if (GyUtils.isNull(vpRequestBody)) {
			String msg = "vpRequestBody is null . ";
			log.info(msg);
			result.setMessage(msg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		VerifiablePresentation request = BeanUtils.toBean(vpRequestBody, VerifiablePresentation.class); 
		log.info("request 参数：{}",request);
		String checkMsg = checkvp(request);
		if (GyUtils.isNotNull(checkMsg)) {
			log.info(checkMsg); 
			result.setMessage(checkMsg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		result.setCode(200000); 
		result.setData("true");
		if (GyUtils.isNull(reqId)) {
			String msg = "reqId is null . ";
			log.info(msg);
			result.setMessage(msg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		if (GyUtils.isNull(request)) {
			String msg = "request is null . ";
			log.info(msg);
			result.setMessage(msg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		String key = String.format("%s%s", REQ_ID_PREFIX, reqId);
		String status = CacheUtils.getCacheData(key);
		log.info("request {}, status :{}",reqId,status);
		if (GyUtils.isNull(status)) {
			String msg = String.format("该请求%s已过期！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		if (!GyUtils.isEquals(status, DID_REQ_STATUS_QR)) {
			String msg = String.format("该请求%s状态不正确，请在页面上重新操作！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		CacheUtils.cacheData(key, DID_REQ_STATUS_CALLBACK);
		List<VerifiableCredential> vcList = request.getVerifiableCredential();
		if (GyUtils.isNotNull(vcList)) { 
			VerifiableCredential vc = vcList.get(0);
			String holderDid = vc.getHolder();
			DidCallbackExtendInfo extInfo = BeanUtils.toBean(request.getExtend(), DidCallbackExtendInfo.class);
			DidCredentialSubject cs = BeanUtils.toBean(vc.getCredentialSubject(), DidCredentialSubject.class);
			YhxxbDTO yhxx = null;
			String dlzh = cs.getPhone();  // 获取手机号
			if (GyUtils.isNotNull(dlzh)) {
				yhxx = yhxxService.getYhxxByDlzh(dlzh);
			}
			else if (GyUtils.isNotNull(extInfo) && GyUtils.isNotNull(extInfo.getAuthoriserIdCard())) {
				yhxx = yhxxService.getYhxxBySfzjhm((extInfo.getAuthoriserIdCard()));
			}
			else {
				yhxx = yhxxService.getYhxxByDid(holderDid);
			}
			//手机号码为空 ，进行页面绑定
			if (GyUtils.isNull(yhxx) && GyUtils.isNull(dlzh)) {
				//缓存did 。一次请求对应一个did 
				String tmp = String.format("%s%s", REQ_USER_DID_PREFIX,reqId);
				CacheUtils.cacheData(tmp, holderDid,timeout);
				//缓存did数据，为创建账号做准备
				cs.setExtInfo(extInfo); 
				tmp = String.format("%s%s", REQ_USER_DID_DATA_PREFIX,reqId);
				CacheUtils.cacheData(tmp, JsonUtils.toJson(cs),timeout);
				//进行手机绑定
				key = String.format("%s%s", REQ_ID_PREFIX, reqId);
				CacheUtils.cacheData(key, DID_REQ_PHONE_BIND,timeout);
			}  
			//手机号不为空 ，直接加入账户数据 
			else if (GyUtils.isNull(yhxx) && GyUtils.isNotNull(dlzh)) {
				yhxx = yhxxService.getYhxxBySjhm(dlzh);
				if (GyUtils.isNull(yhxx)) {
					yhxx = new YhxxbDTO();
					yhxx.setYhUuid(IdUtil.fastSimpleUUID());
					yhxx.setDid(holderDid); 
					yhxx.setSjhm1(dlzh); 
					yhxx.setDlzh(dlzh);
					if (GyUtils.isNotNull(cs.getLegalName())) {
						yhxx.setZsxm1(cs.getLegalName());
					} 
					else if (GyUtils.isNotNull(cs.getEntname())) {
						yhxx.setZsxm1(cs.getEntname());
					} 
					else {
						yhxx.setZsxm1("--");
					}
					if (GyUtils.isNotNull(extInfo)) {
						yhxx.setSfzjhm(extInfo.getAuthoriserIdCard());
					}
					yhxx = yhxxService.saveYhxxByDid(yhxx);
				}
				else {
					yhxx.setDid(holderDid); 
					yhxxService.updateDid(yhxx);
				}
				// 企业认证成功
				YhxxbDTO qyxx = new YhxxbDTO();
				qyxx.setQymc(cs.getEntname());
				qyxx.setNsrsbh(cs.getUniscid());
				qyxx.setYhUuid(yhxx.getYhUuid());
				log.info("qyxx:{}",qyxx);
				qyxx = yhxxService.intQyxxByDid(qyxx);
				String tmp = String.format("%s%s", REQ_USER_DATA_PREFIX,reqId);
				CacheUtils.cacheData(tmp, JsonUtils.toJson(yhxx),timeout);
			}
			else {
				String tmp = String.format("%s%s", REQ_USER_DATA_PREFIX,reqId);
				CacheUtils.cacheData(tmp, JsonUtils.toJson(yhxx),timeout);
			}
		}
		else {
			String msg = String.format("返回参数VerifiableCredential为空！");
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
//		return result;
		return JsonUtils.toJson(result);
	}

	private String checkvp(VerifiablePresentation request) {
		if (GyUtils.isNull(request)) {
			return null;
		}
		String consoleUrl = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_LOGIN_URL);
		// 新建客户端
		IDidClient didClient = new DidClient(consoleUrl, DidClient.version15);
		String username = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_USERNAME);
		String pwd = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_PASSWORD);
		// 登录
		Response<AccessToken> login = didClient.login(username, pwd);
		Response<Boolean> veri = didClient.vpVerify(request);
		log.info("checkvp veri:{}",veri);
		if (GyUtils.isNotNull(veri) && GyUtils.isNotNull(veri.getData())
				&& veri.getData()) {
			return null;
		}
		else {
			return null;
//			return veri.getMessage();
		}
	}

	/**
	 * 获取企业实名凭证信息
	 * 
	 * @name 获取企业实名凭证信息
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取企业实名凭证信息")
	@Parameter(name = "request", description = "请求报文")
	@GetMapping(value ="/pub/getvp/busi", produces = "application/json")
	public String  getBusinessLicenseVP(
			@RequestParam(required = false, name = "reqId") String reqId) {
		Response<VerifiablePresentation<ApplyBusinessLicenseExtend>> result =Response.SuccessResponse();
		if (GyUtils.isNull(reqId)) {
			String msg = "reqId is null . ";
			log.info(msg);
			result.setMessage(msg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		String key = String.format("%s%s", REQ_ID_PREFIX, reqId);
		String status = CacheUtils.getCacheData(key);
		log.info("request {}, status :{}",reqId,status);
		if (GyUtils.isNull(status)) {
			String msg = String.format("该请求%s已过期！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		if (!GyUtils.isEquals(status, DID_REQ_STATUS_PAGE)) {
			String msg = String.format("该请求%s状态不正确，请在页面上重新操作！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		CacheUtils.cacheData(key, DID_REQ_STATUS_QR);
		String consoleUrl = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_LOGIN_URL);
		// 新建客户端
		IDidClient didClient = new DidClient(consoleUrl, DidClient.version15);
		String username = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_USERNAME);
		String pwd = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_PASSWORD);
		// 登录
		Response<AccessToken> login = didClient.login(username, pwd);
		log.info("did控制台登录响应：{}", login);
		List<Proof> proofList = new ArrayList<Proof>();
//        Proof pr = Proof.builder()
//        		.build();
		VerifiablePresentation<ApplyBusinessLicenseExtend> busivp = VerifiablePresentation.vpCreateApplyBusinessLicense(proofList);
		busivp.setPresentationUsage("DID_GET_IDENTITY_VC_REQUEST");
		String url = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_BUSI_LICE_CALLBACK_URL);
		if (GyUtils.isNull(url)) {
			String msg = String.format("系统参数%s为空！", XTCS_CODE_TXW_DID_LOGIN_CALLBACK_URL);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		String callbackUrl = String.format("%s?reqId=%s", url,reqId);
		String authorizedName = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_AUTH_NAME);
		if (GyUtils.isNull(authorizedName)) {
			String msg = String.format("系统参数%s为空！", XTCS_CODE_TXW_DID_AUTH_NAME);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		String authorizedNameEn = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_AUTH_EN_NAME);
		if (GyUtils.isNull(authorizedNameEn)) {
			String msg = String.format("系统参数%s为空！", XTCS_CODE_TXW_DID_AUTH_EN_NAME);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		List<String> vctId = Arrays.asList("100001"); 
		String condid  = XtcsUtils.getXtcs(XTCS_CODE_TXW_DID_CONSOLE_DIDCODE);
		condid = "did:cndid:cndid";
		List<String> issuer = Arrays.asList(condid); 
		ApplyBusinessLicenseExtend extend = ApplyBusinessLicenseExtend.builder()
				.requestId(reqId)
				.method("POST")
				.callbackUrl(callbackUrl)
				.authorizedName(authorizedName)
				.authorizedNameEn(authorizedNameEn)
				.vctId(vctId)
				.issuer(issuer)
				.build();
		busivp.setExtend(extend);
		Response<VerifiablePresentation<ApplyBusinessLicenseExtend>> res = didClient.vpCreateApplyBusinessLicense(busivp);
		log.info("res:{}", res);
//		return res;
		Response<Boolean> ver = didClient.vpVerify(res.getData());
		log.info("ver:{}", ver);
		return JsonUtils.toJson(res); 
	}

	/**
	 * 获取企业实名凭证信息返回调用
	 * 
	 * @name 获取企业实名凭证信息返回调用
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取企业实名凭证信息返回调用")
	@Parameter(name = "request", description = "请求报文")
	@PostMapping(value = "/pub/callback/busi", produces = "application/json")
	public String getBusinessLicenseVPCallback(
			@RequestParam(required = false, name = "reqId") String reqId,
			@RequestBody VerifiablePresentation request) {
		log.info("request 参数：{}",request);
		Response<String> result =Response.SuccessResponse();
		result.setCode(200000); 
		result.setData("true");
		if (GyUtils.isNull(reqId)) {
			String msg = "reqId is null . ";
			log.info(msg);
			result.setMessage(msg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		if (GyUtils.isNull(request)) {
			String msg = "request is null . ";
			log.info(msg);
			result.setMessage(msg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		String checkMsg = checkvp(request);
		if (GyUtils.isNotNull(checkMsg)) {
			log.info(checkMsg); 
			result.setMessage(checkMsg); 
			result.setCode(ERROR_CODE_PARAM);
//			return result;
			return JsonUtils.toJson(result);
		}
		String key = String.format("%s%s", REQ_ID_PREFIX, reqId);
		String status = CacheUtils.getCacheData(key);
		log.info("request {}, status :{}",reqId,status);
		if (GyUtils.isNull(status)) {
			String msg = String.format("该请求%s已过期！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		if (!GyUtils.isEquals(status, DID_REQ_STATUS_QR)) {
			String msg = String.format("该请求%s状态不正确，请在页面上重新操作！", reqId);
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
		CacheUtils.cacheData(key, DID_REQ_STATUS_CALLBACK);
		List<VerifiableCredential> vcList = request.getVerifiableCredential();
		if (GyUtils.isNotNull(vcList)) { 
			VerifiableCredential vc = vcList.get(0);
			String holderDid = vc.getHolder();
			log.info("holderDid:{}",holderDid);
			DidCallbackExtendInfo extInfo = BeanUtils.toBean(request.getExtend(), DidCallbackExtendInfo.class);
			DidCredentialSubject cs = BeanUtils.toBean(vc.getCredentialSubject(), DidCredentialSubject.class);
			log.info("cs:{}",cs);
			YhxxbDTO yhxx =  yhxxService.getYhxxByDid(holderDid);
			if (GyUtils.isNull(yhxx)) {
				String tmp = String.format("%s%s", REQ_USER_DID_DLZH_PREFIX, reqId);
				log.info("key:{}",tmp);
				String yhuuid = CacheUtils.getCacheData(tmp);
				log.info("yhuuid:{}",yhuuid);
				yhxx =  yhxxService.getYhxx(yhuuid);
				if (GyUtils.isNotNull(yhxx)) {
					yhxx.setDid(holderDid);
					yhxxService.updateDid(yhxx);
				}
			}
			else {
				String msg = String.format("已经进行过实名认证。不能进行重复认证！");
				CacheUtils.cacheData(key, DID_REQ_STATUS_BUSI_FAILURE);
				CacheUtils.cacheData(DID_REQ_STATUS_BUSI_FAILURE_MSG_PREFIX+reqId, msg);
				log.info(msg);
				result.setMessage(msg);
				result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//				return result;
				return JsonUtils.toJson(result);
			
			}
			log.info("yhxx:{}",yhxx);
			if (GyUtils.isNull(yhxx)) {
				CacheUtils.cacheData(key, DID_REQ_STATUS_BUSI_FAILURE);
				CacheUtils.cacheData(DID_REQ_STATUS_BUSI_FAILURE_MSG_PREFIX+reqId, "根据did未查询到数据！");
			}  
			else {
				if (GyUtils.isNotNull(cs) ) {
					if (GyUtils.isEquals(cs.getEntname(), yhxx.getZsxm1())
							|| GyUtils.isEquals(cs.getLegalName(), yhxx.getZsxm1())) {
						CacheUtils.cacheData(key, DID_REQ_STATUS_BUSI_SUCCESS);
						YhxxbDTO qyxx = new YhxxbDTO();
						qyxx.setQymc(cs.getEntname());
						qyxx.setNsrsbh(cs.getUniscid());
						qyxx.setYhUuid(yhxx.getYhUuid());
						log.info("qyxx:{}",qyxx);
						qyxx = yhxxService.intQyxxByDid(qyxx);
					}
					else {
						CacheUtils.cacheData(key, DID_REQ_STATUS_BUSI_FAILURE);
						CacheUtils.cacheData(DID_REQ_STATUS_BUSI_FAILURE_MSG_PREFIX+reqId, "名称不一致！");
					}
				}
				else {
					CacheUtils.cacheData(key, DID_REQ_STATUS_BUSI_FAILURE);
					CacheUtils.cacheData(DID_REQ_STATUS_BUSI_FAILURE_MSG_PREFIX+reqId, "根据did未查询到数据！");
				}
			}
		}
		else {
			CacheUtils.cacheData(key, DID_REQ_STATUS_BUSI_FAILURE);
			CacheUtils.cacheData(DID_REQ_STATUS_BUSI_FAILURE_MSG_PREFIX+reqId, "返回参数VerifiableCredential为空！");
			String msg = String.format("返回参数VerifiableCredential为空！");
			log.info(msg);
			result.setMessage(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
//			return result;
			return JsonUtils.toJson(result);
		}
//		return result;
		return JsonUtils.toJson(result);
	}

	/**
	 * 获取登录回调响应结果
	 * 
	 * @name 获取登录回调响应结果
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取登录回调响应结果")
	@Parameter(name = "request", description = "请求报文")
	@GetMapping("/pub/backresult/login")
	public CommonResult<R> getLoginCallbackResult(@RequestParam(required = false, name = "reqId") String reqId) {
		CommonResult<R> result = CommonResult.success(null);
		if (GyUtils.isNull(reqId)) {
			String msg = "reqId is null . ";
			log.info(msg);
			result.setMsg(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
			return result;
		}
		String key = String.format("%s%s", REQ_ID_PREFIX, reqId);
		String status = CacheUtils.getCacheData(key);
//		status = "3";
		R r = R.ok().put("status", status);
		key = String.format("%s%s", REQ_USER_DATA_PREFIX, reqId);
		String userJson = CacheUtils.getCacheData(key);
		if (GyUtils.isNotNull(userJson)) {
			YhxxbDTO yhxx = JsonUtils.toBean(userJson, YhxxbDTO.class);
			 String userId = yhxx.getYhUuid(); 
			// 创建访问令牌
	        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, "default", null);
	        // 构建返回结果
	        final AuthLoginRespVO respVO = new AuthLoginRespVO();
	        respVO.setAccessToken(accessTokenDO.getAccessToken());
	        respVO.setRefreshToken(accessTokenDO.getRefreshToken());
	        respVO.setExpiresTime(accessTokenDO.getGqsj());
	    	AuthLoginRespVO login = respVO;
			final Cookie cookie = new Cookie(SsoConstants.COOKIE_TOKEN_KEY,login.getAccessToken());
	        cookie.setPath(SsoConstants.COOKIE_PATH);
	        cookie.setHttpOnly(true);
	        //cookie.setMaxAge(-1);
	        final HttpServletResponse response = ServletUtils.getResponse();
	        response.addCookie(cookie);
//	        return success(login);
	        r.put("authLoginRespVO", login);
		} 
		result.setData(r);
		return result;
	
	}

	/**
	 * 获取认证回调响应结果
	 * 
	 * @name 获取认证回调响应结果
	 * @time 2025-12-12
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
	 */
	@Operation(summary = "获取认证回调响应结果")
	@Parameter(name = "request", description = "请求报文")
	@GetMapping("/pub/backresult/busi")
	public CommonResult<R> getBusiLiceCallbackResult(@RequestParam(required = false, name = "reqId") String reqId) {
		CommonResult<R> result = CommonResult.success(null);
		if (GyUtils.isNull(reqId)) {
			String msg = "reqId is null . ";
			log.info(msg);
			result.setMsg(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
			return result;
		}
		String key = String.format("%s%s", REQ_ID_PREFIX, reqId);
		String status = CacheUtils.getCacheData(key);
		String msg = CacheUtils.getCacheData(DID_REQ_STATUS_BUSI_FAILURE_MSG_PREFIX+reqId);
//		status = "6";
		R r = R.ok().put("status", status)
				.put("msg", msg);
		result.setData(r);
		return result;
	}

}