/*
 *    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 cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TFascEditLog;
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.mapper.TFascTemplateDetailMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TFascTemplateMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TFascEditLogService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TFascTemplateDetailService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TFascTemplateService;
import com.yifu.cloud.plus.v1.yifu.archives.utils.FascConstants;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TFascTemplateExportVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TFascTemplateSearchVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TFascTemplateUpdateVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 法大大专业版模板表
 *
 * @author hgw
 * @date 2025-09-30 16:29:28
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TFascTemplateServiceImpl extends ServiceImpl<TFascTemplateMapper, TFascTemplate> implements TFascTemplateService {

	private final TFascEditLogService tFascEditLogService;
	private final TFascTemplateDetailMapper tFascTemplateDetailMapper;
	private final TFascTemplateDetailService tFascTemplateDetailService;

	/**
	 * 法大大专业版模板表简单分页查询
	 *
	 * @param tFascTemplate 法大大专业版模板表
	 * @return
	 */
	@Override
	public IPage<TFascTemplate> getTFascTemplatePage(Page<TFascTemplate> page, TFascTemplateSearchVo tFascTemplate) {
		return baseMapper.getTFascTemplatePage(page, tFascTemplate);
	}

	@Override
	public List<TFascTemplate> getTFascTemplateListAll(TFascTemplateSearchVo tFascTemplate) {
		return baseMapper.getTFascTemplateListAll(tFascTemplate);
	}

	/**
	 * 法大大专业版模板表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TFascTemplateSearchVo searchVo) {
		String fileName = "法大大模版列表导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TFascTemplateExportVo> list = new ArrayList<>();
		List<String> idList = Common.getList(searchVo.getIds());
		long count = noPageCountDiy(searchVo, idList);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcelFactory.write(out, TFascTemplateExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				WriteSheet writeSheet;
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = baseMapper.getTFascTemplateExport(searchVo, idList);
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcelFactory.writerSheet("法大大模版列表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcelFactory.writerSheet("法大大模版列表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	@Override
	public List<TFascTemplate> noPageDiy(TFascTemplateSearchVo searchVo) {
		LambdaQueryWrapper<TFascTemplate> wrapper = buildQueryWrapper(searchVo);
		if (searchVo != null) {
			List<String> idList = Common.getList(searchVo.getIds());
			if (Common.isNotNull(idList)) {
				wrapper.in(TFascTemplate::getId, idList);
			}
			wrapper.orderByDesc(BaseEntity::getCreateTime);
			if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0) {
				wrapper.last(" limit " + searchVo.getLimitStart() + "," + searchVo.getLimitEnd());
			}
		}
		return baseMapper.selectList(wrapper);
	}

	private Long noPageCountDiy(TFascTemplateSearchVo searchVo, List<String> idList) {
		LambdaQueryWrapper<TFascTemplate> wrapper = buildQueryWrapper(searchVo);
		if (Common.isNotNull(idList)) {
			wrapper.in(TFascTemplate::getId, idList);
		}
		return baseMapper.selectCount(wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(TFascTemplateSearchVo entity) {
		LambdaQueryWrapper<TFascTemplate> wrapper = Wrappers.lambdaQuery();
		if (entity != null) {
			if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
				wrapper.ge(TFascTemplate::getCreateTime, entity.getCreateTimes()[0])
						.le(TFascTemplate::getCreateTime,
								entity.getCreateTimes()[1]);
			}
			if (Common.isNotNull(entity.getCreateName())) {
				wrapper.eq(TFascTemplate::getCreateName, entity.getCreateName());
			}
		}
		wrapper.eq(TFascTemplate::getDeleteFlag, CommonConstants.ZERO_STRING);
		return wrapper;
	}

	/**
	 * @Description: 获取模板，key是id与_与名称的组合
	 * @Author: hgw
	 * @Date: 2025/10/9 9:33
	 * @return: java.util.Map<java.lang.String, com.yifu.cloud.plus.v1.yifu.archives.entity.TFascTemplate>
	 **/
	private Map<String, TFascTemplate> getTemplateMap() {
		List<TFascTemplate> list = baseMapper.getTFascTemplateList(null);
		Map<String, TFascTemplate> map = new HashMap<>();
		if (Common.isNotNull(list)) {
			for (TFascTemplate t : list) {
				map.put(t.getSignTemplateId() + CommonConstants.DOWN_LINE_STRING + t.getSignTemplateName(), t);
			}
		}
		return map;
	}

	@Override
	public R<List<ErrorMessage>> batchUpdate(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TFascTemplateUpdateVo> util1 = new ExcelUtil<>(TFascTemplateUpdateVo.class);
		Map<String, TFascTemplate> templateMap = this.getTemplateMap();
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, TFascTemplateUpdateVo.class, new ReadListener<TFascTemplateUpdateVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TFascTemplateUpdateVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TFascTemplateUpdateVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						errorMessage.setData(data);
						errorMessageList.add(errorMessage);
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					updateTFascTemplate(cachedDataList, errorMessageList, templateMap);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		// 重新计算模板的是否已配置
		tFascTemplateDetailService.initFascTemplateIsMust(null);

		for (ErrorMessage message : errorMessageList) {
			if (!CommonConstants.SAVE_SUCCESS.equals(message.getMessage())) {
				return R.ok(errorMessageList);
			}
		}
		return R.ok();
	}

	private void updateTFascTemplate(List<TFascTemplateUpdateVo> excelVOList, List<ErrorMessage> errorMessageList
			, Map<String, TFascTemplate> templateMap) {
		TFascTemplateUpdateVo excel;
		// 合同类型Map
		Map<String, String> contractNameMap = new HashMap<>();
		for (String contractName : FascConstants.CONTRACT_NAME_ARR) {
			contractNameMap.put(contractName, contractName);
		}
		TFascTemplate tUpdate;
		List<TFascTemplate> tempUpdateList = new ArrayList<>();
		List<TFascEditLog> logList = new ArrayList<>();
		TFascEditLog tFascEditLog;
		TFascEditLog tFascEditLogDetail;
		String editContent;
		String detailEditContent;
		List<TFascTemplateDetail> detailList;
		List<TFascTemplateDetail> updateDetailList = new ArrayList<>();
		TFascTemplateDetail tFascTemplateDetail;
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			if (Common.isEmpty(excel.getContractType()) || contractNameMap.get(excel.getContractType()) == null) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "皖信合同类型错误", excel));
			} else {
				tUpdate = templateMap.get(excel.getSignTemplateId() + CommonConstants.DOWN_LINE_STRING + excel.getSignTemplateName());
				if (tUpdate == null) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), "根据模版ID、模版名称，未找到模板", excel));
				} else {
					tFascEditLog = new TFascEditLog();
					tFascEditLog.setMainId(tUpdate.getId());
					tFascEditLog.setMainType(CommonConstants.ONE_STRING);
					if (excel.getContractType().equals(tUpdate.getContractType())) {
						editContent = "“合同类型”由“" + tUpdate.getContractType() + "”→“" + excel.getContractType() + "”";
					} else {
						if (Common.isEmpty(tUpdate.getContractType())) {
							editContent = "“合同类型”由“空”→“" + excel.getContractType() + "”";
						} else {
							editContent = "“合同类型”由“" + tUpdate.getContractType() + "”→“" + excel.getContractType() + "”";
							// 此处代码去掉，因为即使变了类型，由于都是非必填，这里也是已配置
							/*if (Common.isNotNull(tUpdate.getIsMustEdit()) && tUpdate.getIsMustEdit().equals(CommonConstants.ONE_STRING)) {
								tUpdate.setIsMustEdit(CommonConstants.ZERO_STRING);
								editContent += "；“法大大必填是否已配置”由“已配置”→“未配置”";
							}*/
							// 合同类型变更，清空明细配置：
							tFascTemplateDetail = new TFascTemplateDetail();
							tFascTemplateDetail.setSignTemplateId(tUpdate.getSignTemplateId());
							detailList = tFascTemplateDetailMapper.getTFascTemplateDetailList(tFascTemplateDetail);
							if (detailList != null && !detailList.isEmpty()) {
								for (TFascTemplateDetail detail : detailList) {
									if (Common.isNotNull(detail.getHrField())) {
										tFascEditLogDetail = new TFascEditLog();
										tFascEditLogDetail.setMainId(detail.getId());
										tFascEditLogDetail.setMainType(CommonConstants.TWO_STRING);
										detailEditContent = "“皖信字段”由“" + detail.getHrField() + "”→“空”；“是否已配置”由“已配置”→“未配置”";
										tFascEditLogDetail.setEditContent(detailEditContent);
										logList.add(tFascEditLogDetail);
										detail.setHrField(null);
										detail.setHrFieldId(null);
										detail.setIsEdit(CommonConstants.ZERO_STRING);
										updateDetailList.add(detail);
									}
								}
							}
						}
						tUpdate.setContractType(excel.getContractType());
						// 添加到更新list
						tempUpdateList.add(tUpdate);
					}
					tFascEditLog.setEditContent(editContent);
					logList.add(tFascEditLog);
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
				}
			}
		}
		// 更新模板
		if (!tempUpdateList.isEmpty()) {
			this.updateBatchById(tempUpdateList);
		}
		// 更新日志
		if (!logList.isEmpty()) {
			tFascEditLogService.saveBatch(logList);
		}
		// 更新映射表
		if (!updateDetailList.isEmpty()) {
			tFascTemplateDetailService.updateBatchById(updateDetailList);
		}
		// 重新计算模板的是否已配置————放到循环外面了
	}

}
