
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.CgJsbzExcel;
import org.sky.scientific.excel.listener.CgJsbzImportListener;
import org.sky.scientific.mapper.CgJsbzMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.entity.CgJsbzEntity;
import org.sky.scientific.service.ICgJsbzService;
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 CgJsbzServiceImpl extends BaseServiceImpl<CgJsbzMapper, CgJsbzEntity> implements ICgJsbzService {

	@Resource
	private XmMapper xmMapper;

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

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

	@Override
	public boolean save(CgJsbzEntity cgJsbz) {
		if (isDuplicate(cgJsbz)) {
			throw new ServiceException("标准号/标准名称已存在");
		}
		return super.save(cgJsbz);
	}

	@Override
	public boolean update(CgJsbzEntity cgJsbz) {
		if (isDuplicate(cgJsbz)) {
			throw new ServiceException("标准号/标准名称已存在");
		}
		return updateById(cgJsbz);
	}

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

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

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