
package org.sky.scientific.service.impl;

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 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.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.mapper.*;
import org.sky.scientific.pojo.dto.CostSummaryDTO;
import org.sky.scientific.pojo.dto.TechnicianDTO;
import org.sky.scientific.pojo.dto.XmAssetQueryParam;
import org.sky.scientific.pojo.entity.*;
import org.sky.scientific.pojo.vo.*;
import org.sky.scientific.service.IEnterpriseInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * 企业基础信息表 服务实现类
 *
 * @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 ArchiveAttachMapper attachMapper;

	@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 one = this.getOne(eq);
		if (Func.isNull(one)) {
			throw new ServiceException("上年度没有数据");
		}
		one.setYearAndMonth(enterpriseInfo.getYearAndMonth());

		// 企业基础信息表
		EnterpriseInfoEntity dbEntity = this.getOne(Wrappers.<EnterpriseInfoEntity>lambdaQuery()
			.eq(EnterpriseInfoEntity::getYearAndMonth, enterpriseInfo.getYearAndMonth()));
		if (Func.isNull(dbEntity)) {
			//新增
			one.setId(null);
			return this.save(one);
		} else {
			//修改
			one.setId(dbEntity.getId());
			return this.updateById(one);
		}
	}

	@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> qyyjkfxmqk(String year) {
		if (Func.isNull(year)) {
			throw new ServiceException("参数year不能为空");
		}
		if (year.length() != 4) {
			throw new ServiceException("参数year为年份，如2025");
		}
		List<A107_1VO> list = a107_1Mapper.qyyjkfxmqk(year, SecureUtil.getTenantId());
		return list;
	}

	@Override
	public Boolean qyyjkfxmqkUpdate(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;
		}
	}

	@Override
	public A107_2VO qyyjkfhdjxgfy(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)) {
			vo.setD2(db.getD2());
			vo.setD58(db.getD58());
			vo.setD55(db.getD55());
			vo.setD56(db.getD56());
			vo.setD45(db.getD45());
			vo.setD22(db.getD22());
			vo.setD23(db.getD23());
			vo.setD24(db.getD24());
			vo.setD25(db.getD25());
			vo.setD26(db.getD26());
			vo.setD53(db.getD53());
			vo.setD54(db.getD54());
			vo.setD36(db.getD36());
			vo.setD37(db.getD37());
			vo.setD38(db.getD38());
			vo.setD46(db.getD46());
			vo.setD47(db.getD47());
			vo.setD48(db.getD48());
			vo.setD49(db.getD49());
			vo.setD50(db.getD50());
			vo.setAttachment(db.getAttachment());
		}

		//一、研究开发人员情况
		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 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);

		//二、研究开发费用情况
		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.setD8(vo.getD8().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		vo.setD9(vo.getD9().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		vo.setD10(vo.getD10().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		vo.setD11(vo.getD11().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		vo.setD12(vo.getD12().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		vo.setD13(vo.getD13().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));
		vo.setD14(vo.getD14().multiply(new BigDecimal("0.001")).setScale(2, RoundingMode.HALF_UP));

		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().setScale(2, RoundingMode.HALF_UP));


		IPage<XmFixedAsset> p2 = Condition.getPage(query);
		XmAssetQueryParam param = new XmAssetQueryParam();
		param.setYearAndMonth(year + "12");
		List<XmFixedAsset> yiqishebeiList = fixedAssetMapper.selectXmFixedAssetPageByYearAndMonth(p2, param, "仪器设备");
		for (XmFixedAsset asset : yiqishebeiList) {
			vo.setD27(vo.getD7().add(asset.getAsset().getZcyz()));
		}
		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));


		return vo;
	}

	@Override
	public boolean qyyjkfhdjxgfyUpdate(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;
		}
	}

	@Override
	public A107012VO yffyjjkcyhmxb(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);

		return vo;
	}

	@Override
	public boolean yffyjjkcyhmxbUpdate(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;
		}
	}

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

		A107041VO vo = new A107041VO();

		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.getD29_1();
			d29_2 = one.getD29_2();
			d29_3 = one.getD29_3();
			d31 = one.getD31();
			d32 = one.getD32();
		}


		return vo;
	}

	@Override
	public boolean gxjsqyyhqkjmxbUpdate(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;
		}
	}

	@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();

		HighTechYB db = highTechYbMapper.selectOne(Wrappers.<HighTechYB>lambdaQuery().eq(HighTechYB::getYearAndMonth, year));
		if (Func.notNull(db)) {
			vo.setD13(db.getD13());
			vo.setD15(db.getD15());
			vo.setD16(db.getD16());
		}
		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);


		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;
		}
	}

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

		ArchiveAttachEntity attach = attachMapper.selectOne(Wrappers.<ArchiveAttachEntity>lambdaQuery().eq(ArchiveAttachEntity::getYearAndMonth, year));
		if (Func.isNull(attach)) {
			attach = new ArchiveAttachEntity();
		}

		return attach;
	}

	@Override
	public boolean fjbczlUpdate(ArchiveAttachEntity attach) {
		if (Func.isNull(attach.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		if (attach.getYearAndMonth().length() != 4) {
			throw new ServiceException("参数yearAndMonth为年份，如2025");
		}
		LambdaQueryWrapper<ArchiveAttachEntity> eq = Wrappers.<ArchiveAttachEntity>lambdaQuery().eq(ArchiveAttachEntity::getYearAndMonth, attach.getYearAndMonth());
		ArchiveAttachEntity one = attachMapper.selectOne(eq);
		if (Func.isNull(one)) {
			attach.setTenantId(SecureUtil.getTenantId());
			return attachMapper.insert(attach) == 1;
		} else {
			attach.setId(one.getId());
			return attachMapper.updateById(attach) == 1;
		}
	}

}
