package com.yifu.cloud.plus.v1.ekp.service.impl.QwExce;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.ekp.config.WxConfig;
import com.yifu.cloud.plus.v1.ekp.entity.EkpInvoiceInfo;
import com.yifu.cloud.plus.v1.ekp.mapper.QwExcelApiMapper;
import com.yifu.cloud.plus.v1.ekp.service.QwExcelApiService;
import com.yifu.cloud.plus.v1.ekp.util.SmartSheetDebugService;
import com.yifu.cloud.plus.v1.ekp.util.WeComSmartSheetManager;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MonthCalculationUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

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

/**
 * @Author fxj
 * @Date 2025/9/26
 * @Description
 * @Version 1.0
 */
@Log4j2
@Service
public class QwExcelApiServiceImpl extends ServiceImpl<QwExcelApiMapper, EkpInvoiceInfo> implements QwExcelApiService {
	@Autowired
	private SmartSheetDebugService debugService;
	@Autowired
	private WxConfig wxConfig;
	@Autowired
	WeComSmartSheetManager weComSmartSheetManager;

	@Override
	public void wxExcelApi() {
		//获取accessToken
		String corpId = "wwbcb090af0dfe50e5";
		//HR审批应用 agentid: 1000009，corpSecret：R0nKkvsY-oF41fuQvUXZ-kFG3_g_Ce0bpZt6mByx524
		String corpSecret = "16kqEL_eU-ARwYyqLgEBWHgxm8gXVnkzv_eJMLy9NpU";
		String docId = "dcTSMCj4lWV9MEP7lquZacOY8WS4g-iHxP_jVYA02tdYwb2YYc3BpDR8NrFWkEngHUg8abET4eTIpo9Zv-571NEA";
		//智能表格发票数据表ID
		String[] sheetIds = new String[]{"q979lj","JdsXE8", "nyaxYZ" ,"lbzy8S"};
		String sheetId;
		String accessToken = weComSmartSheetManager.getAccessToken(corpId,corpSecret);
		if (accessToken == null || accessToken.isEmpty()) {
			log.error("获取access_token失败");
			return;
		}

		int batchSize = 1000;
		int batchCount = 0;
		String[] monthRange =null;
		List<Map<String, Object>> records = new ArrayList<>();
		List<Map<String, Object>> tempRecords = null;
		int totalInserted = 0; // 记录sheet已插入的总数据量
		int totalInsertedSum = 0; // 记录已插入的总数据量
		int sheetIndex = 0; // 当前使用的sheetId索引
		sheetId = sheetIds[sheetIndex]; // 初始化使用第一个sheetId

		log.info("微信智能表格发票数据删除开始...");
		weComSmartSheetManager.deleteAllRows(accessToken,docId,sheetId);
		log.info("微信智能表格发票数据删除完成");
		log.info("微信智能表格发票数据插入开始...");
		//获取最近24个月的发票信息，按月去插入到智能表格中
		for (int i = 0; i < 25; i++){
			monthRange  = MonthCalculationUtils.calculateMonthRange(i);
			if (null != monthRange && monthRange.length == CommonConstants.dingleDigitIntArray[2]){
				records =  baseMapper.selectInvoiceList(monthRange[0],monthRange[1]);
			}
			//分批插入
			if (null != records && !records.isEmpty()){
				batchCount = records.size() / batchSize;
				//如果记录数不能被batchSize整除，需要增加一个批次
				if (records.size() % batchSize != 0) {
					batchCount++;
				}

				for (int j = 0; j < batchCount; j++) {
					tempRecords = records.subList(j * batchSize, Math.min((j + 1) * batchSize, records.size()));

					// 检查是否需要切换到下一个sheetId
					if (totalInserted + tempRecords.size() > 100000) {
						// 如果当前数据加上已插入数据超过100000，则切换到下一个sheetId
						sheetIndex++;
						if (sheetIndex < sheetIds.length) {
							sheetId = sheetIds[sheetIndex];
							totalInserted = 0; // 重置计数器
							log.info("切换到下一个表格，使用sheetId: " + sheetId);

							// 删除新表格中的所有数据
							log.info("清空新表格数据开始...");
							weComSmartSheetManager.deleteAllRows(accessToken, docId, sheetId);
							log.info("清空新表格数据完成");
						} else {
							log.warn("sheetIds已用完，无法继续插入数据");
							return;
						}
					}

					debugService.debugInsertIssueAsso(accessToken,tempRecords,docId,sheetId);
					totalInserted += tempRecords.size();
					totalInsertedSum += tempRecords.size();
				}
			}
		}
		log.info("微信智能表格发票数据插入完成，总共插入记录数: " + totalInsertedSum);

		//智能表格合同数据表ID
		sheetId = "EuVt8X";
		log.info("微信智能表格合同数据删除开始...");
		weComSmartSheetManager.deleteAllRows(accessToken,docId,sheetId);
		log.info("微信智能表格合同数据删除完成");
		log.info("微信智能表格合同数据插入开始...");
		//开始处理合同信息，先获取合同数，然后分批次插入数据，每批次1000条
		int contractCount = baseMapper.selectContractListCount();
		if (contractCount != 0) {
			batchCount = contractCount / batchSize;
			if (batchCount != 0){
				for (int i = 0; i <= batchCount; i++) {
					tempRecords = baseMapper.selectContractList(i * batchSize, batchSize);
					if (tempRecords != null) {
						debugService.debugInsertIssueAsso(accessToken,tempRecords,docId,sheetId);
					}
				}
			}else {
				tempRecords = baseMapper.selectContractList(0, batchSize);
				if (tempRecords != null) {
					debugService.debugInsertIssueAsso(accessToken,tempRecords,docId,sheetId);
				}
			}

		}
		log.info("微信智能表格合同数据插入完成，总共插入记录数: "+contractCount);
	}

}