
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 lombok.SneakyThrows;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.tool.utils.Func;
import org.sky.core.tool.utils.StringUtil;
import org.sky.scientific.mapper.XmWwxmMapper;
import org.sky.scientific.pojo.dto.XmWwxmDTO;
import org.sky.scientific.pojo.entity.XmWwxmEntity;
import org.sky.scientific.pojo.vo.XmWwxmVO;
import org.sky.scientific.service.IXmWwxmService;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目-委外项目 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
public class XmWwxmServiceImpl extends BaseServiceImpl<XmWwxmMapper, XmWwxmEntity> implements IXmWwxmService {

	@Override
	public boolean physicalDeleteByIds(List<Long> ids) {

		return baseMapper.physicalDeleteByIds(ids);
	}

	@Override
	public IPage<XmWwxmVO> selectPage(IPage<XmWwxmVO> page, XmWwxmDTO wwxmDTO) {
		if (wwxmDTO.getXmId() == null) {
			throw new ServiceException("请选择研发项目");
		}
		if(Func.isBlank(wwxmDTO.getYearAndMonth())){
			throw new ServiceException("请选择年份");
 		}
		return page.setRecords(baseMapper.selectXmWwxmPage(page, wwxmDTO));
	}

	@Override
	public List<XmWwxmVO> selectSimpleList(String yearAndMonth) {
		if(StringUtil.isBlank(yearAndMonth)){
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		return baseMapper.selectSimpleList(yearAndMonth);
	}

	@SneakyThrows
	@Override
	public void exportWwxm(OutputStream os, List<XmWwxmVO> list) {
		AtomicInteger index = new AtomicInteger(1);
 		for (XmWwxmVO temp : list) {
			temp.setXh(index.getAndIncrement() + "");
		}
		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);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

}
