
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 lombok.AllArgsConstructor;
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.*;
import org.sky.scientific.pojo.entity.*;
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
@AllArgsConstructor
public class CgZlServiceImpl extends BaseServiceImpl<CgZlMapper, CgZlEntity> implements ICgZlService {

	private final XmMapper xmMapper;
	private final CgRjzzqMapper rjzzqMapper;
	private final CgJsbzMapper jsbzMapper;
	private final CgKylwMapper kylwMapper;
	private final CgQtMapper qtMapper;


	@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);
			}
			try {
				this.save(zlDTO);
			} catch (Exception e) {
				throw new ServiceException("序号为[" + excel.getXh() + "]的数据错误");
			}

		}
	}

	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) {
//		总数= 专利数+软著数+标准数+论文数+其他数量
//		专利数= 专利申请中数+专利授权有效数+已失效数（申请中，包括表示还在进行中，未授权）
//		软著数=申请数=授权数
//		技术标准数=尚未发布数（申请中）+现行有效数（已授权）+废止数
//		标准数=申请数=授权数
//		其他成果数=申请数=授权数

		int intYear = Integer.parseInt(year);

		JSONObject result = new JSONObject();
		long total = 0, shenqingshu = 0, shouquanshu = 0;

   		List<CgZlEntity> zlList = baseMapper.selectList(Wrappers.<CgZlEntity>lambdaQuery().apply("DATE_FORMAT(SHENQING_RQ,'%Y') <= {0} or DATE_FORMAT(SHOUQUAN_RQ,'%Y') <= {1}", year, year));


 		shenqingshu += zlList.stream().filter(temp-> Func.notNull(temp.getShenqingRq()) && cn.hutool.core.date.DateUtil.year(temp.getShenqingRq()) <= intYear).count();
		shouquanshu += zlList.stream().filter(temp-> Func.notNull(temp.getShouquanRq()) && cn.hutool.core.date.DateUtil.year(temp.getShouquanRq()) <= intYear).count();

		total += Func.isEmpty(zlList)?0:zlList.size();

		long rjzzq = rjzzqMapper.selectCount(Wrappers.<CgRjzzqEntity>lambdaQuery().apply("DATE_FORMAT(DJPZRQ,'%Y') <= {0}", year));
		total += rjzzq;
		shenqingshu += rjzzq;
		shouquanshu += rjzzq;

		long jsbz = jsbzMapper.selectCount(Wrappers.<CgJsbzEntity>lambdaQuery().apply("DATE_FORMAT(SSRQ,'%Y') <= {0}", year));
		total += jsbz;
		shenqingshu += jsbz;
		shouquanshu += jsbz;

		long kylw = kylwMapper.selectCount(Wrappers.<CgKylwEntity>lambdaQuery().apply("DATE_FORMAT(FBRQ,'%Y') <= {0}", year));
		total += kylw;
		shenqingshu += kylw;
		shouquanshu += kylw;

		List<CgQtEntity> qtEntityList = qtMapper.selectList(Wrappers.<CgQtEntity>lambdaQuery().apply("DATE_FORMAT(SHENQING_RQ,'%Y') <= {0} or DATE_FORMAT(SHOUQUAN_RQ,'%Y') <= {1}", year, year));
		shenqingshu += qtEntityList.stream().filter(temp-> Func.notNull(temp.getShenqingRq())).count();
		shouquanshu += qtEntityList.stream().filter(temp-> Func.notNull(temp.getShouquanRq())).count();
		total += Func.isEmpty(qtEntityList)?0:qtEntityList.size();

 		result.put("total", total);
		result.put("shenqingshu", shenqingshu);
		result.put("shouquanshu", shouquanshu);

		return result;
	}

}
