
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 com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.excel.YsRyrgfyExcel;
import org.sky.scientific.excel.listener.YsRyrgfyImportListener;
import org.sky.scientific.mapper.TechnicianMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsRyrgfyMapper;
import org.sky.scientific.pojo.entity.TechnicianEntity;
import org.sky.scientific.pojo.entity.YsRyrgfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsRyrgfyVO;
import org.sky.scientific.service.IYsRyrgfyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目预算-人员人工费用 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Slf4j
@AllArgsConstructor
@Service
public class YsRyrgfyServiceImpl extends BaseServiceImpl<YsRyrgfyMapper, YsRyrgfyEntity> implements IYsRyrgfyService {

	private final TechnicianMapper technicianMapper;
	private final XmMapper xmMapper;

	@Override
	public IPage<YsRyrgfyVO> selectYsRyrgfyPage(IPage<YsRyrgfyVO> page, YsRyrgfyVO ysRyrgfy) {
		List<YsRyrgfyVO> dataList = baseMapper.selectYsRyrgfyPage(page, ysRyrgfy);
		for (YsRyrgfyVO vo : dataList) {
			if (Func.notNull(vo.getTechnician())) {
				vo.getTechnician().setForeign(!"在职".equals(vo.getTechnician().getNature()));
			}
 		}
		return page.setRecords(dataList);
	}

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

		//查询项目开始时间对应月份的花名册
		List<TechnicianEntity> dbTechnicianList = technicianMapper.selectList(Wrappers.<TechnicianEntity>lambdaQuery().eq(TechnicianEntity::getYearAndMonth, DateUtil.format(xmVO.getXmkssj(), DateUtil.PATTERN_YYYYMM)));

		if (Func.isEmpty(dbTechnicianList)) {
			throw new ServiceException(xmVO.getXmkssj() + "花名册无数据");
		}

		YsRyrgfyImportListener listener = new YsRyrgfyImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(3) // 重要：设置表头行数(0-based)
			.doRead();
		List<Object> dataList = listener.getDataList();

		List<YsRyrgfyEntity> dbYsList = baseMapper.selectList(Wrappers.<YsRyrgfyEntity>lambdaQuery().eq(YsRyrgfyEntity::getXmId, xmId));

		List<YsRyrgfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object o : dataList) {
			YsRyrgfyExcel excel = (YsRyrgfyExcel) o;
			YsRyrgfyEntity entity = new YsRyrgfyEntity();

			judgeZzsc(xmVO, excel.getZzsc());

			excel.setNumber(Func.isBlank(excel.getNumber()) ? null : excel.getNumber().trim());
			excel.setIdCard(Func.isBlank(excel.getIdCard()) ? null : excel.getIdCard().trim());

			Long technicianId = technicianMapper.getIdByNumberAndIdentityCard(excel.getNumber(), excel.getIdCard(), DateUtil.format(xmVO.getXmkssj(), DateUtil.PATTERN_YYYYMM));
			if (technicianId == null) {
				throw new ServiceException("[" + excel.getName() + "]不存在");
			}

			if (dbYsList.stream().anyMatch(ys -> Func.equals(ys.getTechnicianId(), technicianId))) {
				throw new ServiceException("[" + excel.getName() + "]已在预算表中");
			}
			BeanUtil.copyProperties(excel, entity);
			entity.setTechnicianId(technicianId);
			entity.setXmId(xmId);
			insertList.add(entity);

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

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

	@SneakyThrows
	@Override
	public void exportYsRyrgfy(OutputStream os, YsRyrgfyVO dto) {

		List<YsRyrgfyVO> list = this.selectYsRyrgfyPage(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto).getRecords();
		AtomicInteger index = new AtomicInteger(1);

		List<JSONObject> results = new ArrayList<>();
		for (YsRyrgfyVO temp : list) {
			TechnicianEntity technician = temp.getTechnician();
			JSONObject obj = new JSONObject();
			obj.put("xh", index.getAndIncrement() + "");
			obj.put("name", Func.notNull(technician) ? technician.getName() : "");
			obj.put("number", Func.notNull(technician) ? technician.getNumber() : "");
			obj.put("idCard", Func.notNull(technician) ? technician.getIdCard() : "");
			obj.put("zzsc", temp.getZzsc());
			temp.setPjrgfy(temp.getPjrgfy().divide(BigDecimal.valueOf(10000L), 4 , RoundingMode.UP));
			obj.put("pjrgfy", temp.getPjrgfy());
			obj.put("total", temp.getPjrgfy().multiply(BigDecimal.valueOf(temp.getZzsc())));
			obj.put("foreignStr", Func.notNull(temp.getTechnician()) ? (temp.getTechnician().isForeign() ? "是" : "否") : "");
			results.add(obj);
		}

		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(results, 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();
		}
	}

	@Override
	public boolean saveRyrgfy(YsRyrgfyEntity ysRyrgfy) {
		XmVO xmVO = xmMapper.selectByXmId(ysRyrgfy.getXmId());
		if(Func.isNull(xmVO)){
			throw new ServiceException("研发项目不存在");
		}
		judgeZzsc(xmVO, ysRyrgfy.getZzsc());
		//花名册是否已添加
		List<YsRyrgfyEntity> dbList = baseMapper.selectList(Wrappers.<YsRyrgfyEntity>lambdaQuery().eq(YsRyrgfyEntity::getXmId, ysRyrgfy.getXmId()));
		List<Long> dbTechnicianIdList = dbList.stream().map(YsRyrgfyEntity::getTechnicianId).toList();
		if (dbTechnicianIdList.contains(ysRyrgfy.getTechnicianId())) {
			throw new ServiceException("人员已在预算表中");
		}
		ysRyrgfy.setPjrgfy(ysRyrgfy.getPjrgfy().multiply(BigDecimal.valueOf(10000)));
		return this.save(ysRyrgfy);
	}

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

	@Override
	public boolean updateRyrgfy(YsRyrgfyEntity ysRyrgfy) {
		XmVO xmVO = xmMapper.selectByXmId(ysRyrgfy.getXmId());
		if(Func.isNull(xmVO)){
			throw new ServiceException("研发项目不存在");
		}
		judgeZzsc(xmVO, ysRyrgfy.getZzsc());
		List<YsRyrgfyEntity> dbList = baseMapper.selectList(Wrappers.<YsRyrgfyEntity>lambdaQuery().eq(YsRyrgfyEntity::getXmId, ysRyrgfy.getXmId()));
		for (YsRyrgfyEntity entity : dbList) {
			if (Func.equals(entity.getTechnicianId(), ysRyrgfy.getTechnicianId()) && !Func.equals(entity.getId(), ysRyrgfy.getId())) {
				throw new ServiceException("人员已在预算表中");
			}
		}
		ysRyrgfy.setPjrgfy(ysRyrgfy.getPjrgfy().multiply(BigDecimal.valueOf(10000)));
		return this.updateById(ysRyrgfy);
	}

	private void judgeZzsc(XmVO xmVO, Integer zzsc){
 		long betweenMonth = cn.hutool.core.date.DateUtil.betweenMonth(xmVO.getXmkssj(), xmVO.getXmjssj(), true) + 1;
		if(betweenMonth < zzsc){
			throw new ServiceException("工作时长不能大于研发项目【"+xmVO.getXmbh()+"】的周期【" + betweenMonth +"】个月");
		}
	}
}
