
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 jakarta.annotation.Resource;
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.XmLeaseExcel;
import org.sky.scientific.mapper.XmLeaseMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.entity.XmLeaseEntity;
import org.sky.scientific.service.IXmLeaseService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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
 */
@Service
public class XmLeaseServiceImpl extends BaseServiceImpl<XmLeaseMapper, XmLeaseEntity> implements IXmLeaseService {

	@Resource
	private XmMapper xmMapper;

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

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

			//租赁日期，必须时当月日期
			String judged = DateUtil.judgeDate(excel.getLeaseDate(), 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() + "]不存在，请检查模板数据");
				}
				entity.setXmId(xmId);
			}

			if(BigDecimal.ZERO.compareTo(entity.getUnitPrice()) == 0){
				entity.setUnitPrice(BigDecimal.valueOf(0.00));
			}
			if(entity.getQuantity()==null){
				entity.setQuantity(0.0);
			}

			entity.setAmount(entity.getUnitPrice().multiply(BigDecimal.valueOf(entity.getQuantity())));

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

	@SneakyThrows
	@Override
	public void exportXmLease(OutputStream os, List<XmLeaseEntity> list, String yearAndMonth) {
		List<XmLeaseExcel> results = new ArrayList<>();
		AtomicInteger index = new AtomicInteger(1);
		for (XmLeaseEntity temp : list) {
			XmLeaseExcel excel = BeanUtil.copyProperties(temp, XmLeaseExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			excel.setLeaseDateStr(Func.notNull(temp.getLeaseDate()) ? DateUtil.format(temp.getLeaseDate(), DateUtil.PATTERN_DATE) : null);
			excel.setAmount(BigDecimal.valueOf(temp.getQuantity()).multiply(temp.getUnitPrice()));
			results.add(excel);
		}
		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(results, fillConfig, writeSheet);
		Map<String, Object> map = new HashMap<>();
		map.put("quantitySum", results.stream().mapToDouble(XmLeaseExcel::getQuantity).sum());
		map.put("amountSum", results.stream().map(XmLeaseExcel::getAmount).reduce(BigDecimal.valueOf(0.00), BigDecimal::add));

		map.put("year", yearAndMonth.substring(0, 4));
		map.put("month", yearAndMonth.substring(4));
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

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

	@Override
	public boolean submit(XmLeaseEntity xmLease) {
		if (StringUtil.isBlank(xmLease.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		String judged = DateUtil.judgeDate(xmLease.getLeaseDate(), xmLease.getYearAndMonth());
		if (judged != null) {
			throw new ServiceException(judged);
		}
		xmLease.setAmount(xmLease.getUnitPrice().multiply(BigDecimal.valueOf(xmLease.getQuantity())));
		return this.saveOrUpdate(xmLease);
	}

	@Override
	public List<JSONObject> yanfazulinzichanfeiyongfenpeibiao(XmLeaseEntity dto) {
		if (Func.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		List<XmLeaseEntity> list = baseMapper.yanfazulinzichanfeiyongfenpeibiao(dto);
		for (XmLeaseEntity lease : list) {
			lease.setAmount(BigDecimal.valueOf(lease.getQuantity()).multiply(lease.getUnitPrice()));
		}
		List<JSONObject> result = new ArrayList<>();
		if (CollectionUtil.isEmpty(list)) {
			return result;
		}
		Map<Long, List<XmLeaseEntity>> mapByXmId = list.stream().collect(Collectors.groupingBy(XmLeaseEntity::getXmId));
		for (Long xmId : mapByXmId.keySet()) {
			List<XmLeaseEntity> listByXmId = mapByXmId.get(xmId);

			for (XmLeaseEntity vo : listByXmId) {
				String key = xmId + ":" + DateUtil.format(vo.getLeaseDate(), DateUtil.PATTERN_DATE);

				if (result.isEmpty()) {
					ArrayList<XmLeaseEntity> vos = new ArrayList<>();
					vos.add(vo);
					JSONObject o = new JSONObject();
					o.put(key, vos);
					result.add(o);
				} else {
					for (JSONObject o : result) {
						List<XmLeaseEntity> voList = null;
						if (o.containsKey(key)) {
							voList = o.getJSONArray(key).toJavaList(XmLeaseEntity.class);
						} else {
							voList = new ArrayList<>();
						}
						voList.add(vo);
						o.put(key, voList);
					}
				}
			}
		}
		return result;
	}

	@SneakyThrows
	@Override
	public void exportYanfazulinzichanfeiyongfenpeibiao(OutputStream os, XmLeaseEntity dto) {
		if (Func.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		List<XmLeaseEntity> list = baseMapper.yanfazulinzichanfeiyongfenpeibiao(dto);
		List<XmLeaseExcel> results = new ArrayList<>();
		AtomicInteger index = new AtomicInteger(1);
		list.forEach(temp -> {
			XmLeaseExcel excel = BeanUtil.copyProperties(temp, XmLeaseExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			excel.setLeaseDateStr(Func.notNull(temp.getLeaseDate()) ? DateUtil.format(temp.getLeaseDate(), DateUtil.PATTERN_DATE) : null);
			excel.setAmount(BigDecimal.valueOf(temp.getQuantity()).multiply(temp.getUnitPrice()));
			results.add(excel);
		});
		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(results, fillConfig, writeSheet);
		Map<String, Object> map = new HashMap<>();
		map.put("quantitySum", results.stream().mapToDouble(XmLeaseExcel::getQuantity).sum());
		map.put("amountSum", results.stream().map(XmLeaseExcel::getAmount).reduce(BigDecimal.valueOf(0.00), BigDecimal::add));

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

}
