/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasc.open.api.exception.ApiException;
import com.fasc.open.api.v5_1.res.template.SignTemplateListInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.FddContractInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TAttaInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeContractInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeContractPreMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.utils.FascUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 法大大专业版
 *
 * @author hgw
 * @date 2025-9-29 14:37:03
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class FascServiceImpl extends ServiceImpl<FddContractInfoMapper, FddContractInfo> implements FascService {

	private final FascUtil fascUtil;

	private final TFascEditLogService tFascEditLogService;
	private final TFascPushLogService tFascPushLogService;
	private final TFascTemplateService tFascTemplateService;
	private final TFascTemplateDetailService tFascTemplateDetailService;
	private final TEmployeeContractPreMapper tEmployeeContractPreMapper;
	private final TEmployeeContractInfoMapper tEmployeeContractInfoMapper;
	private final TAttaInfoMapper tAttaInfoMapper;

	private final OSSUtil ossUtil;
	private final static String FASC_NO_CONTRACT = "未找到合同自动化";
	private final static String FASC_NO_EMP_CONTRACT = "未找到自动生成的员工合同";
	private final static String FASC_NO_TEMPLATE = "未找到新法大大模板";

	@Override
	public R<String> getTemplate(String templateName) throws ApiException {
		// templateName 签署任务模板名称
		List<SignTemplateListInfo> list = fascUtil.getTemplateList(templateName, tFascPushLogService);
		if (list != null && !list.isEmpty()) {
			List<TFascTemplate> tList = new ArrayList<>();
			List<TFascTemplateDetail> detailList = new ArrayList<>();
			fascUtil.getTemplateDetailList(list, tList, detailList, tFascPushLogService);
			// 拉取到数据再更新：
			if (!tList.isEmpty() && !detailList.isEmpty()) {
				String editContent1 = "定时任务同步，拉取到数据";
				String editContent2 = "定时任务同步，法大大无该数据";
				List<TFascTemplate> updateMain = new ArrayList<>();
				List<TFascTemplateDetail> updateDetail = new ArrayList<>();

				List<TFascTemplate> allMain = tFascTemplateService.noPageDiy(null);
				List<TFascTemplateDetail> allDetail = tFascTemplateDetailService.getTFascTemplateDetailList(null);
				List<TFascEditLog> logList = new ArrayList<>();
				if (allMain == null || allMain.isEmpty()) {
					// 都是新的：
					tFascTemplateService.saveBatch(tList);
					tFascTemplateDetailService.saveOrUpdateBatch(detailList);
					for (TFascTemplate t : tList) {
						this.addFascLogToList(t.getId(), CommonConstants.ONE_STRING, editContent1, logList);
					}
					for (TFascTemplateDetail t : detailList) {
						this.addFascLogToList(t.getId(), CommonConstants.TWO_STRING, editContent1, logList);
					}
				} else {
					// 混合老新数据
					Map<String, TFascTemplate> oldMainMap = new HashMap<>();
					Map<String, TFascTemplateDetail> oldDetailMap = new HashMap<>();
					for (TFascTemplate t : allMain) {
						oldMainMap.put(t.getSignTemplateId(), t);
					}
					for (TFascTemplateDetail t : allDetail) {
						oldDetailMap.put(t.getSignTemplateId() + CommonConstants.DOWN_LINE_STRING + t.getFascFieldId(), t);
					}
					// 主表：
					TFascTemplate oldMain;
					String logId;
					for (TFascTemplate t : tList) {
						oldMain = oldMainMap.get(t.getSignTemplateId());
						if (oldMain != null) {
							t.setId(oldMain.getId());
						} else {
							logId = String.valueOf(UUID.randomUUID()).replaceAll("-", "");
							t.setId(logId);
						}
						this.addFascLogToList(t.getId(), CommonConstants.ONE_STRING, editContent1, logList);
						updateMain.add(t);
						oldMainMap.remove(t.getSignTemplateId());
					}
					for (TFascTemplate t : oldMainMap.values()) {
						this.addFascLogToList(t.getId(), CommonConstants.ONE_STRING, editContent2, logList);
						t.setDeleteFlag(CommonConstants.DELETE_FLAG);
						updateMain.add(t);
					}
					// 映射表：
					TFascTemplateDetail oldDetail;
					for (TFascTemplateDetail t : detailList) {
						oldDetail = oldDetailMap.get(t.getSignTemplateId() + CommonConstants.DOWN_LINE_STRING + t.getFascFieldId());
						if (oldDetail != null) {
							t.setId(oldDetail.getId());
						} else {
							logId = String.valueOf(UUID.randomUUID()).replaceAll("-", "");
							t.setId(logId);
						}
						this.addFascLogToList(t.getId(), CommonConstants.TWO_STRING, editContent1, logList);
						updateDetail.add(t);
						oldDetailMap.remove(t.getSignTemplateId() + CommonConstants.DOWN_LINE_STRING + t.getFascFieldId());
					}
					for (TFascTemplateDetail t : oldDetailMap.values()) {
						this.addFascLogToList(t.getId(), CommonConstants.TWO_STRING, editContent2, logList);
						t.setDeleteFlag(CommonConstants.DELETE_FLAG);
						updateDetail.add(t);
					}
				}
				// 更新日志
				if (!logList.isEmpty()) {
					tFascEditLogService.saveBatch(logList);
				}
				// 更新模板
				if (!updateMain.isEmpty()) {
					tFascTemplateService.saveOrUpdateBatch(updateMain);
				}
				// 更新模板映射
				if (!updateDetail.isEmpty()) {
					tFascTemplateDetailService.saveOrUpdateBatch(updateDetail);
				}
				// 重新刷新主模板表的必填是否已填
				tFascTemplateDetailService.initFascTemplateIsMust(null);
			}
		}
		return R.ok();
	}

	// 获取模板详情预览链接
	@Override
	public R<String> getTemplateDetailUrl(String signTemplateId) throws ApiException {
		// templateName 签署任务模板名称
		return fascUtil.getTemplateDetailUrl(signTemplateId, tFascPushLogService);
	}

	/**
	 * 向list里添加新日志
	 */
	private void addFascLogToList(String mainId, String mainType, String editContent, List<TFascEditLog> logList) {
		TFascEditLog log = new TFascEditLog();
		log.setMainId(mainId);
		log.setMainType(mainType);
		log.setEditContent(editContent);
		logList.add(log);
	}


	/**
	 * @param id TEmployeeContractPre主键
	 * @Description: 推送法大大任务
	 * @Author: hgw
	 * @Date: 2025/10/15 16:40
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> submitContract(String id) throws ApiException {
		// templateName 签署任务模板名称
		TEmployeeContractPre contract = tEmployeeContractPreMapper.selectById(id);
		if (contract == null) {
			return R.failed(FASC_NO_CONTRACT);
		}
		if (Common.isEmpty(contract.getContractId())) {
			return R.failed("未生成合同，请联系管理员");
		}

		TEmployeeContractInfo empContract = tEmployeeContractInfoMapper.selectById(contract.getContractId());
		if (empContract == null) {
			return R.failed(FASC_NO_EMP_CONTRACT);
		}

		if (Common.isEmpty(contract.getFadadaTemplateId())) {
			return R.failed("未找到合同模板ID，请联系管理员");
		}
		if (Common.isEmpty(contract.getSignType())) {
			return R.failed("签署方式为空，请联系管理员");
		} else if (!CommonConstants.ONE_STRING.equals(contract.getSignType())) {
			return R.failed("签署方式不是电子签，不可发起电子签署");
		}
		if (Common.isEmpty(contract.getProcessStatus())) {
			return R.failed("合同无状态，请联系管理员");
		} else if (!(CommonConstants.dingleDigitStrArray[1].equals(contract.getProcessStatus())
				|| CommonConstants.dingleDigitStrArray[5].equals(contract.getProcessStatus())
				|| CommonConstants.dingleDigitStrArray[7].equals(contract.getProcessStatus()))) {
			return R.failed("合同状态不是待发起、发起失败、签署失败，不可发起电子签署！");
		}
		if (Common.isNotNull(contract.getRequestId())) {
			return R.failed("合同已发起，请勿重复发起！");
		}
		TFascTemplate tFascTemplate = tFascTemplateService.getById(contract.getFadadaTemplateId());
		if (tFascTemplate == null) {
			return R.failed(FASC_NO_TEMPLATE);
		} else if (!"valid".equals(tFascTemplate.getSignTemplateStatus())) {
			return R.failed("法大大模版状态不是“启用”，不可发起电子签署");
		}
		TFascTemplateDetail detail = new TFascTemplateDetail();
		detail.setSignTemplateId(contract.getFadadaTemplateId());
		List<TFascTemplateDetail> detailList = tFascTemplateDetailService.getTFascTemplateDetailList(detail);
		// - 判断是否入职超过1个月——接口入口做了

		R<String> requestInfo = fascUtil.submitContract(contract, tFascPushLogService, tEmployeeContractPreMapper, tFascTemplate, detailList);
		return requestInfo;

	}

	/**
	 * @param id TEmployeeContractPre主键
	 * @Description: 撤销签署任务
	 * @Author: hgw
	 * @Date: 2025/10/15 16:40
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> cancelTask(String id) throws ApiException {
		// templateName 签署任务模板名称
		TEmployeeContractPre contract = tEmployeeContractPreMapper.selectById(id);
		if (contract == null) {
			return R.failed(FASC_NO_CONTRACT);
		}
		if (Common.isEmpty(contract.getRequestId())) {
			return R.failed("无requestId，请检查数据");
		}
		// TODO - 判断什么状态撤销等，需要产品定

		return fascUtil.cancelTask(contract, tFascPushLogService, tEmployeeContractPreMapper);

	}

	/**
	 * @param id TEmployeeContractPre主键
	 * @Description: 催办签署任务
	 * @Author: hgw
	 * @Date: 2025/10/15 17:56
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public R<String> urgeTask(String id) throws ApiException {
		// templateName 签署任务模板名称
		TEmployeeContractPre contract = tEmployeeContractPreMapper.selectById(id);
		if (contract == null) {
			return R.failed(FASC_NO_CONTRACT);
		}
		if (Common.isEmpty(contract.getRequestId())) {
			return R.failed("无requestId，请检查数据");
		}
		// TODO - 判断什么状态催办等，需要产品定

		return fascUtil.urgeTask(contract, tFascPushLogService, tEmployeeContractPreMapper);

	}
	/**
	 * @param id TEmployeeContractPre主键
	 * @Description: 获取附件
	 * @Author: hgw
	 * @Date: 2025/10/15 17:56
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@Override
	public boolean getFileByRequestId(String id) throws ApiException {
		// templateName 签署任务模板名称
		TEmployeeContractPre contract = tEmployeeContractPreMapper.selectById(id);
		if (contract == null) {
			return false;
		}
		if (Common.isEmpty(contract.getRequestId())) {
			// return R.failed("无requestId，请检查数据")
			return false;
		}
		return fascUtil.getFileByRequestId(contract, tFascPushLogService, tAttaInfoMapper, ossUtil);
	}


}
