
package org.sky.scientific.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.JSON;
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.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.mp.support.Condition;
import org.sky.core.mp.support.Query;
import org.sky.core.secure.utils.SecureUtil;
import org.sky.core.tool.api.R;
import org.sky.core.tool.utils.Charsets;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.e.AssetCategoryEnum;
import org.sky.scientific.mapper.*;
import org.sky.scientific.pojo.dto.*;
import org.sky.scientific.pojo.entity.*;
import org.sky.scientific.pojo.vo.*;
import org.sky.scientific.service.IEnterpriseInfoService;
import org.sky.scientific.service.IXmCostDetailsService;
import org.sky.scientific.utils.TemplateService;
import org.sky.system.cache.RegionCache;
import org.sky.system.feign.ISysClient;
import org.sky.system.pojo.entity.Region;
import org.sky.system.pojo.entity.Tenant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 企业基础信息表 服务实现类
 *
 * @author Kd
 * @since 2025-08-14
 */
@Service
@AllArgsConstructor
public class EnterpriseInfoServiceImpl extends BaseServiceImpl<EnterpriseInfoMapper, EnterpriseInfoEntity> implements IEnterpriseInfoService {

	private final A107_1Mapper a107_1Mapper;
	private final A107_2Mapper a107_2Mapper;
	private final A107012Mapper a107012Mapper;
	private final A107041Mapper a107041Mapper;
	private final HighTechYbMapper highTechYbMapper;
	private final TechnicianMapper technicianMapper;
	private final AssetMapper assetMapper;
	private final XmFixedAssetMapper fixedAssetMapper;
	private final CgZlMapper zlMapper;
	private final CgKylwMapper kylwMapper;
	private final CgJsbzMapper jsbzMapper;
	private final CgRjzzqMapper rjzzqMapper;
	private final CgQtMapper qtMapper;

	private final XmWwxmCostMapper wwxmCostMapper;
	private final IXmCostDetailsService xmCostDetailsService;
	private final EnterpriseInfoMapper enterpriseInfoMapper;
	private final XmMapper xmMapper;
	private final ISysClient sysClient;
	private final TemplateService templateService;
	private final XmFixedAssetMapper xmFixedAssetMapper;
	private final XmTechnicianMapper xmTechnicianMapper;


	@Override
	@Transactional
	public Boolean fetchLastYearData(EnterpriseInfoEntity enterpriseInfo) {
		if (Func.isBlank(enterpriseInfo.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		String lastYear = DateUtil.format(DateUtil.minusYears(DateUtil.parse(enterpriseInfo.getYearAndMonth(), DateUtil.PATTERN_YYYY), 1), DateUtil.PATTERN_YYYY);
		LambdaQueryWrapper<EnterpriseInfoEntity> eq = Wrappers.<EnterpriseInfoEntity>lambdaQuery()
			.eq(EnterpriseInfoEntity::getYearAndMonth, lastYear);
		EnterpriseInfoEntity previousYearData = this.getOne(eq);
		if (Func.isNull(previousYearData)) {
			throw new ServiceException("上年度没有数据");
		}

		List<String> ignorePropList = Arrays.asList("id","yearAndMonth","currentYearIncome", "currentYearCost","previousYearIncome","previousYearCost","lastYearIncome","lastYearCost");

		// 企业基础信息表
		EnterpriseInfoEntity dbEntity = this.getOne(Wrappers.<EnterpriseInfoEntity>lambdaQuery()
			.eq(EnterpriseInfoEntity::getYearAndMonth, enterpriseInfo.getYearAndMonth()));
		if (Func.isNull(dbEntity)) {
			//新增
			EnterpriseInfoEntity entity = BeanUtil.copyProperties(previousYearData, EnterpriseInfoEntity.class,  ignorePropList.toArray(new String[0]));
			entity.setTenantId(SecureUtil.getTenantId());
			entity.setYearAndMonth(enterpriseInfo.getYearAndMonth());
			entity.setPreviousYearCost(previousYearData.getCurrentYearCost());
			entity.setPreviousYearIncome(previousYearData.getCurrentYearIncome());
			entity.setLastYearCost(previousYearData.getPreviousYearCost());
			entity.setLastYearIncome(previousYearData.getPreviousYearIncome());

			return this.save(entity);
		} else {
			//修改
			BeanUtil.copyProperties(previousYearData, dbEntity,  ignorePropList.toArray(new String[0]));
			dbEntity.setPreviousYearCost(previousYearData.getCurrentYearCost());
			dbEntity.setPreviousYearIncome(previousYearData.getCurrentYearIncome());
			dbEntity.setLastYearCost(previousYearData.getPreviousYearCost());
			dbEntity.setLastYearIncome(previousYearData.getPreviousYearIncome());
			return this.updateById(dbEntity);
		}
	}

	@Override
	public boolean submit(EnterpriseInfoEntity enterpriseInfo) {
		if (Func.isBlank(enterpriseInfo.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		boolean result = false;

		LambdaQueryWrapper<EnterpriseInfoEntity> eq = Wrappers.<EnterpriseInfoEntity>lambdaQuery()
			.eq(EnterpriseInfoEntity::getYearAndMonth, enterpriseInfo.getYearAndMonth())
			.eq(EnterpriseInfoEntity::getTenantId, SecureUtil.getTenantId());
		EnterpriseInfoEntity one = this.getOne(eq);

		if (Func.isNull(one)) {
			//新增
			result = this.save(enterpriseInfo);
		} else {
			//修改
			enterpriseInfo.setId(one.getId());
			result = this.updateById(enterpriseInfo);
		}
		return result;
	}

	@Override
	public List<A107_1VO> qyyjkfxmqk107_1(String year) {
		if (Func.isNull(year)) {
			throw new ServiceException("参数year不能为空");
		}
		if (year.length() != 4) {
			throw new ServiceException("参数year为年份，如2025");
		}

		List<JSONObject> tempList = xmTechnicianMapper.statisticsWorkHoursByXmAndUnicodeAndMonth(SecureUtil.getTenantId(), year);

		Map<String, List<JSONObject>> mapByXmId = new HashMap<>();
		if (Func.isNotEmpty(tempList)) {
			mapByXmId = tempList.stream().collect(Collectors.groupingBy(item -> item.getString("xmId")));
		}

		List<A107_1VO> list = a107_1Mapper.qyyjkfxmqk(year, SecureUtil.getTenantId());
		for (A107_1VO vo : list) {

//			项目人员实际工作时间（人月）
			double workTime = 0d;
			List<JSONObject> listByXmId = mapByXmId.get(vo.getXmId() + "");
			if (Func.isNotEmpty(listByXmId)) {
				for (JSONObject o : listByXmId) {
					double workHours = o.getDouble("workHours") == null ? 0d : o.getDouble("workHours");
					double attendanceHours = o.getDouble("attendanceHours") == null ? 0d : o.getDouble("attendanceHours");

					workTime += (workHours == 0 || attendanceHours == 0) ? 0d : workHours / attendanceHours;
				}
			}

			vo.setWorkTime(BigDecimal.valueOf(workTime).setScale(2, RoundingMode.HALF_UP).doubleValue());

			//当列15等于基础研究时，列14=P088中对应研发项目的受托方类型的前5项的委外金额合计。当列15不等于基础研究时，列14等于0
			if (Func.equals(vo.getYjlx(), "基础研究")) {
				//对应研发项目的受托方类型的前5项的委外金额合计
				vo.setWwfy(wwxmCostMapper.getAmountByXmAndYear(year, vo.getXmId()));

				XmCostDetailsDTO dto = new XmCostDetailsDTO();
				dto.setXmId(vo.getXmId());
				dto.setYearAndMonth(year + "12");
				List<FinanceCostSummary> summaryList = xmCostDetailsService.financeCostSummary(Condition.getPage(new Query().setCurrent(1).setSize(1)), dto).getRecords();
				if (Func.isEmpty(summaryList)) {
					vo.setCost(BigDecimal.ZERO);
					vo.setCost1(BigDecimal.ZERO);
				} else {
					FinanceCostSummary summary = summaryList.get(0);
					vo.setCost(summary.getTotal());
					vo.setCost1(summary.getTotal());
				}
			} else {
				vo.setCost(BigDecimal.ZERO);
				vo.setCost1(BigDecimal.ZERO);
				vo.setWwfy(BigDecimal.ZERO);
			}
			//其中：企业自主开展=用于科学原理的探索发现的经费总额-委托外单位开展
			vo.setCost2(vo.getCost1().subtract(vo.getWwfy()));
		}
		return list;
	}

	@Override
	public Boolean updateQyyjkfxmqk107_1(A107_1 a1071) {
		LambdaQueryWrapper<A107_1> eq = Wrappers.<A107_1>lambdaQuery().eq(A107_1::getYearAndMonth, a1071.getYearAndMonth())
			.eq(A107_1::getXmId, a1071.getXmId());
		A107_1 one = a107_1Mapper.selectOne(eq);
		if (Func.isNull(one)) {
			a1071.setTenantId(SecureUtil.getTenantId());
			return a107_1Mapper.insert(a1071) == 1;
		} else {
			a1071.setId(one.getId());
			return a107_1Mapper.updateById(a1071) == 1;
		}
	}

	@SneakyThrows
	@Override
	public void exportQyyjkfxmqk107_1(HttpServletResponse response, String year) {
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/对外报表管理/107-1.xlsx");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("107-1企业研究开发项目情况.xlsx", Charsets.UTF_8));
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLSX)
			.build();

		Map<String, Object> map = new HashMap<>();

		List<A107_1VO> list = this.qyyjkfxmqk107_1(year);
		AtomicInteger index = new AtomicInteger(1);
		list.forEach(item -> {
			item.setXh(index.getAndIncrement() + "");
			item.setKssjStr(DateUtil.format(item.getKssj(), DateUtil.PATTERN_YYYYMM));
			item.setJssjStr(DateUtil.format(item.getJssj(), DateUtil.PATTERN_YYYYMM));
		});

		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		//设置list集合数据
		excelWriter.fill(list, fillConfig, writeSheet);

		map.put("year", year);

		R<Tenant> tenant = sysClient.getTenant(SecureUtil.getTenantId());
		if (tenant.isSuccess()) {
			map.put("enterpriseName", tenant.getData().getTenantName());
			map.put("uscc", tenant.getData().getUscc());
		}

		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@Override
	public A107_2VO qyyjkfhdjxgfy107_2(String year) {
		if (Func.isNull(year)) {
			throw new ServiceException("参数year不能为空");
		}
		if (year.length() != 4) {
			throw new ServiceException("参数year为年份，如2025");
		}

		A107_2VO vo = new A107_2VO();
		A107_2 db = a107_2Mapper.selectOne(Wrappers.<A107_2>lambdaQuery().eq(A107_2::getYearAndMonth, year).eq(A107_2::getTenantId, SecureUtil.getTenantId()));
		if (Func.notNull(db)) {
			BeanUtil.copyProperties(db, vo);
		}

		//一、研究开发人员情况
		statisticsYanjiuKaifaRenyuanQingkuang(vo, year);

		//二、研究开发费用情况
		statisticsCost(vo, year);
		if (Func.isNull(vo.getD26()) || vo.getD26().compareTo(BigDecimal.ZERO) <= 0) {
			vo.setD26(vo.getD7());
		}

		// 三、研究开发资产情况
		// d20 当年形成用于研发开发的固定资产
		statisticsFixedAsset(vo, year);

		//四、研究开发支出资金来源
		statisticsD43_D57(vo, year);

		//五、相关政策落实情况
		XmCostDetailsDTO costDetailsDTO = new XmCostDetailsDTO();
		costDetailsDTO.setYearAndMonth(year + "12");
		DeductionCostSummary summary = xmCostDetailsService.deductionCostSummary(costDetailsDTO);
		//申报加计扣除减免税的研究开发支出
		vo.setD52(Func.isNull(summary) ? BigDecimal.ZERO : summary.getYxjjkcjehj_hjje().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//加计扣除减免税金额

		A107012 a107012 = a107012Mapper.selectOne(Wrappers.<A107012>lambdaQuery().eq(A107012::getYearAndMonth, year));
		BigDecimal a107012_d41 = Func.isNull(summary) ? BigDecimal.ZERO : summary.getTotal_fyh();
		BigDecimal a107012_d43 = BigDecimal.ZERO;
		BigDecimal a107012_d44 = BigDecimal.ZERO;
		BigDecimal a107012_d46 = BigDecimal.ZERO;
		BigDecimal a107012_d48 = BigDecimal.ZERO;
		BigDecimal a107012_d49 = BigDecimal.ZERO;
		if (Func.notNull(a107012)) {
			a107012_d43 = a107012.getD43();
			a107012_d44 = a107012.getD44();
			a107012_d46 = a107012.getD46();
			a107012_d48 = a107012.getD48();
			a107012_d49 = a107012.getD49();

		}
		//六、允许扣除的研发费用合计（41+43+44）
		BigDecimal a107012_d45 = a107012_d41.add(a107012_d43).add(a107012_d44);

		//七、允许扣除的研发费用抵减特殊收入后的金额（45-46）
		BigDecimal a107012_d47 = a107012_d45.subtract(a107012_d46);

		//九、本年研发费用加计扣除总额（47-48-49）×50，50为固定的100%
		//如果当年是高企，就税率为15%，如非高企，税率为25%
		vo.setD44(a107012_d47.subtract(a107012_d48).subtract(a107012_d49));
		if (enterpriseInfoMapper.selectCount(Wrappers.<EnterpriseInfoEntity>lambdaQuery().eq(EnterpriseInfoEntity::getHighTechYear, year)) > 0) {
			vo.setD44(vo.getD44().multiply(new BigDecimal("0.15")).multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		} else {
			vo.setD44(vo.getD44().multiply(new BigDecimal("0.25")).multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		}

		//六、企业办研究开发机构 （境内）情况
		// d27 :期末仪器和设备原价
		IPage<XmFixedAsset> p2 = Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE));
		XmAssetQueryParam param = new XmAssetQueryParam();
		param.setYearAndMonth(year + "12");
		List<XmFixedAsset> yiqishebeiList = fixedAssetMapper.selectXmFixedAssetPageByYearAndMonth(p2, param, AssetCategoryEnum.仪器设备.getCode());
		for (XmFixedAsset asset : yiqishebeiList) {
			vo.setD27(vo.getD7().add(asset.getAsset() != null ? asset.getAsset().getZcyz() : BigDecimal.ZERO));
		}
		vo.setD27(vo.getD27().setScale(2, RoundingMode.HALF_UP));

		//七、研究开发产出及相关情况
		List<CgZlEntity> zlList = zlMapper.selectList(Wrappers.<CgZlEntity>lambdaQuery().eq(CgZlEntity::getTenantId, SecureUtil.getTenantId()));

		int d29 = 0, d30 = 0, d32 = 0;
		Date dateMin = DateUtil.parse(year + "-01-01", DateUtil.PATTERN_DATE);
		Date dateMax = DateUtil.parse(year + "-12-31", DateUtil.PATTERN_DATE);
		for (CgZlEntity zl : zlList) {
			Date shenqingRq = zl.getShenqingRq();
			Date shouquanRq = zl.getShouquanRq();
			if (Func.notNull(shenqingRq)) {
				d29++;
				if (Func.equals(year, DateUtil.format(shenqingRq, DateUtil.PATTERN_YYYY))) {
					d30++;
				}
			}
			if (Func.notNull(shouquanRq) && shouquanRq.before(dateMax) && shouquanRq.after(dateMin)) {
				d32++;
			}
		}
		vo.setD29(d29);
		vo.setD30(d30);
		vo.setD32(d32);
		vo.setD33(vo.getD32());

		Long d40 = kylwMapper.selectCount(Wrappers.<CgKylwEntity>lambdaQuery().between(CgKylwEntity::getFbrq, dateMin, dateMax));
		vo.setD40(Func.toInt(d40, 0));

		Long d41 = jsbzMapper.selectCount(Wrappers.<CgJsbzEntity>lambdaQuery()
			.between(CgJsbzEntity::getSsrq, dateMin, dateMax)
			.eq(CgJsbzEntity::getState, "现行有效")
			.in(CgJsbzEntity::getBzlb, List.of("国家标准", "行业标准")));
		vo.setD41(Func.toInt(d41, 0));

		//八、其他相关情况
		//当年企业研发准备金合计
		List<XmEntity> xmList = xmMapper.selectList(Wrappers.emptyWrapper());
		for (XmEntity xm : xmList) {
			String xmyszemx = xm.getXmyszemx();
			if (Func.notNull(xmyszemx)) {
				List<JSONObject> array = JSON.parseArray(xmyszemx, JSONObject.class);
				double sum = array.stream().filter(item -> item.getInteger("year") == Integer.parseInt(year)).mapToDouble(item -> item.getDouble("amount")).sum();
				System.out.println("sum:" + sum);
				vo.setD59(vo.getD59().add(BigDecimal.valueOf(sum)));
				System.out.println("d59:" + vo.getD59());
			}
		}
		//预算的单位是万，这里要显示千元，故乘以10即可，即1万=10千元
		vo.setD59(vo.getD59().multiply(new BigDecimal("10")).setScale(2, RoundingMode.HALF_UP));

		return vo;
	}

	private void statisticsD43_D57(A107_2VO vo, String year) {
		//2.来自政府部门
		List<A107_1> d43List = a107_1Mapper.selectList(Wrappers.<A107_1>lambdaQuery().eq(A107_1::getYearAndMonth, year));
		for (A107_1 a1071 : d43List) {
			vo.setD43(vo.getD43().add(a1071.getGovBonus()));
		}
		vo.setD43(vo.getD43().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//1.来自企业自筹 =行7-行43-行58-行55-行56
		vo.setD57(vo.getD7().subtract(vo.getD43()).subtract(vo.getD58()).subtract(vo.getD55()).subtract(vo.getD56()));
	}

	private void statisticsFixedAsset(A107_2VO vo, String year) {
		XmAssetQueryParam p = new XmAssetQueryParam();
		p.setYearAndMonth(year);
		List<XmFixedAsset> yiqishebeiList = xmFixedAssetMapper.selectXmFixedAssetPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), p, AssetCategoryEnum.仪器设备.getCode());
		List<XmFixedAsset> fangwujianzhuwuList = xmFixedAssetMapper.selectXmFixedAssetPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), p, AssetCategoryEnum.房屋建筑物.getCode());

		BigDecimal yiqishebeiTotal = BigDecimal.ZERO;
		for (XmFixedAsset yiqishebei : yiqishebeiList) {
			AssetEntity asset = yiqishebei.getAsset();
			if (asset != null && Func.equals(DateUtil.format(asset.getKssj(), DateUtil.PATTERN_YYYY), year)) {
				yiqishebeiTotal = yiqishebeiTotal.add(asset.getZcyz());
			}
		}

		BigDecimal fangwujianzhuwuTotal = BigDecimal.ZERO;
		for (XmFixedAsset fangwujianzhuwu : fangwujianzhuwuList) {
			AssetEntity asset = fangwujianzhuwu.getAsset();
			if (asset != null && Func.equals(DateUtil.format(asset.getKssj(), DateUtil.PATTERN_YYYY), year)) {
				yiqishebeiTotal = fangwujianzhuwuTotal.add(asset.getZcyz());
			}
		}
		vo.setD20(fangwujianzhuwuTotal.add(yiqishebeiTotal).multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		// d21 其中：仪器和设备
		vo.setD21(yiqishebeiTotal.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
	}

	private void statisticsYanjiuKaifaRenyuanQingkuang(A107_2VO vo, String year) {
		IPage<TechnicianVO> page = Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE));
		TechnicianDTO dto = new TechnicianDTO();
		dto.setYearAndMonth(year);
		dto.setTenantId(SecureUtil.getTenantId());
		List<TechnicianVO> technicianVOList = technicianMapper.niandugaokejirenyuanhuizongbiao(page, dto);

		int d1 = 0, d3 = 0, d4 = 0, d5 = 0, d6 = 0;
		if (Func.isNotEmpty(technicianVOList)) {
			d1 = technicianVOList.size();
			d3 = (int) technicianVOList.stream().filter(item -> item.getGender() == 2).count();
			d5 = (int) technicianVOList.stream().filter(item -> List.of("本科", "硕士研究生", "博士研究生").contains(item.getEducation())).count();
		}
		vo.setD1(d1);
		vo.setD3(d3);
		vo.setD4(d4);
		vo.setD5(d5);
		vo.setD6(d6);
	}

	private void statisticsCost(A107_2VO vo, String year) {
		CostSummaryDTO costSummaryDTO = new CostSummaryDTO();
		costSummaryDTO.setStartYearMonth(year + "01");
		costSummaryDTO.setMonthCount(12);
		costSummaryDTO.setTenantId(SecureUtil.getTenantId());
		List<CostSummaryVO> list = assetMapper.costSummary(costSummaryDTO);
		for (CostSummaryVO costSummaryVO : list) {
			costSummaryVO.setWwfyAdjust(costSummaryVO.getWwfy().multiply(new BigDecimal("0.8")).setScale(2, RoundingMode.HALF_UP));
			costSummaryVO.setTotal(costSummaryVO.getRyrgfy().add(costSummaryVO.getZjtrfy()).add(costSummaryVO.getZjfyycqdtfy()).add(costSummaryVO.getSjfy()).add(costSummaryVO.getWxzctxfy()).add(costSummaryVO.getZbtsfyysyfy()).add(costSummaryVO.getQtfy()).add(costSummaryVO.getWwfyAdjust()).setScale(2, RoundingMode.HALF_UP));
			vo.setD8(vo.getD8().add(costSummaryVO.getRyrgfy()));
			vo.setD9(vo.getD9().add(costSummaryVO.getZjtrfy()));
			vo.setD10(vo.getD10().add(costSummaryVO.getZjfyycqdtfy()));
			vo.setD11(vo.getD11().add(costSummaryVO.getWxzctxfy()));
			vo.setD12(vo.getD12().add(costSummaryVO.getSjfy()));
			vo.setD13(vo.getD13().add(costSummaryVO.getZbtsfyysyfy()));
			vo.setD14(vo.getD14().add(costSummaryVO.getWwfy()));
			vo.setD19(vo.getD19().add(costSummaryVO.getQtfy()));
		}

		//换算成千元
		//1.人员人工费用
		vo.setD8(vo.getD8().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//2.直接投入费用
		vo.setD9(vo.getD9().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//3.折旧费用与长期待摊费用
		vo.setD10(vo.getD10().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//4.无形资产摊销费用
		vo.setD11(vo.getD11().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//5.设计费用
		vo.setD12(vo.getD12().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//6.装备调试费用与试验费用
		vo.setD13(vo.getD13().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//7.委托外部研究开发费用
		vo.setD14(vo.getD14().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//8.其他费用
		vo.setD19(vo.getD19().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));

		XmWwxmCostQuery wwxmCostQuery = new XmWwxmCostQuery();
		wwxmCostQuery.setYearAndMonth(year);
		List<XmWwxmCostVO> wwxmCostVOList = wwxmCostMapper.selectPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), wwxmCostQuery);

		//①委托境内研究机构
		BigDecimal d15 = wwxmCostVOList.stream().filter(item -> Func.equals(item.getStflx(), "境内研究机构")).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
		vo.setD15(d15.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//②委托境内高等学校
		BigDecimal d16 = wwxmCostVOList.stream().filter(item -> Func.equals(item.getStflx(), "境内高等学校")).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
		vo.setD16(d16.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//③委托境内企业
		BigDecimal d17 = wwxmCostVOList.stream().filter(item -> Func.equals(item.getStflx(), "境内企业")).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
		vo.setD17(d17.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		//④委托境外机构
		BigDecimal d18 = wwxmCostVOList.stream().filter(item -> Func.equals(item.getStflx(), "境外机构")).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
		vo.setD18(d18.multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));

		vo.setD7(vo.getD8().add(vo.getD9()).add(vo.getD10()).add(vo.getD11()).add(vo.getD12()).add(vo.getD13()).add(vo.getD14()).add(vo.getD19()));
	}

	@Override
	public boolean updateQyyjkfhdjxgfy107_2(A107_2 a1072) {
		LambdaQueryWrapper<A107_2> eq = Wrappers.<A107_2>lambdaQuery().eq(A107_2::getYearAndMonth, a1072.getYearAndMonth());
		A107_2 one = a107_2Mapper.selectOne(eq);
		if (Func.isNull(one)) {
			a1072.setTenantId(SecureUtil.getTenantId());
			return a107_2Mapper.insert(a1072) == 1;
		} else {
			a1072.setId(one.getId());
			return a107_2Mapper.updateById(a1072) == 1;
		}
	}

	@SneakyThrows
	@Override
	public void exportQyyjkfhdjxgqk107_2(HttpServletResponse response, String year) {
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/对外报表管理/107-2.xlsx");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("107-2企业研究开发活动及相关情况.xlsx", Charsets.UTF_8));
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLSX)
			.build();
		A107_2VO vo = this.qyyjkfhdjxgfy107_2(year);

		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		//设置list集合数据
		Map<String, Object> map = new HashMap<>();
		BeanUtil.copyProperties(vo, map);
		map.put("year", year);
		R<Tenant> tenant = sysClient.getTenant(SecureUtil.getTenantId());
		if (tenant.isSuccess()) {
			map.put("enterpriseName", tenant.getData().getTenantName());
			map.put("uscc", tenant.getData().getUscc());
		}
		excelWriter.fill(map, fillConfig, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@Override
	public A107012VO yffyjjkcyhmxbA107012(String year) {
		if (Func.isNull(year)) {
			throw new ServiceException("参数year不能为空");
		}
		if (year.length() != 4) {
			throw new ServiceException("参数year为年份，如2025");
		}
		A107012VO vo = new A107012VO();
		A107012 one = a107012Mapper.selectOne(Wrappers.<A107012>lambdaQuery().eq(A107012::getYearAndMonth, year));

		BigDecimal d43 = new BigDecimal("0.00"), d44 = new BigDecimal("0.00"), d46 = new BigDecimal("0.00"), d48 = new BigDecimal("0.00"), d49 = new BigDecimal("0.00");
		if (Func.notNull(one)) {
			d43 = one.getD43();
			d44 = one.getD44();
			d46 = one.getD46();
			d48 = one.getD48();
			d49 = one.getD49();
		}
		vo.setD43(d43);
		vo.setD44(d44);
		vo.setD46(d46);
		vo.setD48(d48);
		vo.setD49(d49);

		XmCostDetailsDTO costDetailsDTO = new XmCostDetailsDTO();
		costDetailsDTO.setYearAndMonth(year + "12");
		DeductionCostSummary summary = xmCostDetailsService.deductionCostSummary(costDetailsDTO);

		vo.setD1(Func.isNull(summary) ? 0 : (int) summary.getItemList().stream().map(DeductionCostSummaryItem::getXmId).distinct().count());
		//（一）人员人工费用（4+5+6）
		vo.setD3(Func.isNull(summary) ? BigDecimal.ZERO : summary.getRyrgfy_hjje());
		//(二）直接投入费用（8+9+10+11+12+13+14+15）
		vo.setD7(Func.isNull(summary) ? BigDecimal.ZERO : summary.getZjtrfy_hjje());
		//（三）折旧费用（17+18）
		vo.setD16(Func.isNull(summary) ? BigDecimal.ZERO : summary.getZjfy_hjje());
		//（四）无形资产摊销（20+21+22）
		vo.setD19(Func.isNull(summary) ? BigDecimal.ZERO : summary.getWxzctx_hjje());
		//（五）新产品设计费
		vo.setD23(Func.isNull(summary) ? BigDecimal.ZERO : summary.getXcpsjfd_hjje());
		//（六）其他相关费用
		vo.setD28(Func.isNull(summary) ? BigDecimal.ZERO : summary.getQtxgfyhj_hjje());
		//（七）经限额调整后的其他相关费用
		vo.setD34(Func.isNull(summary) ? BigDecimal.ZERO : summary.getQtxgfyhj_adjust_hjje());

		//一、自主研发、合作研发、集中研发（3+7+16+19+23+34）
		vo.setD2(vo.getD3().add(vo.getD7()).add(vo.getD16()).add(vo.getD19()).add(vo.getD23()).add(vo.getD28()).add(vo.getD34()));

		//二、委托研发（36+37+39）
		//（一）委托境内机构或个人进行研发活动所发生的费用
		vo.setD36(Func.isNull(summary) ? BigDecimal.ZERO : summary.getWtjnjgfy_hjje());
		//（二）委托境外机构进行研发活动发生的费用
		vo.setD37(Func.isNull(summary) ? BigDecimal.ZERO : summary.getWtjwjgfy_hjje());
		//其中：允许加计扣除的委托境外机构进行研发活动发生的费用
		vo.setD38(Func.isNull(summary) ? BigDecimal.ZERO : summary.getWtjwjgfy_adjust_hjje());
		//（三）委托境外个人进行研发活动发生的费用
		XmWwxmCostQuery wwxmCostQuery = new XmWwxmCostQuery();
		wwxmCostQuery.setYearAndMonth(year);
		List<XmWwxmCostVO> wwxmCostVOList1 = wwxmCostMapper.selectPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), wwxmCostQuery);
		vo.setD39(wwxmCostVOList1.stream().filter(t -> "境外个人".equalsIgnoreCase(t.getStflx())).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD35(vo.getD36().add(vo.getD37()).add(vo.getD39()));

		//三、年度研发费用小计（2+36×80%+38）
		//（一）本年费用化金额
		vo.setD41(Func.isNull(summary) ? BigDecimal.ZERO : summary.getTotal_fyh());
		//（二）本年资本化金额
		vo.setD42(Func.isNull(summary) ? BigDecimal.ZERO : summary.getTotal_zbh());

		//一、自主研发、合作研发、集中研发（3+7+16+19+23+34）
		vo.setD2(vo.getD3().add(vo.getD7()).add(vo.getD16()).add(vo.getD19()).add(vo.getD23()).add(vo.getD34()));

		//三、年度研发费用小计（2+36×80%+38）
		vo.setD40(vo.getD2().add(vo.getD36().multiply(new BigDecimal("0.8"))).add(vo.getD38()));

		//六、允许扣除的研发费用合计（41+43+44）
		vo.setD45(vo.getD41().add(vo.getD43()).add(vo.getD44()));

		//七、允许扣除的研发费用抵减特殊收入后的金额（45-46）
		vo.setD47(vo.getD45().subtract(vo.getD46()));

		//九、本年研发费用加计扣除总额（47-48-49）×50，50为固定的100%
		vo.setD51((vo.getD47().subtract(vo.getD48()).subtract(vo.getD49())));

		//十、销售研发活动直接形成产品（包括组成部分）对应材料部分转移以后年度扣减金额（当47-48-49≥0，本行=0；当47-48-49<0，本行=47-48-49的绝对值）
		vo.setD52(vo.getD51().compareTo(BigDecimal.ZERO) > 0 ? BigDecimal.ZERO : vo.getD51().abs());
		return vo;
	}

	@Override
	public boolean updateYffyjjkcyhmxbA107012(A107012 a107012) {
		LambdaQueryWrapper<A107012> eq = Wrappers.<A107012>lambdaQuery().eq(A107012::getYearAndMonth, a107012.getYearAndMonth());
		A107012 one = a107012Mapper.selectOne(eq);
		if (Func.isNull(one)) {
			a107012.setTenantId(SecureUtil.getTenantId());
			return a107012Mapper.insert(a107012) == 1;
		} else {
			a107012.setId(one.getId());
			return a107012Mapper.updateById(a107012) == 1;
		}
	}

	@SneakyThrows
	@Override
	public void exportYffyjjkcyhmxbA107012(OutputStream os, String year) {
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/对外报表管理/A107012.xlsx");

		ExcelWriter excelWriter = EasyExcel.write(os)
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLSX)
			.build();
		A107012VO vo = this.yffyjjkcyhmxbA107012(year);

		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		//设置list集合数据
		Map<String, Object> map = new HashMap<>();
		BeanUtil.copyProperties(vo, map);
		map.put("dL1", vo.getD47().subtract(vo.getD48()).subtract(vo.getD49()));

		excelWriter.fill(map, fillConfig, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@Override
	public A107041VO gxjsqyyhqkjmxbA107041(String year) {
		if (Func.isNull(year)) {
			throw new ServiceException("参数year不能为空");
		}
		if (year.length() != 4) {
			throw new ServiceException("参数year为年份，如2025");
		}

		A107041VO vo = new A107041VO();

		//国家重点支持的高新技术领域
		EnterpriseInfoEntity enterpriseInfo = enterpriseInfoMapper.selectOne(Wrappers.<EnterpriseInfoEntity>lambdaQuery()
			.eq(EnterpriseInfoEntity::getYearAndMonth, year)
			.eq(EnterpriseInfoEntity::getTenantId, SecureUtil.getTenantId()));
		if (Func.notNull(enterpriseInfo)) {
			vo.setD1(enterpriseInfo.getHighTechDomainL1Name());
			vo.setD2(enterpriseInfo.getHighTechDomainL2Name());
			vo.setD3(enterpriseInfo.getHighTechDomainL3Name());
		}

		A107041 one = a107041Mapper.selectOne(Wrappers.<A107041>lambdaQuery().eq(A107041::getYearAndMonth, year));

		BigDecimal d5 = new BigDecimal("0.00"), d6 = new BigDecimal("0.00"), d8 = new BigDecimal("0.00"), d9 = new BigDecimal("0.00");
		int d12 = 0;
		BigDecimal d29_1 = new BigDecimal("0.00"), d29_2 = new BigDecimal("0.00"), d29_3 = new BigDecimal("0.00"), d31 = new BigDecimal("0.00"), d32 = new BigDecimal("0.00");

		if (Func.notNull(one)) {
			d5 = one.getD5();
			d6 = one.getD6();
			d8 = one.getD8();
			d9 = one.getD9();
			d12 = one.getD12();
			d29_1 = one.getD2901();
			d29_2 = one.getD2902();
			d29_3 = one.getD2903();
			d31 = one.getD31();
			d32 = one.getD32();
		}

		vo.setD5(d5);
		vo.setD6(d6);
		vo.setD4(vo.getD5().add(vo.getD6()));
		vo.setD8(d8);
		vo.setD9(d9);
		vo.setD7(vo.getD6().subtract(vo.getD9()));

		vo.setD10(vo.getD7().doubleValue() == 0 ? BigDecimal.ZERO : vo.getD4().divide(vo.getD7(), 4, RoundingMode.HALF_UP));

		//四、本年科技人员数
		IPage<TechnicianVO> page = Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE));
		TechnicianDTO dto = new TechnicianDTO();
		dto.setYearAndMonth(year);
		dto.setTenantId(SecureUtil.getTenantId());
		List<TechnicianVO> technicianVOList = technicianMapper.niandugaokejirenyuanhuizongbiao(page, dto);
		vo.setD11(Func.isEmpty(technicianVOList) ? 0 : technicianVOList.size());
		//五、本年职工总数
		vo.setD12(d12);
		//六、本年科技人员占企业当年职工总数的比例（11÷12）
		vo.setD13(vo.getD12() == 0 ? BigDecimal.ZERO : BigDecimal.valueOf((vo.getD11() * 1.0) / vo.getD12()));

		XmCostDetailsDTO xmCostDetailsDTO = new XmCostDetailsDTO();
		xmCostDetailsDTO.setYearAndMonth(year + "12");
		List<HighTechCostSummary> summaryList1 = xmCostDetailsService.highTechCostSummary(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), xmCostDetailsDTO).getRecords();

		xmCostDetailsDTO = new XmCostDetailsDTO();
		xmCostDetailsDTO.setYearAndMonth(Integer.parseInt(year) - 1 + "12");
		List<HighTechCostSummary> summaryList2 = xmCostDetailsService.highTechCostSummary(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), xmCostDetailsDTO).getRecords();

		xmCostDetailsDTO = new XmCostDetailsDTO();
		xmCostDetailsDTO.setYearAndMonth(Integer.parseInt(year) - 2 + "12");
		List<HighTechCostSummary> summaryList3 = xmCostDetailsService.highTechCostSummary(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), xmCostDetailsDTO).getRecords();

		//七、归集的高新研发费用金额（16+25）
		//一）内部研究开发投入
		//1.人员人工费用
		vo.setD17_1(summaryList1.stream().map(HighTechCostSummary::getRyrgTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD17_2(summaryList2.stream().map(HighTechCostSummary::getRyrgTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD17_3(summaryList3.stream().map(HighTechCostSummary::getRyrgTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD17_4(vo.getD17_1().add(vo.getD17_2()).add(vo.getD17_3()));

		//2.直接投入费用
		vo.setD18_1(summaryList1.stream().map(HighTechCostSummary::getZjtrTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD18_2(summaryList2.stream().map(HighTechCostSummary::getZjtrTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD18_3(summaryList3.stream().map(HighTechCostSummary::getZjtrTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD18_4(vo.getD18_1().add(vo.getD18_2()).add(vo.getD18_3()));

		//3.折旧费用与长期待摊费用
		vo.setD19_1(summaryList1.stream().map(HighTechCostSummary::getZjfyycqdtfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD19_2(summaryList2.stream().map(HighTechCostSummary::getZjfyycqdtfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD19_3(summaryList3.stream().map(HighTechCostSummary::getZjfyycqdtfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD19_4(vo.getD19_1().add(vo.getD19_2()).add(vo.getD19_3()));

		//4.无形资产摊销费用
		vo.setD20_1(summaryList1.stream().map(HighTechCostSummary::getWxzctxTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD20_2(summaryList2.stream().map(HighTechCostSummary::getWxzctxTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD20_3(summaryList3.stream().map(HighTechCostSummary::getWxzctxTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD20_4(vo.getD20_1().add(vo.getD20_2()).add(vo.getD20_3()));

		//5.设计费用
		vo.setD21_1(summaryList1.stream().map(HighTechCostSummary::getSjfTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD21_2(summaryList2.stream().map(HighTechCostSummary::getSjfTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD21_3(summaryList3.stream().map(HighTechCostSummary::getSjfTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD21_4(vo.getD21_1().add(vo.getD21_2()).add(vo.getD21_3()));

		//6.设备调试费与实验费用
		vo.setD22_1(summaryList1.stream().map(HighTechCostSummary::getZbtsfyysyfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD22_2(summaryList2.stream().map(HighTechCostSummary::getZbtsfyysyfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD22_3(summaryList3.stream().map(HighTechCostSummary::getZbtsfyysyfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD22_4(vo.getD22_1().add(vo.getD22_2()).add(vo.getD22_3()));

		//7.其他费用
		vo.setD23_1(summaryList1.stream().map(HighTechCostSummary::getQtfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD23_2(summaryList2.stream().map(HighTechCostSummary::getQtfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD23_3(summaryList3.stream().map(HighTechCostSummary::getQtfyTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD23_4(vo.getD23_1().add(vo.getD23_2()).add(vo.getD23_3()));

		//其中：可计入研发费用的其他费用

		vo.setD24_1(summaryList1.stream().map(HighTechCostSummary::getQtfyAdjust).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD24_2(summaryList2.stream().map(HighTechCostSummary::getQtfyAdjust).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD24_3(summaryList3.stream().map(HighTechCostSummary::getQtfyAdjust).reduce(BigDecimal.ZERO, BigDecimal::add));
		vo.setD24_4(vo.getD24_1().add(vo.getD24_2()).add(vo.getD24_3()));

		XmWwxmCostQuery wwxmCostQuery = new XmWwxmCostQuery();
		wwxmCostQuery.setYearAndMonth(year);
		List<XmWwxmCostVO> wwxmCostVOList1 = wwxmCostMapper.selectPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), wwxmCostQuery);

		wwxmCostQuery = new XmWwxmCostQuery();
		wwxmCostQuery.setYearAndMonth(Integer.parseInt(year) - 1 + "12");
		List<XmWwxmCostVO> wwxmCostVOList2 = wwxmCostMapper.selectPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), wwxmCostQuery);

		wwxmCostQuery = new XmWwxmCostQuery();
		wwxmCostQuery.setYearAndMonth(Integer.parseInt(year) - 2 + "12");
		List<XmWwxmCostVO> wwxmCostVOList3 = wwxmCostMapper.selectPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), wwxmCostQuery);

		//二）委托外部研发费用【（26+28）×80%】
		//1.境内的外部研发费
		BigDecimal d26_1 = wwxmCostVOList1.stream().filter(t -> Arrays.asList("境内研究机构", "境内高等学校", "境内企业", "境内个人").contains(t.getStflx())).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
		vo.setD26_1(d26_1);
		BigDecimal d26_2 = wwxmCostVOList2.stream().filter(t -> Arrays.asList("境内研究机构", "境内高等学校", "境内企业", "境内个人").contains(t.getStflx())).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
		vo.setD26_2(d26_2);
		BigDecimal d26_3 = wwxmCostVOList3.stream().filter(t -> Arrays.asList("境内研究机构", "境内高等学校", "境内企业", "境内个人").contains(t.getStflx())).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
		vo.setD26_3(d26_3);
		vo.setD26_4(vo.getD26_1().add(vo.getD26_2()).add(vo.getD26_3()));
		//2.境外的外部研发费
		BigDecimal d27_1 = wwxmCostVOList1.stream().filter(t -> Arrays.asList("境外机构", "境外个人").contains(t.getStflx())).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
		vo.setD27_1(d27_1);
		BigDecimal d27_2 = wwxmCostVOList2.stream().filter(t -> Arrays.asList("境外机构", "境外个人").contains(t.getStflx())).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
		vo.setD27_2(d27_2);
		BigDecimal d27_3 = wwxmCostVOList3.stream().filter(t -> Arrays.asList("境外机构", "境外个人").contains(t.getStflx())).map(XmWwxmCostVO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
		vo.setD27_3(d27_3);
		vo.setD27_4(vo.getD27_1().add(vo.getD27_2()).add(vo.getD27_3()));

		XmCostDetailsDTO costDetailsDTO = new XmCostDetailsDTO();
		costDetailsDTO.setYearAndMonth(year + "12");
		DeductionCostSummary summary = xmCostDetailsService.deductionCostSummary(costDetailsDTO);
		vo.setD28_1(Func.isNull(summary) ? BigDecimal.ZERO : summary.getWtjwjgfy_adjust_hjje());

		costDetailsDTO.setYearAndMonth((Integer.parseInt(year) - 1) + "12");
		summary = xmCostDetailsService.deductionCostSummary(costDetailsDTO);
		vo.setD28_2(Func.isNull(summary) ? BigDecimal.ZERO : summary.getWtjwjgfy_adjust_hjje());

		costDetailsDTO.setYearAndMonth((Integer.parseInt(year) - 2) + "12");
		summary = xmCostDetailsService.deductionCostSummary(costDetailsDTO);
		vo.setD28_3(Func.isNull(summary) ? BigDecimal.ZERO : summary.getWtjwjgfy_adjust_hjje());

		vo.setD28_4(vo.getD28_1().add(vo.getD28_2()).add(vo.getD28_3()));

		vo.setD15_1(vo.getD16_1().add(vo.getD25_1()));
		vo.setD15_2(vo.getD16_2().add(vo.getD25_2()));
		vo.setD15_3(vo.getD16_3().add(vo.getD25_3()));
		vo.setD15_4(vo.getD15_1().add(vo.getD15_2()).add(vo.getD15_3()));

		vo.setD16_1(vo.getD17_1().add(vo.getD18_1()).add(vo.getD19_1()).add(vo.getD20_1()).add(vo.getD21_1()).add(vo.getD22_1()).add(vo.getD23_1()).add(vo.getD24_1()));
		vo.setD16_2(vo.getD17_2().add(vo.getD18_2()).add(vo.getD19_2()).add(vo.getD20_2()).add(vo.getD21_2()).add(vo.getD22_2()).add(vo.getD23_2()).add(vo.getD24_2()));
		vo.setD16_3(vo.getD17_3().add(vo.getD18_3()).add(vo.getD19_3()).add(vo.getD20_3()).add(vo.getD21_3()).add(vo.getD22_3()).add(vo.getD23_3()).add(vo.getD24_3()));
		vo.setD16_4(vo.getD16_1().add(vo.getD16_2()).add(vo.getD16_3()));

		vo.setD25_1(vo.getD26_1().add(vo.getD28_1().multiply(BigDecimal.valueOf(0.8))));
		vo.setD25_2(vo.getD26_2().add(vo.getD28_2().multiply(BigDecimal.valueOf(0.8))));
		vo.setD25_3(vo.getD26_3().add(vo.getD28_3().multiply(BigDecimal.valueOf(0.8))));
		vo.setD25_4(vo.getD25_1().add(vo.getD25_2()).add(vo.getD25_3()));

		vo.setD2901(d29_1 == null ? BigDecimal.ZERO : d29_1);
		vo.setD2902(d29_2 == null ? BigDecimal.ZERO : d29_2);
		vo.setD2903(d29_3 == null ? BigDecimal.ZERO : d29_3);

		vo.setD2904(vo.getD2901().add(vo.getD2902()).add(vo.getD2903()));

		//九、三年研发费用占销售（营业）收入的比例（15行第4列/29行第4列）
		vo.setD30((vo.getD2904().compareTo(BigDecimal.ZERO) == 0) ? BigDecimal.ZERO : vo.getD15_4().divide(vo.getD2904()));

		vo.setD31(d31);
		vo.setD32(d32);
		return vo;
	}

	@Override
	public boolean updateGxjsqyyhqkjmxbA107041(A107041 a107041) {
		LambdaQueryWrapper<A107041> eq = Wrappers.<A107041>lambdaQuery().eq(A107041::getYearAndMonth, a107041.getYearAndMonth());
		A107041 one = a107041Mapper.selectOne(eq);
		if (Func.isNull(one)) {
			a107041.setTenantId(SecureUtil.getTenantId());
			return a107041Mapper.insert(a107041) == 1;
		} else {
			a107041.setId(one.getId());
			return a107041Mapper.updateById(a107041) == 1;
		}
	}

	@SneakyThrows
	@Override
	public void exportQxjsqyyhqkjmxbA107041(HttpServletResponse response, String year) {
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/对外报表管理/A107041.xlsx");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("A107041高新技术企业优惠情况及明细表.xlsx", Charsets.UTF_8));
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLSX)
			.build();
		A107041VO vo = this.gxjsqyyhqkjmxbA107041(year);

		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		//设置list集合数据
		Map<String, Object> map = new HashMap<>();
		BeanUtil.copyProperties(vo, map);

		excelWriter.fill(map, fillConfig, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}

	@Override
	public HighTechYBVO gqnb(String year) {
		if (Func.isNull(year)) {
			throw new ServiceException("参数year不能为空");
		}
		if (year.length() != 4) {
			throw new ServiceException("参数year为年份，如2025");
		}
		HighTechYBVO vo = new HighTechYBVO();
		vo.setYearAndMonth(year);

		R<Tenant> r = sysClient.getTenant(SecureUtil.getTenantId());
		if (r.isSuccess()) {
			Tenant tenant = r.getData();
			vo.setEnterpriseName(tenant.getTenantName());
			vo.setUscc(tenant.getUscc());
			vo.setLinkman(tenant.getLinkman());
			vo.setContactNumber(tenant.getContactNumber());
			if (Func.isNotEmpty(tenant.getDistrictCode())) {
				Region region = RegionCache.getByCode(tenant.getDistrictCode());
				if (region != null) {
					vo.setRegionName(region.getProvinceName() + "-" + region.getCityName() + "-" + region.getDistrictName());
				}
			}
		}

		EnterpriseInfoEntity enterpriseInfo = enterpriseInfoMapper.selectOne(Wrappers.<EnterpriseInfoEntity>lambdaQuery().eq(EnterpriseInfoEntity::getYearAndMonth, year));
		if (Func.notNull(enterpriseInfo)) {
			vo.setHighTechNumber(enterpriseInfo.getHighTechNumber());
			vo.setHighTechYear(enterpriseInfo.getHighTechYear());
		}

		HighTechYB db = highTechYbMapper.selectOne(Wrappers.<HighTechYB>lambdaQuery().eq(HighTechYB::getYearAndMonth, year));
		if (Func.notNull(db)) {
			BeanUtil.copyProperties(db, vo);
		}
		Date dateMin = DateUtil.parse(year + "-01-01", DateUtil.PATTERN_DATE);
		Date dateMax = DateUtil.parse(year + "-12-31", DateUtil.PATTERN_DATE);
		List<CgZlEntity> zlList = zlMapper.selectList(Wrappers.<CgZlEntity>lambdaQuery().between(CgZlEntity::getShouquanRq, dateMin, dateMax));
		int d2 = 0, d3 = 0, d9 = 0, d10 = 0;
		if (Func.isNotEmpty(zlList)) {
			d2 = (int) zlList.stream().filter(item -> Func.equals(item.getZllx(), "发明专利")).count();
			d3 = (int) zlList.stream().filter(item -> Func.equals(item.getZllx(), "发明专利") && Func.equals(item.getSfgfzl(), "是")).count();
			d9 = (int) zlList.stream().filter(item -> Func.equals(item.getZllx(), "实用新型专利")).count();
			d10 = (int) zlList.stream().filter(item -> Func.equals(item.getZllx(), "外观专利")).count();
		}
		vo.setD2(d2);
		vo.setD3(d3);
		vo.setD9(d9);
		vo.setD10(d10);

		int d4 = 0, d5 = 0, d6 = 0, d7 = 0, d8 = 0;
		List<CgQtEntity> qtList = qtMapper.selectList(Wrappers.<CgQtEntity>lambdaQuery().between(CgQtEntity::getShouquanRq, dateMin, dateMax));
		if (Func.isNotEmpty(qtList)) {
			d4 = (int) qtList.stream().filter(item -> Func.equals(item.getCmlx(), "植物新品种")).count();
			d5 = (int) qtList.stream().filter(item -> Func.equals(item.getCmlx(), "国家级农作物品种")).count();
			d6 = (int) qtList.stream().filter(item -> Func.equals(item.getCmlx(), "国家新药")).count();
			d7 = (int) qtList.stream().filter(item -> Func.equals(item.getCmlx(), "国家一级中药保护品种")).count();
			d8 = (int) qtList.stream().filter(item -> Func.equals(item.getCmlx(), "集成电路布图设计专有权")).count();
		}
		vo.setD4(d4);
		vo.setD5(d5);
		vo.setD6(d6);
		vo.setD7(d7);
		vo.setD8(d8);

		//当年获得软件著作权
		Long count = rjzzqMapper.countByYear(year, SecureUtil.getTenantId());
		vo.setD11(count.intValue());

		vo.setD1(vo.getD2() - vo.getD3() + vo.getD4() + vo.getD5() + vo.getD6() + vo.getD7() + vo.getD8() + vo.getD9() + vo.getD10() + vo.getD11());

		Query query = new Query();
		query.setCurrent(1);
		query.setSize(Integer.MAX_VALUE);
		IPage<TechnicianVO> page = Condition.getPage(query);
		TechnicianDTO dto = new TechnicianDTO();
		dto.setYearAndMonth(year);
		dto.setTenantId(SecureUtil.getTenantId());
		List<TechnicianVO> technicianVOList = technicianMapper.niandugaokejirenyuanhuizongbiao(page, dto);

		int d14 = 0;
		if (Func.isNotEmpty(technicianVOList)) {
			d14 = technicianVOList.size();
		}
		//科技人员数
		vo.setD14(d14);

		//销售收入
		if (Func.notNull(enterpriseInfo)) {
			vo.setD19(enterpriseInfo.getCurrentYearIncome().toPlainString());
		} else {
			vo.setD19("0.00");
		}
		//todo 研究开发费用额
		//取数:对外报表-107-2表-二、研究开发费用情况-研究开发费用合计
		A107_2VO a107_2VO = new A107_2VO();
		statisticsCost(a107_2VO, year);
		vo.setD26(a107_2VO.getD7().toPlainString());

		//取数:对外报表:107.2表，六、企业办研究开发机构(境内)情况,机构研究开发费用
		A107_2 a1072 = a107_2Mapper.selectOne(Wrappers.<A107_2>lambdaQuery().eq(A107_2::getYearAndMonth, year));
		if (Func.isNull(a1072)) {
			vo.setD28(a107_2VO.getD7().toPlainString());
		} else {
			vo.setD28(a1072.getD26().toPlainString());
		}

		//取数：对外报表-107-2表，三、研究开发资本情况-当年形成用于研发开发的固定资本
		XmAssetQueryParam p = new XmAssetQueryParam();
		p.setYearAndMonth(year);
		List<XmFixedAsset> yiqishebeiList = xmFixedAssetMapper.selectXmFixedAssetPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), p, AssetCategoryEnum.仪器设备.getCode());
		List<XmFixedAsset> fangwujianzhuwuList = xmFixedAssetMapper.selectXmFixedAssetPageByYear(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), p, AssetCategoryEnum.房屋建筑物.getCode());

		BigDecimal yiqishebeiTotal = BigDecimal.ZERO;
		for (XmFixedAsset yiqishebei : yiqishebeiList) {
			AssetEntity asset = yiqishebei.getAsset();
			if (asset != null && Func.equals(DateUtil.format(asset.getKssj(), DateUtil.PATTERN_YYYY), year)) {
				yiqishebeiTotal = yiqishebeiTotal.add(asset.getZcyz());
			}
		}

		BigDecimal fangwujianzhuwuTotal = BigDecimal.ZERO;
		for (XmFixedAsset fangwujianzhuwu : fangwujianzhuwuList) {
			AssetEntity asset = fangwujianzhuwu.getAsset();
			if (asset != null && Func.equals(DateUtil.format(asset.getKssj(), DateUtil.PATTERN_YYYY), year)) {
				yiqishebeiTotal = fangwujianzhuwuTotal.add(asset.getZcyz());
			}
		}
		vo.setD29(fangwujianzhuwuTotal.add(yiqishebeiTotal).multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP).toPlainString());
		return vo;
	}

	@Override
	public boolean gqnbUpdate(HighTechYB highTechYB) {
		LambdaQueryWrapper<HighTechYB> eq = Wrappers.<HighTechYB>lambdaQuery().eq(HighTechYB::getYearAndMonth, highTechYB.getYearAndMonth());
		HighTechYB one = highTechYbMapper.selectOne(eq);
		if (Func.isNull(one)) {
			highTechYB.setTenantId(SecureUtil.getTenantId());
			return highTechYbMapper.insert(highTechYB) == 1;
		} else {
			highTechYB.setId(one.getId());
			return highTechYbMapper.updateById(highTechYB) == 1;
		}
	}

	@SneakyThrows
	@Override
	public void exportGqnb(OutputStream os, HighTechYBVO techYBVO) {

		templateService.processTemplate("年度高新技术企业发展情况报表.ftl", techYBVO, new OutputStreamWriter(os));
	}

	@Override
	public TorchDevYBVO torchDevYB(String year) {
		TorchDevYBVO vo = new TorchDevYBVO();

		//企业概况
		EnterpriseInfoEntity enterpriseInfo = enterpriseInfoMapper.selectOne(Wrappers.<EnterpriseInfoEntity>lambdaQuery().eq(EnterpriseInfoEntity::getYearAndMonth, year));
		if (Func.notNull(enterpriseInfo)) {
			vo.setQb13(enterpriseInfo.getHighTechNumber());
			vo.setQb11("是");
		} else {
			vo.setQb11("否");
		}

		//经济概况
		//研发费用
		XmCostDetailsDTO dto = new XmCostDetailsDTO();
		dto.setYearAndMonth(year + "12");
		List<HighTechCostSummary> list = xmCostDetailsService.highTechCostSummary(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto).getRecords();
		list.forEach(item -> {
			item.setTotal(item.getRyrgTotal().add(item.getZjtrTotal()).add(item.getZjfyycqdtfyTotal()).add(item.getSjfTotal()).add(item.getWxzctxTotal()).add(item.getZbtsfyysyfyTotal()).add(item.getQtfyAdjust()).add(item.getWwyfTotal()));
		});
		vo.setQc236(list.stream().map(HighTechCostSummary::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add).multiply(new BigDecimal("0.001")));

		//享受高新技术企业所得税减免
		A107041 a107041 = a107041Mapper.selectOne(Wrappers.<A107041>lambdaQuery().eq(A107041::getYearAndMonth, year));
		if (Func.notNull(a107041)) {
			vo.setQc20_1(a107041.getD31());
		}

		List<A107_1VO> a107_1VOList = this.qyyjkfxmqk107_1(year);
		Integer xh = 1;
		for (A107_1VO a1071VO : a107_1VOList) {
			a1071VO.setXh(xh + "");
			a1071VO.setKssjStr(Func.notNull(a1071VO.getKssj()) ? DateUtil.format(a1071VO.getKssj(), DateUtil.PATTERN_DATE) : null);
			a1071VO.setJssjStr(Func.notNull(a1071VO.getJssj()) ? DateUtil.format(a1071VO.getJssj(), DateUtil.PATTERN_DATE) : null);
			xh++;
		}
		vo.setA1071(a107_1VOList);

		//一、研究开发人员情况
		A107_2VO a107_2VO = new A107_2VO();
		A107_2 db107_2 = a107_2Mapper.selectOne(Wrappers.<A107_2>lambdaQuery().eq(A107_2::getYearAndMonth, year).eq(A107_2::getTenantId, SecureUtil.getTenantId()));
		if (Func.notNull(db107_2)) {
			BeanUtil.copyProperties(db107_2, a107_2VO);
		}
		this.statisticsYanjiuKaifaRenyuanQingkuang(a107_2VO, year);
		vo.setQj09(a107_2VO.getD1());
		vo.setQj68(a107_2VO.getD2());
		vo.setQj09_1(a107_2VO.getD4());
		vo.setQj09_2(a107_2VO.getD5());
		vo.setQj09_3(a107_2VO.getD6());

		//二、研究开发费用情况
		statisticsCost(a107_2VO, year);
		vo.setQj20(a107_2VO.getD7());
		vo.setQj23_1(a107_2VO.getD8());
		vo.setQj23_2(a107_2VO.getD9());
		vo.setQj23_3(a107_2VO.getD10());
		vo.setQj23_4(a107_2VO.getD11());
		vo.setQj23_6(a107_2VO.getD12());
		vo.setQj23_7(a107_2VO.getD13());
		vo.setQj33(a107_2VO.getD14());
		vo.setQj33_1(a107_2VO.getD15());
		vo.setQj33_2(a107_2VO.getD16());
		vo.setQj33_3(a107_2VO.getD17());
		vo.setQj33_4(a107_2VO.getD18());
		vo.setQj33_5(a107_2VO.getD19());

		//三、研究开发资产情况
		statisticsFixedAsset(a107_2VO, year);
		vo.setQj250(a107_2VO.getD20());
		vo.setQj251(a107_2VO.getD21());

		//四、研究开发支出资金来源情况
		vo.setQj253(a107_2VO.getD58());
		vo.setQj254(a107_2VO.getD55());
		vo.setQj255(a107_2VO.getD56());

		statisticsD43_D57(a107_2VO, year);
		vo.setQj256(a107_2VO.getD57());
		vo.setQj252(a107_2VO.getD43());

		//五、企业办研究开发机构（境内）情况
		vo.setQi01(a107_2VO.getD22());
		vo.setQi07_0(a107_2VO.getD23());
		vo.setQi07_1(a107_2VO.getD24());
		vo.setQi07_2(a107_2VO.getD25());
		vo.setQi14_1(a107_2VO.getD26());

		//六、研究开发产出及相关情况
		//（一）自主知识产权情况
		List<CgZlEntity> zlList = zlMapper.selectList(Wrappers.<CgZlEntity>lambdaQuery().eq(CgZlEntity::getTenantId, SecureUtil.getTenantId()));

		Date dateMin = DateUtil.parse(year + "-01-01", DateUtil.PATTERN_DATE);
		Date dateMax = DateUtil.parse(year + "-12-31", DateUtil.PATTERN_DATE);

		vo.setQj55(zlList.stream().filter(zl -> Func.notNull(zl.getShenqingRq()) && zl.getShenqingRq().before(dateMax) && zl.getShenqingRq().after(dateMin)).count());
		vo.setQj56(zlList.stream().filter(zl -> Func.notNull(zl.getShenqingRq()) && zl.getShenqingRq().before(dateMax) && zl.getShenqingRq().after(dateMin) && Func.equals("发明专利", zl.getZllx())).count());
		vo.setQj56_1(zlList.stream().filter(zl -> Func.notNull(zl.getShenqingRq()) && zl.getShenqingRq().before(dateMax) && zl.getShenqingRq().after(dateMin) && Func.equals("发明专利", zl.getZllx()) && Func.equals("国内", zl.getGb())).count());
		vo.setQj55_1(zlList.stream().filter(zl -> Func.notNull(zl.getShenqingRq()) && zl.getShenqingRq().before(dateMax) && zl.getShenqingRq().after(dateMin) && Func.equals("境外（欧美日）", zl.getGb())).count());
		vo.setQj55_2(zlList.stream().filter(zl -> Func.notNull(zl.getShenqingRq()) && zl.getShenqingRq().before(dateMax) && zl.getShenqingRq().after(dateMin) && Func.equals("PCT国际专利", zl.getGb())).count());

		vo.setQj74(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && zl.getShouquanRq().after(dateMin)).count());
		vo.setQj57(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && zl.getShouquanRq().after(dateMin) && Func.equals("发明专利", zl.getZllx())).count());
		vo.setQj57_1(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && zl.getShouquanRq().after(dateMin) && Func.equals("发明专利", zl.getZllx()) && Func.equals("国内", zl.getGb())).count());
		vo.setQj75(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && zl.getShouquanRq().after(dateMin) && Func.equals("境外（欧美日）", zl.getGb())).count());

		vo.setQj83(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && Func.equals("授权有效", zl.getFlzt())).count());
		vo.setQj83_1(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && Func.equals("授权有效", zl.getFlzt()) && Arrays.asList("境外（除欧美日外）", "境外（欧美日）").contains(zl.getGb())).count());
		vo.setQj82(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && Func.equals("授权有效", zl.getFlzt()) && Func.equals("境外（欧美日）", zl.getGb())).count());
		vo.setQj73(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && Func.equals("授权有效", zl.getFlzt()) && Func.equals("发明专利", zl.getZllx())).count());
		vo.setQj73_1(zlList.stream().filter(zl -> Func.notNull(zl.getShouquanRq()) && zl.getShouquanRq().before(dateMax) && Func.equals("授权有效", zl.getFlzt()) && Func.equals("发明专利", zl.getZllx()) && Arrays.asList("境外（除欧美日外）", "境外（欧美日）").contains(zl.getGb())).count());

		//（三）其他情况
		//发表科技论文
		List<CgKylwEntity> kylwList = kylwMapper.selectList(Wrappers.<CgKylwEntity>lambdaQuery().eq(CgKylwEntity::getTenantId, SecureUtil.getTenantId()));
		vo.setQi25(Func.isEmpty(kylwList) ? 0 : kylwList.size());
		//拥有软件著作权
		List<CgRjzzqEntity> rjzzqList = rjzzqMapper.selectList(Wrappers.<CgRjzzqEntity>lambdaQuery().eq(CgRjzzqEntity::getTenantId, SecureUtil.getTenantId()));
		vo.setQj85(Func.isEmpty(rjzzqList) ? 0 : rjzzqList.size());
		//其中：当年获得软件著作权
		vo.setQj85_1(rjzzqList.stream().filter(item -> Func.notNull(item.getDjpzrq()) && item.getDjpzrq().before(dateMax) && item.getDjpzrq().after(dateMin)).count());
		//拥有集成电路布图
		List<CgQtEntity> qtList = qtMapper.selectList(Wrappers.<CgQtEntity>lambdaQuery().eq(CgQtEntity::getTenantId, SecureUtil.getTenantId()));
		vo.setQj86(qtList.stream().filter(item -> Func.notNull(item.getShouquanRq()) && Func.equals(item.getCmlx(), "集成电路布图设计专有权")).count());
		//其中：当年获得集成电路布图
		vo.setQj86_1(qtList.stream().filter(item -> Func.notNull(item.getShouquanRq()) && Func.equals(item.getCmlx(), "集成电路布图设计专有权") && item.getShouquanRq().before(dateMax) && item.getShouquanRq().after(dateMin)).count());
		//拥有植物新品种
		vo.setQj87(qtList.stream().filter(item -> Func.equals(item.getCmlx(), "植物新品种")).count());
		vo.setQj87_1(qtList.stream().filter(item -> Func.notNull(item.getShouquanRq()) && Func.equals(item.getCmlx(), "植物新品种") && item.getShouquanRq().before(dateMax) && item.getShouquanRq().after(dateMin)).count());
		//拥有国家一类新药品种
		vo.setQj101(qtList.stream().filter(item -> Func.equals(item.getCmlx(), "国家新药")).count());
		vo.setQj101_1(qtList.stream().filter(item -> Func.notNull(item.getShouquanRq()) && Func.equals(item.getCmlx(), "国家新药") && item.getShouquanRq().before(dateMax) && item.getShouquanRq().after(dateMin)).count());
		//拥有国家一级中药保护品种
		vo.setQj100(qtList.stream().filter(item -> Func.equals(item.getCmlx(), "国家一级中药保护品种")).count());
		vo.setQj100_1(qtList.stream().filter(item -> Func.notNull(item.getShouquanRq()) && Func.equals(item.getCmlx(), "国家一级中药保护品种") && item.getShouquanRq().before(dateMax) && item.getShouquanRq().after(dateMin)).count());
		//累计形成国际标准
		List<CgJsbzEntity> jsbzList = jsbzMapper.selectList(Wrappers.<CgJsbzEntity>lambdaQuery().eq(CgJsbzEntity::getTenantId, SecureUtil.getTenantId()));
		vo.setQj98(jsbzList.stream().filter(item -> Func.equals(item.getBzlb(), "国际标准")).count());
		vo.setQj98_1(jsbzList.stream().filter(item -> Func.notNull(item.getSsrq()) && Func.equals(item.getBzlb(), "国际标准") && Func.equals(item.getState(), "现行有效") && item.getSsrq().before(dateMax) && item.getSsrq().after(dateMin)).count());
		//累计形成国家或行业标准
		vo.setQi27(jsbzList.stream().filter(item -> Func.equals(item.getBzlb(), "国家标准") || Func.equals(item.getBzlb(), "行业标准")).count());
		vo.setQi27_1(jsbzList.stream().filter(item -> Func.notNull(item.getSsrq()) && Func.equals(item.getBzlb(), "国家标准") || Func.equals(item.getBzlb(), "行业标准") && Func.equals(item.getState(), "现行有效") && item.getSsrq() != null && item.getSsrq().before(dateMax) && item.getSsrq().after(dateMin)).count());
		return vo;
	}

	@SneakyThrows
	@Override
	public void exportTorchDevYB(HttpServletResponse response, String year) {
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/对外报表管理/火炬发展年报.xlsx");
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("火炬发展年报.xlsx", Charsets.UTF_8));
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLSX)
			.build();
		TorchDevYBVO torchDevYBVO = this.torchDevYB(year);
		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		excelWriter.fill(torchDevYBVO.getA1071(), fillConfig, writeSheet);

		//设置list集合数据
		excelWriter.fill(torchDevYBVO, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
	}
}
