
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.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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.mp.support.Condition;
import org.sky.core.mp.support.Query;
import org.sky.core.tool.utils.*;
import org.sky.scientific.excel.XmGoodsExcel;
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.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

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

	@Resource
	private XmMapper xmMapper;

	@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(HttpServletResponse response, XmGoodsDTO dto) {

		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发领料燃料动力明细清单.xls");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("研发领料燃料动力明细清单.xls", Charsets.UTF_8));

		List<XmGoodsVO> list = this.selectXmGoodsPage(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto).getRecords();
 		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());

			excel.setAmount(excel.getUnitPrice().multiply(new BigDecimal(excel.getUseQuantity())));
			excel.setUseDateStr(DateUtil.format(excel.getUseDate(), DateUtil.PATTERN_DATE));
			resultList.add(excel);

		}

		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.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", dto.getYearAndMonth().substring(0, 4));
		map.put("month", dto.getYearAndMonth().substring(4));
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@Override
	public boolean importXmGoods(MultipartFile file, String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		List<XmGoodsExcel> data = ExcelUtil.read(file, 0, 2, XmGoodsExcel.class);
		if (CollectionUtil.isEmpty(data)) {
			throw new ServiceException("未能从模板中读取数据，请检查模板格式是否正确");
		}
		List<XmGoodsEntity> insertList = new ArrayList<>();
		for (XmGoodsExcel excel : data) {
			XmGoodsEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(excel, XmGoodsDTO.class));
			//判断日期是否为当月日期
			XmCostDetailsServiceImpl.judgeDate(entity.getUseDate(), yearAndMonth);

			if (!StringUtil.isAllBlank(excel.getXmmc(), excel.getXmbh())) {
				//根据项目名称或编号查询xmId
				Long xmId = xmMapper.getXmIdByXmmcOrXmbh(yearAndMonth, excel.getXmmc(), excel.getXmbh());
				if (xmId == null) {
					throw new ServiceException("研发项目[" + (StringUtil.isNotBlank(excel.getXmmc()) ? excel.getXmmc() + "," : "") + (StringUtil.isNotBlank(excel.getXmbh()) ? excel.getXmbh() : "") + "]不存在，请检查模板数据");
				}
				entity.setXmId(xmId);

			}
			entity.setYearAndMonth(yearAndMonth);
			insertList.add(entity);
		}
		return this.saveBatch(insertList);
	}

	@Override
	public boolean physicalDeleteByIds(List<Long> ids) {
		return baseMapper.physicalDeleteByIds(ids) > 0;
	}

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

		//判断日期是否为当月日期
		XmCostDetailsServiceImpl.judgeDate(xmGoods.getUseDate(), xmGoods.getYearAndMonth());

		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);
			Map<Date, List<XmGoodsVO>> mapByDay = listByXmId.stream().collect(Collectors.groupingBy(XmGoodsVO::getUseDate));

			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;
	}

}
