
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.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.secure.utils.SecureUtil;
import org.sky.core.tool.utils.*;
import org.sky.scientific.excel.CgQtExcel;
import org.sky.scientific.excel.listener.CgQtImportListener;
import org.sky.scientific.mapper.CgQtMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.CgQtDTO;
import org.sky.scientific.pojo.entity.CgQtEntity;
import org.sky.scientific.pojo.vo.XmCGSummary;
import org.sky.scientific.service.ICgQtService;
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.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 科研成果-其他成果 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
public class CgQtServiceImpl extends BaseServiceImpl<CgQtMapper, CgQtEntity> implements ICgQtService {

	@Resource
	private XmMapper xmMapper;

	@Override
	public IPage<CgQtEntity> selectPageByCondition(IPage<CgQtEntity> page, CgQtDTO qt) {
		qt.setTenantId(SecureUtil.getTenantId());
		List<CgQtEntity> list = baseMapper.selectPageByCondition(page, qt);
		return page.setRecords(list);
	}

	@SneakyThrows
	@Transactional
	@Override
	public void importQt(MultipartFile file) {
		CgQtImportListener listener = new CgQtImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(3) // 重要：设置表头行数(0-based)
			.doRead();
		List<CgQtExcel> dataList = listener.getDataList();
		if (CollectionUtil.isEmpty(dataList)) {
			throw new ServiceException("未能从模板中读取数据，请检查模板格式是否正确");
		}
		for (CgQtExcel excel : dataList) {
			CgQtEntity qtDTO = Objects.requireNonNull(BeanUtil.copyProperties(excel, CgQtDTO.class));
			if (StringUtil.isNotBlank(excel.getXmbh())) {
				Long xmId = xmMapper.getXmIdByXmmcOrXmbh(null, null, excel.getXmbh());
				if (xmId == null) {
					throw new ServiceException("项目不存在，导入失败，请检查数据");
				}
				qtDTO.setXmId(xmId);
			}
			if(isDuplicate(qtDTO)){
				throw new ServiceException("成果编号/成果名称已存在");
			}
			this.save(qtDTO);
		}
	}

	@Override
	public boolean save(CgQtEntity cgQt) {
		if(isDuplicate(cgQt)){
			throw new ServiceException("成果编号/成果名称已存在");
		}
		return super.save(cgQt);
	}

	@Override
	public boolean update(CgQtEntity cgQt) {
		if(isDuplicate(cgQt)){
			throw new ServiceException("成果编号/成果名称已存在");
		}
		return updateById(cgQt);
	}

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

	@Override
	public IPage<XmCGSummary> xmCgSummary(IPage<XmCGSummary> page, Long xmId) {
		List<XmCGSummary> list = baseMapper.xmCgSummary(page, xmId, SecureUtil.getTenantId());
		return page.setRecords(list);
	}

	private boolean isDuplicate(CgQtEntity cgQt) {
		LambdaQueryWrapper<CgQtEntity> wrapper = Wrappers.<CgQtEntity>lambdaQuery()
			.eq(CgQtEntity::getCgbh, cgQt.getCgbh()).or().eq(CgQtEntity::getCgmc, cgQt.getCgmc());
		List<CgQtEntity> list = baseMapper.selectList(wrapper);
		if (Func.isEmpty(list)) {
			return false;
		}
		if (list.size() == 1) {
			return cgQt.getId()==null || !Func.equals(cgQt.getId(), list.get(0).getId());
		}
		return true;
	}

	@SneakyThrows
	@Override
	public void exportXmCgSummary(OutputStream os, List<XmCGSummary> list) {
		AtomicInteger index = new AtomicInteger(1);
		List<JSONObject> results = new ArrayList<>();
		for (XmCGSummary temp : list) {
			JSONObject obj = new JSONObject();
			obj.put("xh", index.getAndIncrement() + "");
			obj.put("cgmc", temp.getCgmc());
			obj.put("cgbh", temp.getCgbh());
			obj.put("date1Str", Func.notNull(temp.getDate1()) ? DateUtil.format(temp.getDate1(), DateUtil.PATTERN_DATE) : null);
			obj.put("date2Str", Func.notNull(temp.getDate2()) ? DateUtil.format(temp.getDate2(), DateUtil.PATTERN_DATE) : null);
			obj.put("cglx", temp.getCglx());
			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<>();
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@SneakyThrows
	@Override
	public void export(OutputStream os, List<CgQtEntity> list) {
		AtomicInteger index = new AtomicInteger(1);
		List<CgQtExcel> results = new ArrayList<>();
		list.forEach(temp -> {
			CgQtExcel excel = BeanUtil.copyProperties(temp, CgQtExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			excel.setShenqingRqStr(Func.notNull(temp.getShenqingRq()) ? DateUtil.format(temp.getShenqingRq(), DateUtil.PATTERN_DATE) : null);
			excel.setShouquanRqStr(Func.notNull(temp.getShouquanRq()) ? DateUtil.format(temp.getShouquanRq(), DateUtil.PATTERN_DATE) : null);
			results.add(excel);
		});
		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);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}
}
