/*
 *    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.salary.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TStatisticsCurrentReportMarket;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TStatisticsCurrentReportMarketMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TStatisticsCurrentReportMarketService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TStatisticsCurrentReportMarketSearchVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TStatisticsCurrentReportMarketVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 统计-本期申报-回盘数据
 *
 * @author hgw
 * @date 2022-08-05 11:40:14
 */
@Log4j2
@Service
public class TStatisticsCurrentReportMarketServiceImpl extends ServiceImpl<TStatisticsCurrentReportMarketMapper, TStatisticsCurrentReportMarket> implements TStatisticsCurrentReportMarketService {
	/**
	 * 统计-本期申报-回盘数据简单分页查询
	 *
	 * @param tStatisticsCurrentReportMarket 统计-本期申报-回盘数据
	 * @return
	 */
	@Override
	public IPage<TStatisticsCurrentReportMarket> getTStatisticsCurrentReportMarketPage(Page<TStatisticsCurrentReportMarket> page, TStatisticsCurrentReportMarketSearchVo tStatisticsCurrentReportMarket) {
		return baseMapper.getTStatisticsCurrentReportMarketPage(page, tStatisticsCurrentReportMarket);
	}

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

	private LambdaQueryWrapper buildQueryWrapper(TStatisticsCurrentReportMarketSearchVo entity) {
		LambdaQueryWrapper<TStatisticsCurrentReportMarket> wrapper = Wrappers.lambdaQuery();
		return wrapper;
	}

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

				@Override
				public void invoke(TStatisticsCurrentReportMarketVo 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)) {
						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());
					if (!cachedDataList.isEmpty()) {
						if (Common.isEmpty(declareMonth)) {
							if (Common.isNotNull(cachedDataList.get(0).getCreateStart())) {
								declareMonth = DateUtil.getYearMonth(cachedDataList.get(0).getCreateStart());
							}
							if (Common.isEmpty(declareMonth)) {
								errorMessageList.add(new ErrorMessage(CommonConstants.TWO_INT
										, "请检查‘税款所属期起’单元格格式是文本格式，且满足日期格式yyyy-MM-dd或yyyyMMdd"));
							} else {
								try {
									Integer.parseInt(declareMonth);
								} catch (Exception e) {
									errorMessageList.add(new ErrorMessage(CommonConstants.TWO_INT
											, "请检查‘税款所属期起’单元格格式是文本格式，且满足日期格式yyyy-MM-dd或yyyyMMdd"));
								}
							}
							declareTitle = cachedDataList.get(0).getInvoiceTitle();
							if (Common.isEmpty(declareTitle)) {
								errorMessageList.add(new ErrorMessage(CommonConstants.TWO_INT
										, "封面抬头全称-不能为空"));
							}
							if (Common.isNotNull(declareMonth) && Common.isNotNull(declareTitle)) {
								TStatisticsCurrentReportMarket sdsCheck = new TStatisticsCurrentReportMarket();
								sdsCheck.setDeclareMonth(declareMonth);
								sdsCheck.setInvoiceTitle(declareTitle);
								QueryWrapper<TStatisticsCurrentReportMarket> queryWrapperSc = new QueryWrapper<>();
								queryWrapperSc.setEntity(sdsCheck);
								int count = baseMapper.getCountByMonthAndTitle(declareMonth, declareTitle);
								if (count > CommonConstants.ZERO_INT) {
									errorMessageList.add(new ErrorMessage(CommonConstants.TWO_INT
											, "当前月同一-封面抬头全称-已存在数据。"));
								}
							}
						}
						if (errorMessageList.isEmpty()) {
							importTStatisticsCurrentReportMarket(declareMonth, cachedDataList);
						}
					}
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		boolean isTrue = true;
		for (ErrorMessage message : errorMessageList) {
			if (!CommonConstants.SAVE_SUCCESS.equals(message.getMessage())) {
				isTrue = false;
				break;
			}
		}
		if (isTrue) {
			return R.ok();
		} else {
			return R.failed(errorMessageList);
		}
	}

	private void importTStatisticsCurrentReportMarket(String declareMonth, List<TStatisticsCurrentReportMarketVo> excelVOList) {
		// 个性化校验逻辑
		TStatisticsCurrentReportMarketVo excel;
		TStatisticsCurrentReportMarket insert;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			insert = new TStatisticsCurrentReportMarket();
			BeanUtil.copyProperties(excel, insert);
			insert.setDeclareMonth(declareMonth);
			this.save(insert);
		}
	}

	@Override
	public int deleteByYearMonth(String yearMonth) {
		return baseMapper.deleteByYearMonth(yearMonth);
	}

}
