
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.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.sky.core.excel.util.ExcelUtil;
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.XmDirectCostExcel;
import org.sky.scientific.mapper.XmDirectCostMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.entity.XmDirectCostEntity;
import org.sky.scientific.pojo.vo.XmDirectCostSummary;
import org.sky.scientific.service.IXmDirectCostService;
import org.sky.scientific.service.IXmService;
import org.sky.system.cache.DictCache;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 研发项目直投费用清单 服务实现类
 *
 * @author Kd
 * @since 2025-07-17
 */
@Service
@AllArgsConstructor
public class XmDirectCostServiceImpl extends BaseServiceImpl<XmDirectCostMapper, XmDirectCostEntity> implements IXmDirectCostService {

	private final XmMapper xmMapper;
	private final IXmService xmService;

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

	@SneakyThrows
	@Override
	public void exportXmDirectCost(OutputStream os, List<XmDirectCostEntity> list) {
		AtomicInteger index = new AtomicInteger(1);
		list.forEach(temp -> {
			temp.setXh(index.getAndIncrement() + "");
			temp.setUseDateStr(Func.notNull(temp.getUseDate()) ? DateUtil.format(temp.getUseDate(), DateUtil.PATTERN_DATE) : null);
			String typeStr = DictCache.getValue("zhitoufeiyong_lx", temp.getType());
			temp.setType(typeStr);
		});
		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("amountSum", list.stream().map(XmDirectCostEntity::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@Override
	public boolean importXmDirectCost(MultipartFile file, String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		List<XmDirectCostExcel> data = ExcelUtil.read(file, 0, 3, XmDirectCostExcel.class);
		if (CollectionUtil.isEmpty(data)) {
			throw new ServiceException("未能从模板中读取数据，请检查模板格式是否正确");
		}
		List<XmDirectCostEntity> insertList = new ArrayList<>();
		for (XmDirectCostExcel excel : data) {
			String judged = DateUtil.judgeDate(excel.getUseDate(), yearAndMonth);
			if (judged != null) {
				throw new ServiceException(judged);
			}

			XmDirectCostEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(excel, XmDirectCostEntity.class));
			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, true);
				entity.setXmId(xmId);
			}

			String type = null;
			if(Func.isBlank(excel.getType()) || Func.isNull(type=DictCache.getKey("zhitoufeiyong_lx", excel.getType().trim()))){
				throw new ServiceException("直投费用类型错误");
			}
			entity.setType(type);
			entity.setYearAndMonth(yearAndMonth);
			insertList.add(entity);
		}
		return this.saveBatch(insertList);
	}

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

	@Override
	public boolean submit(XmDirectCostEntity xmDirectCost) {
		if (StringUtil.isBlank(xmDirectCost.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		xmService.judgeXmIsOver(xmDirectCost.getXmId(), true);
		String judged = DateUtil.judgeDate(xmDirectCost.getUseDate(), xmDirectCost.getYearAndMonth());
		if (judged != null) {
			throw new ServiceException(judged);
		}
		return this.saveOrUpdate(xmDirectCost);
	}

	@Override
	public List<XmDirectCostSummary> tourufeiyonghuizongbiao(XmDirectCostEntity dto) {
		if (Func.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		List<XmDirectCostSummary> list = null;
		if (dto.getYearAndMonth().length() == 6) {
			list = baseMapper.tourufeiyonghuizongbiao(dto);
		} else if (dto.getYearAndMonth().length() == 4) {
			list = baseMapper.tourufeiyonghuizongbiaoByYear(dto);
		}else {
			throw new ServiceException("参数yearAndMonth格式错误，只能是yyyy或者yyyyMM");
		}
		for (XmDirectCostSummary summary : list) {
			summary.setTotal(summary.getCailiaofy().add(summary.getRanliaofy()).add(summary.getDonglify()).add(summary.getYiqishebeify()).add(summary.getFawuzulinfy()).add(summary.getFy6()).add(summary.getFy7()).add(summary.getFy8()));
		}
		return list;
	}

	@SneakyThrows
	@Override
	public void exportTourufeiyonghuizongbiao(HttpServletResponse response, XmDirectCostEntity dto) {

		List<XmDirectCostSummary> list = this.tourufeiyonghuizongbiao(dto);
		AtomicInteger index = new AtomicInteger(1);
		list.forEach(temp -> {
			temp.setXh(index.getAndIncrement() + "");
			temp.setTotal(temp.getCailiaofy().add(temp.getRanliaofy()).add(temp.getDonglify()).add(temp.getYiqishebeify()).add(temp.getFawuzulinfy()).add(temp.getFy6()).add(temp.getFy7()).add(temp.getFy8()));
		});
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发费用管理/直接投入费用/直接投入费用汇总表P081.xls");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("直接投入费用汇总表.xls", Charsets.UTF_8));
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.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("cailiaofySum", list.stream().map(XmDirectCostSummary::getCailiaofy).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("ranliaofySum", list.stream().map(XmDirectCostSummary::getRanliaofy).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("donglifySum", list.stream().map(XmDirectCostSummary::getDonglify).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("yiqishebeifySum", list.stream().map(XmDirectCostSummary::getYiqishebeify).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("fawuzulinfySum", list.stream().map(XmDirectCostSummary::getFawuzulinfy).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("fy6Sum", list.stream().map(XmDirectCostSummary::getFy6).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("fy7Sum", list.stream().map(XmDirectCostSummary::getFy7).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("fy8Sum", list.stream().map(XmDirectCostSummary::getFy8).reduce(BigDecimal.ZERO, BigDecimal::add));
		map.put("totalSum", list.stream().map(XmDirectCostSummary::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add));

		String yearAndMonth = dto.getYearAndMonth();
		map.put("yearAndMonth", yearAndMonth.length() == 6 ? yearAndMonth.substring(0, 4) + "年" + yearAndMonth.substring(4) + "月" : yearAndMonth.substring(0, 4) + "年");
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}
}
