
package org.sky.scientific.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.Func;
import org.sky.scientific.excel.listener.YsZjtrfyImportListener;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsZjtrfyMapper;
import org.sky.scientific.pojo.entity.YsZjtrfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsZjtrfyVO;
import org.sky.scientific.service.IYsZjtrfyService;
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 YsZjtrfyServiceImpl extends BaseServiceImpl<YsZjtrfyMapper, YsZjtrfyEntity> implements IYsZjtrfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsZjtrfyVO> selectYsZjtrfyPage(IPage<YsZjtrfyVO> page, YsZjtrfyVO ysZjtrfy) {
		return page.setRecords(baseMapper.selectYsZjtrfyPage(page, ysZjtrfy));
	}

	@Override
	public boolean saveZjtrfy(YsZjtrfyEntity ysZjtrfy) {
		// 是否重复
		if (isDuplicate(ysZjtrfy)) {
			throw new ServiceException("物资名称已存在");
		}
		if (ysZjtrfy.getDanJia() != null) {
			ysZjtrfy.setDanJia(ysZjtrfy.getDanJia() * 10000);
		}
		if (ysZjtrfy.getYsje() != null) {
			ysZjtrfy.setYsje(ysZjtrfy.getYsje() * 10000);
		}
		if (ysZjtrfy.getZlfyys() != null) {
			ysZjtrfy.setZlfyys(ysZjtrfy.getZlfyys() * 10000);
		}

		return this.save(ysZjtrfy);
	}

	private boolean isDuplicate(YsZjtrfyEntity entity) {
//		LambdaQueryWrapper<YsZjtrfyEntity> ew = Wrappers.<YsZjtrfyEntity>lambdaQuery()
//			.eq(YsZjtrfyEntity::getXmId, entity.getXmId())
//			.eq(YsZjtrfyEntity::getWzmc, entity.getWzmc());
//		List<YsZjtrfyEntity> list = baseMapper.selectList(ew);

		return false;
	}

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

	@Override
	public boolean updateZjtrfy(YsZjtrfyEntity ysZjtrfy) {
		if (ysZjtrfy.getXmId() == null) {
			throw new ServiceException("请选择科研项目");
		}
		if (ysZjtrfy.getDanJia() != null) {
			ysZjtrfy.setDanJia(ysZjtrfy.getDanJia() * 10000);
		}
		if (ysZjtrfy.getYsje() != null) {
			ysZjtrfy.setYsje(ysZjtrfy.getYsje() * 10000);
		}
		if (ysZjtrfy.getZlfyys() != null) {
			ysZjtrfy.setZlfyys(ysZjtrfy.getZlfyys() * 10000);
		}
		return this.updateById(ysZjtrfy);
	}

	@SneakyThrows
	@Override
	public void importZjtrfy(MultipartFile file, Long xmId) {

		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}
		XmVO xmVO = xmMapper.selectByXmId(xmId);
		if (Func.isNull(xmVO)) {
			throw new ServiceException("研发项目不存在");
		}
		YsZjtrfyImportListener listener = new YsZjtrfyImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(3) // 重要：设置表头行数(0-based)
			.doRead();
		List<Object> dataList = listener.getDataList();

		List<YsZjtrfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object excel : dataList) {
			YsZjtrfyEntity entity = new YsZjtrfyEntity();
			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 exportYsZjtrfy(OutputStream os, YsZjtrfyVO dto) {
		List<YsZjtrfyVO> list = this.selectYsZjtrfyPage(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto).getRecords();
		AtomicInteger index = new AtomicInteger(1);
		for (YsZjtrfyVO temp : list) {
			temp.setXh(index.getAndIncrement() + "");
			if (temp.getDanJia() == null) {
				temp.setDanJia(0.00);
			}
			temp.setDanJia(temp.getDanJia() / 10000);
			if (temp.getYongLiang() == null) {
				temp.setYongLiang(0);
			}
			temp.setWuziTotal(BigDecimal.valueOf(temp.getYongLiang() * temp.getDanJia()));
			if(temp.getYsje()!=null){
				temp.setYsje(temp.getYsje() / 10000);
			}
			if(temp.getZlfyys()!=null){
				temp.setZlfyys(temp.getZlfyys() / 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();
		}
	}
}
