
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.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.CgRjzzqExcel;
import org.sky.scientific.excel.listener.CgRjzzqImportListener;
import org.sky.scientific.mapper.CgRjzzqMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.CgRjzzqDTO;
import org.sky.scientific.pojo.entity.CgRjzzqEntity;
import org.sky.scientific.service.ICgRjzzqService;
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.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 科研成果-软件著作 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
public class CgRjzzqServiceImpl extends BaseServiceImpl<CgRjzzqMapper, CgRjzzqEntity> implements ICgRjzzqService {

	@Resource
	private XmMapper xmMapper;

	@SneakyThrows
	@Transactional
	@Override
	public void importRjzzq(MultipartFile file) {
		CgRjzzqImportListener listener = new CgRjzzqImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(3) // 重要：设置表头行数(0-based)
			.doRead();
		List<CgRjzzqExcel> dataList = listener.getDataList();
		if (CollectionUtil.isEmpty(dataList)) {
			throw new ServiceException("未能从模板中读取数据，请检查模板格式是否正确");
		}
		for (CgRjzzqExcel excel : dataList) {
			CgRjzzqEntity entity = Objects.requireNonNull(BeanUtil.copyProperties(excel, CgRjzzqDTO.class));
			if (isDuplicate(entity)) {
				throw new ServiceException("软件名称已存在");
			}
			if (StringUtil.isNotBlank(excel.getXmbh())) {
				Long xmId = xmMapper.getXmIdByXmmcOrXmbh(null, null, excel.getXmbh());
				if (xmId == null) {
					throw new ServiceException("项目不存在，导入失败，请检查数据");
				}
				entity.setXmId(xmId);
			}
			try {
				this.save(entity);
			} catch (Exception e) {
				throw new ServiceException("序号为[" + excel.getXh() + "]的数据错误");
			}


		}
	}

	@Override
	public boolean saveRjzzq(CgRjzzqEntity rjzzq) {
		if (isDuplicate(rjzzq)) {
			throw new ServiceException("软件名称已存在");
		}
		return this.save(rjzzq);
	}

	@Override
	public boolean updateRjzzq(CgRjzzqEntity rjzzq) {
		if (isDuplicate(rjzzq)) {
			throw new ServiceException("软件名称已存在");
		}
		return updateById(rjzzq);
	}

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

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

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

	@SneakyThrows
	@Override
	public void export(OutputStream os, List<CgRjzzqEntity> list) {
		AtomicInteger index = new AtomicInteger(1);
		List<CgRjzzqExcel> results = new ArrayList<>();
		list.forEach(temp -> {
			CgRjzzqExcel excel = BeanUtil.copyProperties(temp, CgRjzzqExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			excel.setKfwcrqStr(Func.notNull(temp.getKfwcrq()) ? DateUtil.format(temp.getKfwcrq(), DateUtil.PATTERN_DATE) : null);
			excel.setScfbrqStr(Func.notNull(temp.getScfbrq()) ? DateUtil.format(temp.getScfbrq(), DateUtil.PATTERN_DATE) : null);
			excel.setDjpzrqStr(Func.notNull(temp.getDjpzrq()) ? DateUtil.format(temp.getDjpzrq(), 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();
		}
	}

}
