
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.YsSjfyExcel;
import org.sky.scientific.excel.listener.YsSjfyImportListener;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsSjfyMapper;
import org.sky.scientific.pojo.entity.YsSjfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsSjfyVO;
import org.sky.scientific.service.IYsSjfyService;
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 YsSjfyServiceImpl extends BaseServiceImpl<YsSjfyMapper, YsSjfyEntity> implements IYsSjfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsSjfyVO> selectYsSjfyPage(IPage<YsSjfyVO> page, YsSjfyVO ysSjfy) {
		List<YsSjfyVO> vos = baseMapper.selectYsSjfyPage(page, ysSjfy);
		return page.setRecords(vos);
	}

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

	@Override
	public boolean saveSjfy(YsSjfyEntity ysSjfy) {
		if (baseMapper.selectCount(Wrappers.<YsSjfyEntity>lambdaQuery().eq(YsSjfyEntity::getSjnr, ysSjfy.getSjnr()).eq(YsSjfyEntity::getXmId, ysSjfy.getXmId())) > 0) {
			throw new ServiceException("设计内容或详情已存在");
		}
		ysSjfy.setYsje(ysSjfy.getYsje() * 10000);
		return save(ysSjfy);
	}

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

	@SneakyThrows
	@Override
	public void importSjfy(MultipartFile file, Long xmId) {
		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}
		XmVO xmVO = xmMapper.selectByXmId(xmId);
		if (Func.isNull(xmVO)) {
			throw new ServiceException("研发项目不存在");
		}

		YsSjfyImportListener listener = new YsSjfyImportListener();
		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<YsSjfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object o : dataList) {
			YsSjfyExcel excel = (YsSjfyExcel) o;
			YsSjfyEntity entity = new YsSjfyEntity();
			entity.setXmId(xmId);
			entity.setSjnr(excel.getSjnr());
			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 exportYsSjfy(OutputStream os, YsSjfyVO dto) {
		List<YsSjfyVO> list = this.selectYsSjfyPage(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto).getRecords();
		AtomicInteger index = new AtomicInteger(1);
		for (YsSjfyVO 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();
		}
	}

}
