
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.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.tool.utils.*;
import org.sky.scientific.excel.XmGoodsExcel;
import org.sky.scientific.excel.listener.XmGoodsImportListener;
import org.sky.scientific.mapper.XmGoodsMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.XmGoodsDTO;
import org.sky.scientific.pojo.entity.XmGoodsEntity;
import org.sky.scientific.pojo.vo.XmGoodsVO;
import org.sky.scientific.service.IXmGoodsService;
import org.sky.scientific.service.IXmService;
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.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 研发项目物料清单 服务实现类
 *
 * @author Kd
 * @since 2025-07-17
 */
@Slf4j
@Service
@AllArgsConstructor
public class XmGoodsServiceImpl extends BaseServiceImpl<XmGoodsMapper, XmGoodsEntity> implements IXmGoodsService {

	private final XmMapper xmMapper;
	private final IXmService xmService;

	@Override
	public IPage<XmGoodsVO> selectXmGoodsPage(IPage<XmGoodsVO> page, XmGoodsDTO dto) {
		if (StringUtil.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		return page.setRecords(baseMapper.selectXmGoodsPage(page, dto));
	}

	@SneakyThrows
	@Override
	public void exportXmGoods(OutputStream os, List<XmGoodsVO> list, String yearAndMonth) {
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发费用管理/直接投入费用/研发领料燃料动力明细清单.xls");
		AtomicInteger index = new AtomicInteger(1);
		List<XmGoodsExcel> resultList = new ArrayList<>();
		for (XmGoodsVO vo : list) {
			XmGoodsExcel excel = BeanUtil.copyProperties(vo, XmGoodsExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			if (excel.getUnitPrice() == null) {
				excel.setUnitPrice(BigDecimal.valueOf(0.00));
			}
			if (excel.getUseQuantity() == null) {
				excel.setUseQuantity(0.00);
			}
			excel.setAmount(excel.getUnitPrice().multiply(BigDecimal.valueOf(excel.getUseQuantity())));
			excel.setUseDateStr(Func.notNull(excel.getUseDate()) ? DateUtil.format(excel.getUseDate(), DateUtil.PATTERN_DATE) : null);
			resultList.add(excel);
		}
		ExcelWriter excelWriter = EasyExcel.write(os)
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLS)
			.build();
		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		//设置list集合数据
		excelWriter.fill(resultList, writeSheet);
		Map<String, Object> map = new HashMap<>();
		map.put("year", yearAndMonth.substring(0, 4));
		map.put("month", yearAndMonth.substring(4));
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@SneakyThrows
	@Override
	public boolean importXmGoods(MultipartFile file, String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		XmGoodsImportListener listener = new XmGoodsImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(2) // 重要：设置表头行数(0-based)
			.doRead();
		List<Object> data = listener.getDataList();
 		if (CollectionUtil.isEmpty(data)) {
			throw new ServiceException("未能从模板中读取数据，请检查模板格式是否正确");
		}
		List<XmGoodsEntity> insertList = new ArrayList<>();
		for (Object obj : data) {
			XmGoodsExcel excel = (XmGoodsExcel) obj;
			XmGoodsEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(excel, XmGoodsDTO.class));
			//判断日期是否为当月日期
			String judged = DateUtil.judgeDate(entity.getUseDate(), yearAndMonth);
			if (judged != null) {
				throw new ServiceException(judged);
			}
			if (StringUtil.isNotBlank(excel.getXmbh())) {
				//根据项目名称或编号查询xmId
				Long xmId = xmMapper.getXmIdByXmmcOrXmbh(null, null, excel.getXmbh());
				if (xmId == null) {
					throw new ServiceException("研发项目[" + excel.getXmbh() + "]不存在，请检查模板数据");
				}
				xmService.judgeXmIsOver(xmId, yearAndMonth,true);
				entity.setXmId(xmId);
			}
			entity.setYearAndMonth(yearAndMonth);
			insertList.add(entity);
		}
		return this.saveBatch(insertList);
	}

	@Override
	@Transactional
	public boolean physicalDeleteByIds(List<Long> ids) {
		for (Long id : ids) {
			XmGoodsEntity entity = baseMapper.selectById(id);
			if (Func.notNull(entity)) {
				xmService.judgeXmIsOver(entity.getXmId(), entity.getYearAndMonth(),true);
			}
		}
		return baseMapper.physicalDeleteByIds(ids) > 0;
	}

	@Override
	public boolean submit(XmGoodsEntity xmGoods) {
		if (StringUtil.isBlank(xmGoods.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		xmService.judgeXmIsOver(xmGoods.getXmId(), xmGoods.getYearAndMonth(),true);

		if (Func.notNull(xmGoods.getUseQuantity()) && Func.notNull(xmGoods.getUnitPrice())) {
			xmGoods.setAmount(xmGoods.getUnitPrice().multiply(BigDecimal.valueOf(xmGoods.getUseQuantity())));
		}

		//判断日期是否为当月日期
		String judged = DateUtil.judgeDate(xmGoods.getUseDate(), xmGoods.getYearAndMonth());
		if (judged != null) {
			throw new ServiceException(judged);
		}

		return this.saveOrUpdate(xmGoods);
	}

	@Override
	public List<JSONObject> yanfalingliaodan(XmGoodsDTO dto) {
		if (Func.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		if (Func.isBlank(dto.getType())) {
			throw new ServiceException("参数type为空，或者不在[材料、燃料、动力]之列");
		}
		List<XmGoodsVO> list = baseMapper.yanfalingliaodan(dto);
		List<JSONObject> result = new ArrayList<>();
		if (CollectionUtil.isEmpty(list)) {
			return result;
		}
		Map<Long, List<XmGoodsVO>> mapByXmId = list.stream().collect(Collectors.groupingBy(XmGoodsVO::getXmId));
		for (Long xmId : mapByXmId.keySet()) {
			List<XmGoodsVO> listByXmId = mapByXmId.get(xmId);
			for (XmGoodsVO vo : listByXmId) {
				String key = xmId + ":" + DateUtil.format(vo.getUseDate(), DateUtil.PATTERN_DATE);
				if (result.isEmpty()) {
					ArrayList<XmGoodsVO> vos = new ArrayList<>();
					vos.add(vo);
					JSONObject o = new JSONObject();
					o.put(key, vos);
					result.add(o);
				} else {
					for (JSONObject o : result) {
						List<XmGoodsVO> voList = null;
						if (o.containsKey(key)) {
							voList = o.getJSONArray(key).toJavaList(XmGoodsVO.class);
						} else {
							voList = new ArrayList<>();
						}
						voList.add(vo);
						o.put(key, voList);
					}
				}
			}
		}
		return result;
	}

	@SneakyThrows
	@Override
	public void exportYanfalingliaodan(OutputStream os, XmGoodsDTO dto) {
		dto.setType("材料");
		this.export(os, dto, "研发领料单.xls");
	}

	@SneakyThrows
	@Override
	public void exportYanfadonglihaoyongdan(OutputStream os, XmGoodsDTO dto) {
		dto.setType("动力");
		this.export(os, dto, "研发动力消耗单.xls");
	}

	@SneakyThrows
	@Override
	public void exportYanfaranliaohaoyongdan(OutputStream os, XmGoodsDTO dto) {
		dto.setType("燃料");
		this.export(os, dto, "研发燃料消耗单.xls");
	}

	@SneakyThrows
	private void export(OutputStream os, XmGoodsDTO dto, String templateName) {
		if (Func.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		if (Func.isNull(dto.getUseDate())) {
			throw new ServiceException("参数useDate不能为空");
		}
		List<XmGoodsVO> list = baseMapper.yanfalingliaodan(dto);
		List<XmGoodsExcel> results = new ArrayList<>();
		AtomicInteger index = new AtomicInteger(1);
		list.forEach(temp -> {
			XmGoodsExcel excel = BeanUtil.copyProperties(temp, XmGoodsExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			excel.setUseDateStr(Func.notNull(temp.getUseDate()) ? DateUtil.format(temp.getUseDate(), DateUtil.PATTERN_DATE) : null);
			if (excel.getUseQuantity() == null) {
				excel.setUseQuantity(0.0);
			}
			if (excel.getUnitPrice() == null) {
				excel.setUnitPrice(BigDecimal.valueOf(0.00));
			}
			excel.setAmount(BigDecimal.valueOf(excel.getUseQuantity()).multiply(excel.getUnitPrice()));
			results.add(excel);
		});
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发费用管理/直接投入费用/" + templateName);

		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(results, fillConfig, writeSheet);
		Map<String, Object> map = new HashMap<>();
		map.put("amountSum", results.stream().map(XmGoodsExcel::getAmount).reduce(BigDecimal.valueOf(0.00), BigDecimal::add));
		map.put("useQuantitySum", results.stream().mapToDouble(XmGoodsExcel::getUseQuantity).sum());

		map.put("xmbh", Func.isNotEmpty(results) ? results.get(0).getXmbh() : "");
		map.put("xmmc", Func.isNotEmpty(results) ? results.get(0).getXmmc() : "");
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}
}
