/*
 *    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.core.toolkit.Wrappers;
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 com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
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 TFascCompanyService tFascCompanyService;

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

	@Override
	public R<String> getTemplate(String templateName) throws ApiException {

		String userId = "-1";
		String userName = "系统";
		YifuUser user = SecurityUtils.getUser();
		if (user != null && Common.isNotNull(user.getId())) {
			userId = user.getId();
			userName = user.getNickname();
		}
		List<TFascCompany> companyList = tFascCompanyService.getTFascCompanyAllList();
		if (companyList != null && !companyList.isEmpty()) {
			// templateName 签署任务模板名称
			List<TFascTemplate> tList = new ArrayList<>();
			List<SignTemplateListInfo> listSubList;
			List<TFascTemplate> tempList = new ArrayList<>();
			List<TFascTemplateDetail> detailList = new ArrayList<>();
			List<TFascTemplateDetail> detailSubList;
			for (TFascCompany company : companyList) {
				listSubList = fascUtil.getTemplateList(templateName, tFascPushLogService, company);
				if (listSubList != null && !listSubList.isEmpty()) {
					detailSubList = new ArrayList<>();
					fascUtil.getTemplateDetailList(listSubList, tempList, detailSubList, tFascPushLogService, company);
					if (!tempList.isEmpty() && !detailSubList.isEmpty()) {
						tList.addAll(tempList);
						detailList.addAll(detailSubList);
					}
				}
			}

			// 拉取到数据再更新：
			if (!tList.isEmpty() && !detailList.isEmpty()) {
				String editContent1 = "定时任务同步，拉取到数据";
				String editContent2 = "定时任务同步，法大大无该数据";
				if (!"-1".equals(userId)) {
					editContent1 = "手动拉取任务同步，拉取到数据";
					editContent2 = "手动拉取任务同步，法大大无该数据";
				}
				List<TFascTemplate> updateMain = new ArrayList<>();
				List<TFascTemplateDetail> updateDetail = new ArrayList<>();

				List<TFascTemplate> allMain = tFascTemplateService.getTFascTemplateListAll(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, userId, userName);
					}
					for (TFascTemplateDetail t : detailList) {
						this.addFascLogToList(t.getId(), CommonConstants.TWO_STRING, editContent1, logList, userId, userName);
					}
				} 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, userId, userName);
						updateMain.add(t);
						oldMainMap.remove(t.getSignTemplateId());
					}
					for (TFascTemplate t : oldMainMap.values()) {
						this.addFascLogToList(t.getId(), CommonConstants.ONE_STRING, editContent2, logList, userId, userName);
						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());
							t.setHrField(oldDetail.getHrField());
							t.setHrFieldId(oldDetail.getHrFieldId());
						} else {
							logId = String.valueOf(UUID.randomUUID()).replaceAll("-", "");
							t.setId(logId);
						}
						this.addFascLogToList(t.getId(), CommonConstants.TWO_STRING, editContent1, logList, userId, userName);
						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, userId, userName);
						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 签署任务模板名称
		TFascCompany company = null;
		TFascTemplate tFascTemplate = tFascTemplateService.getOne(Wrappers.<TFascTemplate>query()
				.lambda().eq(TFascTemplate::getSignTemplateId, signTemplateId)
				.last(CommonConstants.LAST_ONE_SQL));
		if (tFascTemplate != null && Common.isNotNull(tFascTemplate.getCompanyId())) {
			company = tFascCompanyService.getById(tFascTemplate.getCompanyId());
		}
		if (company == null) {
			return R.failed("无公司信息，请检查数据!");
		}
		return fascUtil.getTemplateDetailUrl(signTemplateId, tFascPushLogService, company);
	}

	/**
	 * 向list里添加新日志
	 */
	private void addFascLogToList(String mainId, String mainType, String editContent, List<TFascEditLog> logList, String userId, String userName) {
		TFascEditLog log = new TFascEditLog();
		log.setMainId(mainId);
		log.setMainType(mainType);
		log.setEditContent(editContent);
		log.setCreateBy(userId);
		log.setCreateName(userName);
		log.setCreateTime(LocalDateTime.now());
		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.ZERO_STRING.equals(contract.getSignType())) {
			return R.failed("签署方式不是电子签，不可发起电子签署");
		}
		// 如果状态过多，可以改为这个：
		// ArrayUtils.contains(forbidStatusArr, tGzOfferInfo.getOfferStatus())

		if (Common.isNotNull(contract.getRequestId())) {
			return R.failed("合同已发起，请勿重复发起！");
		}
		TFascTemplate tFascTemplate = tFascTemplateService.getOne(Wrappers.<TFascTemplate>query()
				.lambda().eq(TFascTemplate::getSignTemplateId, contract.getFadadaTemplateId())
				.last(CommonConstants.LAST_ONE_SQL));
		if (tFascTemplate == null) {
			return R.failed(FASC_NO_TEMPLATE);
		} else if (!"valid".equals(tFascTemplate.getSignTemplateStatus())) {
			return R.failed("法大大模版状态不是“启用”，不可发起电子签署");
		}
		List<TFascTemplateDetail> detailList = tFascTemplateDetailService.getTDetailListByFieldType(contract.getFadadaTemplateId());
		// - 判断是否入职超过1个月——接口入口做了

		TFascCompany company = tFascCompanyService.getById(tFascTemplate.getCompanyId());

		R<String> requestInfo = fascUtil.submitContract(contract, tFascPushLogService, tEmployeeContractPreMapper, tFascTemplate, detailList, company);
		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，请检查数据");
		}
		TFascCompany company = getTFascCompany(contract);
		if (company == null) {
			return R.failed("无公司信息，请检查数据!");
		}
		return fascUtil.cancelTask(contract, tFascPushLogService, tEmployeeContractPreMapper, company);

	}

	private TFascCompany getTFascCompany(TEmployeeContractPre contract) {
			TFascCompany company = null;
		if (Common.isNotNull(contract.getFadadaTemplateId())) {
			TFascTemplate tFascTemplate = tFascTemplateService.getOne(Wrappers.<TFascTemplate>query()
					.lambda().eq(TFascTemplate::getSignTemplateId, contract.getFadadaTemplateId())
					.last(CommonConstants.LAST_ONE_SQL));
			if (tFascTemplate != null && Common.isNotNull(tFascTemplate.getCompanyId())) {
				company = tFascCompanyService.getById(tFascTemplate.getCompanyId());
			}
		}
		return company;
	}

	/**
	 * @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，请检查数据");
		}

		TFascCompany company = getTFascCompany(contract);
		if (company == null) {
			return R.failed("无公司信息，请检查数据!");
		}
		return fascUtil.urgeTask(contract, tFascPushLogService, tEmployeeContractPreMapper, company);

	}
	/**
	 * @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;
		}
		TFascCompany company = getTFascCompany(contract);
		if (company == null) {
			return false;
		}
		return fascUtil.getFileByRequestId(contract, tFascPushLogService, tAttaInfoMapper, ossUtil, company);
	}


}
