package com.yifu.cloud.plus.v1.yifu.archives.utils;

import com.fasc.open.api.bean.base.BaseRes;
import com.fasc.open.api.bean.common.OpenId;
import com.fasc.open.api.bean.common.TemplateField;
import com.fasc.open.api.exception.ApiException;
import com.fasc.open.api.v5_1.client.OpenApiClient;
import com.fasc.open.api.v5_1.client.ServiceClient;
import com.fasc.open.api.v5_1.client.TemplateClient;
import com.fasc.open.api.v5_1.req.template.GetSignTemplateListReq;
import com.fasc.open.api.v5_1.req.template.SignTemplateDetailReq;
import com.fasc.open.api.v5_1.req.template.SignTemplateListFilterInfo;
import com.fasc.open.api.v5_1.res.service.AccessTokenRes;
import com.fasc.open.api.v5_1.res.template.DocumentInfo;
import com.fasc.open.api.v5_1.res.template.SignTemplateDetailRes;
import com.fasc.open.api.v5_1.res.template.SignTemplateListInfo;
import com.fasc.open.api.v5_1.res.template.SignTemplateListRes;
import com.yifu.cloud.plus.v1.yifu.archives.config.FascConfig;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TFascPushLog;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TFascTemplate;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TFascTemplateDetail;
import com.yifu.cloud.plus.v1.yifu.archives.service.TFascPushLogService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.CheckedException;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.LocalDateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hgw
 * @Date: 2025-9-25 14:24:53
 * @return: 企业法大大专业版配置
 **/
@Component
public class FascUtil {

	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private FascConfig fascConfig;

	/**
	 * @Description: 获取token
	 * @Author: huyc
	 * @Date: 2023/7/28 14:46
	 * @return: java.lang.String
	 **/
	public String getFascToken(OpenApiClient openApiClient) throws ApiException {
		String tokenKey = CacheConstants.FASC_ACCOSS_TOKEN;
		Object wxToken = redisTemplate.opsForValue().get(tokenKey);
		if (null != wxToken) {
			return String.valueOf(wxToken);
		}
		if (openApiClient == null) {
			openApiClient = new OpenApiClient(fascConfig.getAppId(), fascConfig.getAppSecret(), fascConfig.getAppUrl());
		}
		ServiceClient serviceClient = new ServiceClient(openApiClient);
		BaseRes<AccessTokenRes> res = serviceClient.getAccessToken();
		String token = null;
		if (res != null && res.isSuccess() && res.getData() != null && res.getData().getAccessToken() != null) {
			token = res.getData().getAccessToken();
		}
		if (Common.isEmpty(token)) {
			throw new CheckedException("获取法大大专业版token失败");
		}
		redisTemplate.opsForValue().set(tokenKey, token);
		redisTemplate.expire(tokenKey, 3600, TimeUnit.SECONDS);
		return token;
	}

	/**
	 * @Description: 获取模板
	 * @Author: hgw
	 * @Date: 2025/10/10 17:59
	 * @return: java.util.List<com.fasc.open.api.v5_1.res.template.SignTemplateListInfo>
	 **/
	public List<SignTemplateListInfo> getTemplateList(String templateName, TFascPushLogService tFascPushLogService)
			throws ApiException {
		OpenApiClient openApiClient = new OpenApiClient(fascConfig.getAppId(), fascConfig.getAppSecret(), fascConfig.getAppUrl());
		TemplateClient templateClient = new TemplateClient(openApiClient);
		String accessToken = this.getFascToken(openApiClient);

		GetSignTemplateListReq getSignTemplateListReq = new GetSignTemplateListReq();
		getSignTemplateListReq.setListPageNo(1);
		getSignTemplateListReq.setListPageSize(100);
		OpenId ownerId = new OpenId();
		ownerId.setIdType(CacheConstants.FASC_ID_TYPE);
		ownerId.setOpenId(fascConfig.getOpenId());
		getSignTemplateListReq.setOwnerId(ownerId);
		SignTemplateListFilterInfo signTemplateListFilterInfo = new SignTemplateListFilterInfo();
		if (Common.isNotNull(templateName)) {
			// 签署任务模板名称，如果传了该参数，会根据名称模糊匹配查询，长度最大100个字符。
			signTemplateListFilterInfo.setSignTemplateName(templateName);
		} else {
			signTemplateListFilterInfo.setSignTemplateName("");
		}
		getSignTemplateListReq.setListFilter(signTemplateListFilterInfo);
		getSignTemplateListReq.setAccessToken(accessToken);

		// 新增推送日志
		TFascPushLog pushLog = new TFascPushLog();
		pushLog.setTransReferenceId(fascConfig.getOpenId());
		pushLog.setPushData(getSignTemplateListReq.toString());
		pushLog.setTaskStatus(CommonConstants.ZERO_STRING);
		pushLog.setTypeKey("获取所有模板");
		pushLog.setTypeName("获取模板");
		tFascPushLogService.save(pushLog);

		BaseRes<SignTemplateListRes> res = templateClient.getSignTemplateList(getSignTemplateListReq);
		List<SignTemplateListInfo> list = null;
		if (res != null) {
			// 更新日志
			pushLog.setReturnData(res.toString());
			pushLog.setTaskStatus(res.isSuccess() ? CommonConstants.ONE_STRING : CommonConstants.TWO_STRING);
			tFascPushLogService.updateById(pushLog);

			if (res.isSuccess() && res.getData() != null && res.getData().getSignTemplates() != null
					&& !res.getData().getSignTemplates().isEmpty()) {
				list = res.getData().getSignTemplates();
				if (res.getData().getListPageCount() != null) {
					int listPageCount = res.getData().getListPageCount();
					// 超过1页的循环查询
					if (listPageCount > 1) {
						for (int i = 2; i <= listPageCount; i++) {
							getSignTemplateListReq.setListPageNo(i);

							pushLog = new TFascPushLog();
							pushLog.setTransReferenceId(fascConfig.getOpenId());
							pushLog.setPushData(getSignTemplateListReq.toString());
							pushLog.setTaskStatus(CommonConstants.ZERO_STRING);
							pushLog.setTypeKey(pushLog.getId() + "获取所有模板" + i);
							pushLog.setTypeName("分页循环获取模板");
							tFascPushLogService.save(pushLog);

							res = templateClient.getSignTemplateList(getSignTemplateListReq);
							if (res != null) {
								// 更新日志
								pushLog.setReturnData(res.toString());
								pushLog.setTaskStatus(res.isSuccess() ? CommonConstants.ONE_STRING : CommonConstants.TWO_STRING);
								tFascPushLogService.updateById(pushLog);

								if (res.getData().getSignTemplates() != null && !res.getData().getSignTemplates().isEmpty()) {
									list.addAll(res.getData().getSignTemplates());
								}
							}
						}
					}
				}
			}
		}
		return list;
	}

	/**
	 * @Description: 获取明细映射
	 * @Author: hgw
	 * @Date: 2025/10/10 17:59
	 * @return: void
	 **/
	public void getTemplateDetailList(List<SignTemplateListInfo> templateList, List<TFascTemplate> tList
			, List<TFascTemplateDetail> detailList, TFascPushLogService tFascPushLogService) throws ApiException {
		OpenApiClient openApiClient = new OpenApiClient(fascConfig.getAppId(), fascConfig.getAppSecret(), fascConfig.getAppUrl());
		TemplateClient templateClient = new TemplateClient(openApiClient);
		String accessToken = this.getFascToken(openApiClient);

		OpenId openId = new OpenId();
		openId.setIdType(CacheConstants.FASC_ID_TYPE);
		openId.setOpenId(fascConfig.getOpenId());
		List<DocumentInfo> list = null;
		if (templateList != null && !templateList.isEmpty()) {
			// 调用查询模板详情接口
			SignTemplateDetailReq signTemplateDetailReq;
			BaseRes<SignTemplateDetailRes> res;
			TFascTemplate template;
			TFascTemplateDetail detail;
			String signTemplateId;
			String fieldType;
			String isMust;
			StringBuilder zhangName;
			for (SignTemplateListInfo mainInfo : templateList) {
				if (mainInfo != null && mainInfo.getSignTemplateId() != null) {
					zhangName = new StringBuilder();
					template = new TFascTemplate();
					signTemplateId = mainInfo.getSignTemplateId();
					template.setSignTemplateId(signTemplateId);
					template.setSignTemplateName(mainInfo.getSignTemplateName());
					template.setSignTemplateStatus(mainInfo.getSignTemplateStatus());
					template.setFascCreateTime(LocalDateTimeUtils.coverStringToLDT(mainInfo.getCreateTime()));
					template.setUpdateTime(LocalDateTimeUtils.coverStringToLDT(mainInfo.getUpdateTime()));
					// 有可能不对：template.setCompanyName(mainInfo.getCatalogName());
					template.setCompanyName(mainInfo.getCatalogName());
					template.setCreatorMemberName(mainInfo.getCreatorMemberName());
					template.setDeleteFlag(CommonConstants.NOT_DELETE_FLAG);
					tList.add(template);

					signTemplateDetailReq = new SignTemplateDetailReq();
					signTemplateDetailReq.setOwnerId(openId);
					signTemplateDetailReq.setSignTemplateId(mainInfo.getSignTemplateId());
					signTemplateDetailReq.setAccessToken(accessToken);

					// 新增推送日志
					TFascPushLog pushLog = new TFascPushLog();
					pushLog.setTransReferenceId(fascConfig.getOpenId());
					pushLog.setPushData(signTemplateDetailReq.toString());
					pushLog.setTaskStatus(CommonConstants.ZERO_STRING);
					pushLog.setTypeKey("获取所有明细映射");
					pushLog.setTypeName("获取明细映射");
					tFascPushLogService.save(pushLog);

					res = templateClient.getSignTemplateDetail(signTemplateDetailReq);

					if (res != null) {
						// 更新日志
						pushLog.setReturnData(res.toString());
						pushLog.setTaskStatus(res.isSuccess() ? CommonConstants.ONE_STRING : CommonConstants.TWO_STRING);
						tFascPushLogService.updateById(pushLog);

						if (res.isSuccess() && res.getData() != null && res.getData().getDocs() != null
								&& !res.getData().getDocs().isEmpty()) {
							if (list == null) {
								list = new ArrayList<>();
							}
							// 循环文档（1,2,3）
							for (DocumentInfo doc : res.getData().getDocs()) {
								if (doc.getDocFields() != null) {
									// 循环文档里的字段
									for (TemplateField fields : doc.getDocFields()) {
										fieldType = fields.getFieldType();
										if (Common.isNotNull(fieldType)) {
											if (FascConstants.FIELD_TEXT_TYPE.contains(fieldType)) {
												// 文本数字等控件
												detail = new TFascTemplateDetail();
												detail.setSignTemplateId(signTemplateId);
												detail.setFascField(fields.getFieldName());
												detail.setFascFieldId(fields.getFieldId());
												isMust = CommonConstants.ONE_STRING;
												if (this.isFieldNotRequired(fields, fieldType)) {
													isMust = CommonConstants.ZERO_STRING;
												}
												detail.setIsMust(isMust);
												detail.setDeleteFlag(CommonConstants.NOT_DELETE_FLAG);
												detailList.add(detail);
											} else if (FascConstants.FIELD_ZHANG_TYPE.contains(fieldType)) {
												// 章控件
												if (zhangName.length() > 0) {
													zhangName.append("；");
												}
												zhangName.append(fields.getFieldName());
											}
										}
									}
								}
							}
						}
					}
					template.setZhangName(zhangName.toString());
				}
			}
		}
	}

	/**
	 * @param fields    字段属性
	 * @param fieldType 字段类型
	 * @Description: 统一判断字段是否非必填
	 * @Author: hgw
	 * @Date: 2025/10/10 16:10
	 * @return: boolean
	 **/
	private boolean isFieldNotRequired(TemplateField fields, String fieldType) {
		switch (fieldType) {
			case "text_single_line":
				return fields.getFieldTextSingleLine() != null && Boolean.FALSE.equals(fields.getFieldTextSingleLine().getRequired());
			case "text_multi_line":
				return fields.getFieldTextMultiLine() != null && Boolean.FALSE.equals(fields.getFieldTextMultiLine().getRequired());
			case "number":
				return fields.getFieldNumber() != null && Boolean.FALSE.equals(fields.getFieldNumber().getRequired());
			case "id_card":
				return fields.getFieldIdCard() != null && Boolean.FALSE.equals(fields.getFieldIdCard().getRequired());
			case "fill_date":
				return fields.getFieldFillDate() != null && Boolean.FALSE.equals(fields.getFieldFillDate().getRequired());
			default:
				return false;
		}
	}

}
