
package org.sky.scientific.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.tool.utils.CollectionUtil;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.core.tool.utils.StringUtil;
import org.sky.scientific.excel.XmCqdtfyExcel;
import org.sky.scientific.excel.listener.XmCqdtfyImportListener;
import org.sky.scientific.mapper.XmCqdtfyMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.XmCqdtfyDTO;
import org.sky.scientific.pojo.entity.XmCqdtfyEntity;
import org.sky.scientific.pojo.vo.XmCqdtfyVO;
import org.sky.scientific.service.IXmCqdtfyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 长期待摊费用分配表 服务实现类
 *
 * @author Kd
 * @since 2025-07-24
 */
@Service
@AllArgsConstructor
public class XmCqdtfyServiceImpl extends BaseServiceImpl<XmCqdtfyMapper, XmCqdtfyEntity> implements IXmCqdtfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<XmCqdtfyVO> selectPageByCondition(IPage<XmCqdtfyVO> page, XmCqdtfyDTO dto) {
		return page.setRecords(baseMapper.selectPageByCondition(page, dto));
	}

	@SneakyThrows
	@Override
	@Transactional
	public void importData(MultipartFile file, String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		XmCqdtfyImportListener listener = new XmCqdtfyImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(2) // 重要：设置表头行数(0-based)
			.doRead();
		List<Object> dataList = listener.getDataList();

		List<XmCqdtfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object obj : dataList) {
			XmCqdtfyExcel excel = (XmCqdtfyExcel) obj;
			XmCqdtfyEntity entity = new XmCqdtfyEntity();
			cn.hutool.core.bean.BeanUtil.copyProperties(excel, entity);
			if (StringUtil.isBlank(excel.getXmbh())) {
				throw new ServiceException("序号[" + excel.getXh() + "]的研发项目编号为空，请重新填写数据");
			}
			//根据项目编号查询xmId
			Long xmId = xmMapper.getXmIdByXmmcOrXmbh(null, null, excel.getXmbh());
			if (xmId == null) {
				throw new ServiceException("序号[" + excel.getXh() + "]的研发项目不存在，请检查模板数据");
			}
			entity.setXmId(xmId);
			entity.setYearAndMonth(yearAndMonth);
			insertList.add(entity);
			if (insertList.size() % batchCount == 0 && this.saveBatch(insertList)) {
				insertList.clear();
			}
		}
		if (!insertList.isEmpty()) {
			this.saveBatch(insertList);
		}
	}

	@Override
	public boolean submit(XmCqdtfyEntity entity) {
		LambdaQueryWrapper<XmCqdtfyEntity> queryWrapper = Wrappers.<XmCqdtfyEntity>lambdaQuery()
			.eq(XmCqdtfyEntity::getYearAndMonth, entity.getYearAndMonth())
			.eq(XmCqdtfyEntity::getCtdtfymc, entity.getCtdtfymc());
		List<XmCqdtfyEntity> list = baseMapper.selectList(queryWrapper);

		if(entity.getId() == null){
			//新增
			if(Func.isNotEmpty(list)){
				throw new ServiceException("长期待摊费用名称已存在");
			}
		}else {
			//修改
			if(Func.isNotEmpty(list) && !Func.equals(list.get(0).getId(), entity.getId())){
				throw new ServiceException("长期待摊费用名称已存在");
			}
			//后续同 长期待摊费用名称的已使用月数 +1

		}
		return this.saveOrUpdate(entity);
	}

	@Override
	@Transactional
	public boolean physicalDeleteByIds(List<Long> ids) {
		for (Long id : ids) {
			XmCqdtfyEntity cqdtfy = baseMapper.selectById(id);
			if(Func.notNull(cqdtfy)){
				baseMapper.physicalDeleteByNameAndMonth(cqdtfy.getCtdtfymc(), cqdtfy.getYearAndMonth());
			}
		}
//		return baseMapper.physicalDeleteByIds(ids) > 0;
		return true;
	}

	@Override
	public boolean fetchLastMonthData(String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		//查询本月数据，若有，则不能导入
		Long count = baseMapper.selectCount(Wrappers.<XmCqdtfyEntity>lambdaQuery().eq(XmCqdtfyEntity::getYearAndMonth, yearAndMonth));
		if (count > 0) {
			throw new ServiceException("有数据，需要删除" + yearAndMonth + "的数据才能导入");
		}
		//查询上月数据
		String lastMonth = DateUtil.format(DateUtil.minusMonths(DateUtil.parse(yearAndMonth, DateUtil.PATTERN_YYYYMM), 1), DateUtil.PATTERN_YYYYMM);
		List<XmCqdtfyEntity> lastMonthDataList = baseMapper.selectList(Wrappers.<XmCqdtfyEntity>lambdaQuery().eq(XmCqdtfyEntity::getYearAndMonth, lastMonth));
		if (CollectionUtil.isEmpty(lastMonthDataList)) {
			throw new ServiceException("上个月无数据");
		}
		List<XmCqdtfyEntity> insertList = new ArrayList<>();
		for (XmCqdtfyEntity entity : lastMonthDataList) {
			entity.setYearAndMonth(yearAndMonth);
			entity.setYsyys(Math.min(entity.getYsyys() + 1, entity.getSysm()));
			entity.setId(null);
			entity.setCreateUser(null);
			entity.setCreateDept(null);
			entity.setCreateTime(null);
			insertList.add(entity);
		}
		return this.saveBatch(insertList);
	}

	@SneakyThrows
	@Override
	public void exportXmCqdtfy(OutputStream os, List<XmCqdtfyVO> list, String yearAndMonth) {
		AtomicInteger index = new AtomicInteger(1);

		Integer sysmSum = 0, ysyysSum = 0;
		BigDecimal zcyzSum = BigDecimal.ZERO;
		for (XmCqdtfyVO vo : list) {
			vo.setXh(index.getAndIncrement() + "");
			vo.setYftxe(vo.getYtxe().multiply(vo.getSyzb()));
			vo.setSyzb(vo.getSyzb().multiply(new BigDecimal("100")));

			sysmSum += vo.getSysm();
			ysyysSum += vo.getYsyys();
			zcyzSum = zcyzSum.add(vo.getZcyz());
		}

		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发费用管理/折旧费用与长期待摊费用/每月长期待摊费用分配表.xls");
		ExcelWriter excelWriter = EasyExcel.write(os)
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLS)
			.build();

		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		//设置list集合数据
		excelWriter.fill(list, fillConfig, writeSheet);
		Map<String, Object> map = new HashMap<>();
		map.put("yearAndMonth", yearAndMonth);
		map.put("sysmSum", sysmSum);
		map.put("ysyysSum", ysyysSum);
		map.put("zcyzSum", zcyzSum);
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

}
