
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.CgKylwExcel;
import org.sky.scientific.excel.listener.CgKylwImportListener;
import org.sky.scientific.mapper.CgKylwMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.entity.CgKylwEntity;
import org.sky.scientific.service.ICgKylwService;
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 CgKylwServiceImpl extends BaseServiceImpl<CgKylwMapper, CgKylwEntity> implements ICgKylwService {

	@Resource
	private XmMapper xmMapper;

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

    @SneakyThrows
	@Override
    public void export(OutputStream os, List<CgKylwEntity> list) {
		AtomicInteger index = new AtomicInteger(1);
		List<CgKylwExcel> results = new ArrayList<>();
		list.forEach(temp -> {
			CgKylwExcel excel = BeanUtil.copyProperties(temp, CgKylwExcel.class);
			assert excel != null;
			excel.setXh(index.getAndIncrement() + "");
			excel.setFbrqStr(Func.notNull(temp.getFbrq())?DateUtil.format(temp.getFbrq(), 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();
		}
     }

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

	@Override
	public boolean save(CgKylwEntity cgKylw) {
		if(isDuplicate(cgKylw)){
			throw new ServiceException("论文名称已存在");
		}
		return super.save(cgKylw);
	}

	@Override
	public boolean update(CgKylwEntity cgKylw) {
		if(isDuplicate(cgKylw)){
			throw new ServiceException("论文名称已存在");
		}
		return updateById(cgKylw);
	}

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

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

}
