
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 com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.Func;
import org.sky.scientific.excel.YsQtfyExcel;
import org.sky.scientific.excel.listener.YsQtfyImportListener;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsQtfyMapper;
import org.sky.scientific.pojo.entity.YsQtfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsQtfyVO;
import org.sky.scientific.service.IYsQtfyService;
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 YsQtfyServiceImpl extends BaseServiceImpl<YsQtfyMapper, YsQtfyEntity> implements IYsQtfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsQtfyVO> selectYsQtfyPage(IPage<YsQtfyVO> page, YsQtfyVO ysQtfy) {
		return page.setRecords(baseMapper.selectYsQtfyPage(page, ysQtfy));
	}

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

	@Override
	public boolean saveQtfy(YsQtfyEntity ysQtfy) {
		if (baseMapper.selectCount(Wrappers.<YsQtfyEntity>lambdaQuery().eq(YsQtfyEntity::getFynr, ysQtfy.getFynr()).eq(YsQtfyEntity::getXmId, ysQtfy.getXmId())) > 0) {
			throw new ServiceException("费用内容已存在 ");
		}
		ysQtfy.setYsje(ysQtfy.getYsje() * 10000);
		return save(ysQtfy);
	}

	@Override
	public boolean updateQtfy(YsQtfyEntity ysQtfy) {
		if (ysQtfy.getXmId() == null) {
			throw new ServiceException("请选择科研项目");
		}
		ysQtfy.setYsje(ysQtfy.getYsje() * 10000);
		return this.updateById(ysQtfy);
	}

	@SneakyThrows
	@Override
	public void importQtfy(MultipartFile file, Long xmId) {
		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}
		XmVO xmVO = xmMapper.selectByXmId(xmId);
		if (Func.isNull(xmVO)) {
			throw new ServiceException("研发项目不存在");
		}
		YsQtfyImportListener listener = new YsQtfyImportListener();
		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<YsQtfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object o : dataList) {
			YsQtfyExcel excel = (YsQtfyExcel) o;
			YsQtfyEntity entity = new YsQtfyEntity();
			entity.setXmId(xmId);
			entity.setFynr(excel.getFynr());
			entity.setYsje(excel.getYsje());
			insertList.add(entity);

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

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

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

		for (YsQtfyVO temp : list) {
			temp.setXh(index.getAndIncrement() + "");
			temp.setYsje(temp.getYsje() / 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();
		}
	}

}
