
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.CgZlExcel;
import org.sky.scientific.excel.listener.CgZlImportListener;
import org.sky.scientific.mapper.CgZlMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.entity.CgZlEntity;
import org.sky.scientific.service.ICgZlService;
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 CgZlServiceImpl extends BaseServiceImpl<CgZlMapper, CgZlEntity> implements ICgZlService {

	@Resource
	private XmMapper xmMapper;

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

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

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

	@Override
	public boolean save(CgZlEntity cgZl) {
		if (isDuplicate(cgZl)) {
			throw new ServiceException("专利号/专利名称已存在");
		}

		return super.save(cgZl);
	}

	@Override
	public boolean update(CgZlEntity cgZl) {
		if (isDuplicate(cgZl)) {
			throw new ServiceException("专利号/专利名称已存在");
		}
		return updateById(cgZl);
	}

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

	@SneakyThrows
	@Override
	public void exportZl(OutputStream os, List<CgZlEntity> list) {
		AtomicInteger index = new AtomicInteger(1);
		List<CgZlExcel> results = new ArrayList<>();
		list.forEach(temp -> {
			CgZlExcel excel = BeanUtil.copyProperties(temp, CgZlExcel.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();
		}
	}

	@Override
	public JSONObject zlDashboard(String tenantId, String year) {
		return baseMapper.zlDashboard(tenantId, year);
	}

}
