
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 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.BeanUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.excel.YsWtwbyjkffyExcel;
import org.sky.scientific.excel.listener.YsWtwbyjkffyImportListener;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsWtwbyjkffyMapper;
import org.sky.scientific.pojo.entity.YsWtwbyjkffyEntity;
import org.sky.scientific.pojo.vo.YsWtwbyjkffyVO;
import org.sky.scientific.service.IYsWtwbyjkffyService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目预算-委托外部研究开发费 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
@AllArgsConstructor
public class YsWtwbyjkffyServiceImpl extends BaseServiceImpl<YsWtwbyjkffyMapper, YsWtwbyjkffyEntity> implements IYsWtwbyjkffyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsWtwbyjkffyVO> selectYsWtwbyjkffyPage(IPage<YsWtwbyjkffyVO> page, YsWtwbyjkffyVO ysWtwbyjkffy) {
		return page.setRecords(baseMapper.selectYsWtwbyjkffyPage(page, ysWtwbyjkffy));
	}

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

	@Override
	public boolean saveWtwbyjkffy(YsWtwbyjkffyEntity ysWtwbyjkffy) {
		ysWtwbyjkffy.setWwfy(ysWtwbyjkffy.getWwfy() * 10000);
		return save(ysWtwbyjkffy);
	}

	@Override
	public boolean updateWtwbyjkffy(YsWtwbyjkffyEntity ysWtwbyjkffy) {
		if (ysWtwbyjkffy.getXmId() == null) {
			throw new ServiceException("请选择科研项目");
		}
		ysWtwbyjkffy.setWwfy(ysWtwbyjkffy.getWwfy() * 10000);
		return this.updateById(ysWtwbyjkffy);
	}

	@SneakyThrows
	@Override
	public void importWtwbyjkffy(MultipartFile file, Long xmId) {
		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}
		YsWtwbyjkffyImportListener listener = new YsWtwbyjkffyImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(3) // 重要：设置表头行数(0-based)
			.doRead();
		List<Object> dataList = listener.getDataList();
		if (Func.isEmpty(dataList)) {
			throw new ServiceException("未能读取到数据，请检查");
		}

		List<YsWtwbyjkffyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object o : dataList) {
			YsWtwbyjkffyExcel excel = (YsWtwbyjkffyExcel) o;
			YsWtwbyjkffyEntity entity = new YsWtwbyjkffyEntity();
			entity.setXmId(xmId);

			BeanUtil.copyProperties(excel, entity);
			insertList.add(entity);

			if (insertList.size() % batchCount == 0 && this.saveBatch(insertList)) {
				insertList.clear();
			}
		}

		if (Func.isNotEmpty(insertList)) {
			this.saveBatch(insertList);
		}
	}

	@SneakyThrows
	@Override
	public void exportYsWtwbyjkffy(OutputStream os, YsWtwbyjkffyVO dto) {
		List<YsWtwbyjkffyVO> list = this.selectYsWtwbyjkffyPage(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto).getRecords();
		AtomicInteger index = new AtomicInteger(1);

		for (YsWtwbyjkffyVO temp : list) {
			temp.setXh(index.getAndIncrement() + "");
			temp.setWwfy(temp.getWwfy() / 10000);
		}
		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<>();

		JSONObject xm = xmMapper.getXmmcAndXmbhByXmId(dto.getXmId());
		map.put("xmmc", Func.notNull(xm) ? xm.getString("xmmc") : "");
		map.put("xmbh", Func.notNull(xm) ? xm.getString("xmbh") : "");
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

}
