
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.YsZbtsysyfyExcel;
import org.sky.scientific.excel.listener.YsZbtsysyfyImportListener;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsZbtsysyfyMapper;
import org.sky.scientific.pojo.entity.YsZbtsysyfyEntity;
import org.sky.scientific.pojo.vo.YsZbtsysyfyVO;
import org.sky.scientific.service.IYsZbtsysyfyService;
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.math.BigDecimal;
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 YsZbtsysyfyServiceImpl extends BaseServiceImpl<YsZbtsysyfyMapper, YsZbtsysyfyEntity> implements IYsZbtsysyfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsZbtsysyfyVO> selectYsZbtsysyfyPage(IPage<YsZbtsysyfyVO> page, YsZbtsysyfyVO ysZbtsysyfy) {
		return page.setRecords(baseMapper.selectYsZbtsysyfyPage(page, ysZbtsysyfy));
	}

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

	@Override
	public boolean saveZbtssyfy(YsZbtsysyfyEntity ysZbtsysyfy) {
		if(baseMapper.selectCount(Wrappers.<YsZbtsysyfyEntity>lambdaQuery().eq(YsZbtsysyfyEntity::getFyje, ysZbtsysyfy.getYsje()).eq(YsZbtsysyfyEntity::getXmId, ysZbtsysyfy.getXmId())) > 0){
			throw new ServiceException("费用内容已存在");
		}
		ysZbtsysyfy.setYsje(ysZbtsysyfy.getYsje().multiply(BigDecimal.valueOf(10000)));
		return save(ysZbtsysyfy);
	}

	@Override
	public boolean updateZbtssyfy(YsZbtsysyfyEntity ysZbtsysyfy) {
		if (ysZbtsysyfy.getXmId() == null) {
			throw new ServiceException("请选择科研项目");
		}
		ysZbtsysyfy.setYsje(ysZbtsysyfy.getYsje().multiply(BigDecimal.valueOf(10000)));
		return this.updateById(ysZbtsysyfy);
	}

	@SneakyThrows
	@Override
	public void importZbtsysyfy(MultipartFile file, Long xmId) {
		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}
		YsZbtsysyfyImportListener listener = new YsZbtsysyfyImportListener();
		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<YsZbtsysyfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object o : dataList) {
			YsZbtsysyfyExcel excel = (YsZbtsysyfyExcel) o;
			YsZbtsysyfyEntity entity = new YsZbtsysyfyEntity();
			entity.setXmId(xmId);
			entity.setFyje(excel.getFyje());
			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 exportYsZbtsysyfy(OutputStream os, YsZbtsysyfyVO dto) {
		List<YsZbtsysyfyVO> list = this.selectYsZbtsysyfyPage(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto).getRecords();
		AtomicInteger index = new AtomicInteger(1);

		for (YsZbtsysyfyVO temp : list) {
			temp.setXh(index.getAndIncrement() + "");
			if (temp.getYsje() != null) {
				temp.setYsje(temp.getYsje().multiply(BigDecimal.valueOf(0.0001)));
			}
		}
		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();
		}
	}

}
