
package org.sky.scientific.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.sky.core.excel.util.ExcelUtil;
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.CollectionUtil;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.core.tool.utils.StringUtil;
import org.sky.scientific.excel.XmFixedAssetExcel;
import org.sky.scientific.mapper.AssetMapper;
import org.sky.scientific.mapper.XmIntangibleAssetMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsWxzctxfyMapper;
import org.sky.scientific.pojo.dto.XmAssetQueryParam;
import org.sky.scientific.pojo.entity.AssetEntity;
import org.sky.scientific.pojo.entity.XmIntangibleAsset;
import org.sky.scientific.pojo.vo.XmIntangibleAssetCostVo;
import org.sky.scientific.pojo.vo.YsWxzctxfyVO;
import org.sky.scientific.service.IXmIntangibleAssetService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 研发项目无形资产表 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Slf4j
@Service
public class XmIntangibleAssetServiceImpl extends BaseServiceImpl<XmIntangibleAssetMapper, XmIntangibleAsset> implements IXmIntangibleAssetService {

	@Resource
	private YsWxzctxfyMapper ysWxzctxfyMapper;
	@Resource
	private XmMapper xmMapper;
	@Resource
	private AssetMapper assetMapper;

	@Override
	public IPage<XmIntangibleAsset> selectPage(IPage<XmIntangibleAsset> page, XmAssetQueryParam param) {
		if (StringUtil.isBlank(param.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		List<XmIntangibleAsset> list = null;
		if (param.getYearAndMonth().length() == 4) {
			//全年
			list = baseMapper.selectPageByYear(page, param);
		} else {
			//按月
			list = baseMapper.selectPageByYearAndMonth(page, param);
		}

		return page.setRecords(list);
	}

	@Override
	public boolean zhijieyinyong(String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		//获取本月数据
		List<XmIntangibleAsset> thisMonthList = baseMapper.selectListByYearAndMonth(yearAndMonth);
//		if(Func.isNotEmpty(thisMonthList)){
//			throw new ServiceException("");
//		}
		Date lastDate = DateUtil.minusMonths(DateUtil.parse(yearAndMonth, DateUtil.PATTERN_YYYYMM), 1);
		//获取上个月数据
		List<XmIntangibleAsset> lastMonthList = baseMapper.selectListByYearAndMonth(DateUtil.format(lastDate, DateUtil.PATTERN_YYYYMM));

		List<String> zcbmList = thisMonthList.stream().map(XmIntangibleAsset::getZcbm).toList();
		Map<Long, List<XmIntangibleAsset>> c1 = thisMonthList.stream().collect(Collectors.groupingBy(XmIntangibleAsset::getXmId));

		if (!CollectionUtil.isEmpty(lastMonthList)) {
			//复制上个月数据到本月
			List<XmIntangibleAsset> insertList = new ArrayList<>();
			for (XmIntangibleAsset dbAsset : lastMonthList) {
				//本月为包含dbAsset，新增
//				if (!Func.contains(new List[]{zcbmList}, dbAsset.getZcbm())) {
				if(Func.isNotEmpty(c1.get(dbAsset.getXmId())) && c1.get(dbAsset.getXmId()).stream().anyMatch(item -> Func.equals(item.getZcbm(), dbAsset.getZcbm()))){
					continue;
				}
//				if (!Func.contains(new List[]{zcbmList}, dbAsset.getZcbm())) {
					XmIntangibleAsset asset = new XmIntangibleAsset();
					asset.setYearAndMonth(yearAndMonth);
					asset.setXmId(dbAsset.getXmId());
					asset.setAssetId(dbAsset.getAssetId());
					asset.setZcbm(dbAsset.getZcbm());
					insertList.add(asset);
//				}
			}
			if (CollectionUtil.isNotEmpty(insertList)) {
				return this.saveBatch(insertList);
			}else {
				throw new ServiceException("无数据可引入");
			}
		} else {
			//若无，则获取预算表中的无形资产，研发项目周期（含变更）包含本月的
			List<YsWxzctxfyVO> ysList = ysWxzctxfyMapper.selectByYearAndMonth(yearAndMonth);
			if (CollectionUtil.isEmpty(ysList)) {
				throw new ServiceException("项目预算表中没有无形资产");
			}
			List<XmIntangibleAsset> insertList = new ArrayList<>();
			for (YsWxzctxfyVO ys : ysList) {
//				if (CollectionUtil.isNotEmpty(zcbmList) && zcbmList.contains(ys.getZcbm())) {
//					continue;
//				}
				if(Func.isNotEmpty(c1.get(ys.getXmId())) && c1.get(ys.getXmId()).stream().anyMatch(item -> Func.equals(item.getZcbm(), ys.getZcbm()))){
					continue;
				}
				XmIntangibleAsset asset = new XmIntangibleAsset();
				asset.setYearAndMonth(yearAndMonth);
				asset.setXmId(ys.getXmId());
				asset.setZcbm(ys.getZcbm());
				asset.setAssetId(ys.getZcEntity().getId());
 				insertList.add(asset);
			}
			if (CollectionUtil.isNotEmpty(insertList)) {
				return this.saveBatch(insertList);
			}else {
				throw new ServiceException("无数据可引入");
			}
		}
	}

	@Override
	public void xmIntangibleAssetImport(MultipartFile file, String yearAndMonth) {
		if (StringUtil.isBlank(yearAndMonth)) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		List<XmFixedAssetExcel> data = ExcelUtil.read(file, XmFixedAssetExcel.class);
		if (CollectionUtil.isEmpty(data)) {
			throw new ServiceException("导入数据为空");
		}
		//获取本月数据
		List<XmIntangibleAsset> thisMonthList = baseMapper.selectListByYearAndMonth(yearAndMonth);
		List<String> zcbmList = thisMonthList.stream().map(XmIntangibleAsset::getZcbm).toList();

		List<XmIntangibleAsset> insertList = new ArrayList<>();
		Map<String, Long> xmIdMap = new HashMap<>();
		Map<String, AssetEntity> assetIdMap = new HashMap<>();
		for (XmFixedAssetExcel excel : data) {

			if (Func.contains(new List[]{zcbmList}, excel.getZcbm())) {
				continue;
			}
			if (StringUtil.isAllBlank(excel.getXmmc(), excel.getXmbh())) {
				throw new ServiceException("序号为[" + excel.getXh() + "]的项目研发编号和项目研发名称都为空");
			}
			String xmkey = "xm:" + excel.getXmbh() + ":" + excel.getXmmc();
			Long xmId = xmIdMap.get(xmkey);
			if(xmId == null){
				xmId = xmMapper.getXmIdByXmmcOrXmbh(yearAndMonth, excel.getXmmc(), excel.getXmbh());
				if (xmId == null) {
					throw new ServiceException("序号为[" + excel.getXh() + "]的项目不存在");
				}
			}
			xmIdMap.put(xmkey, xmId);

			if (StringUtil.isAllBlank(excel.getXmmc(), excel.getXmbh())) {
				throw new ServiceException("序号为[" + excel.getXh() + "]的资产编码和资产名称都为空");
			}

			String assetkey = "asset:" + excel.getZcbm() + ":" + excel.getZcmc();
			AssetEntity dbAsset = assetIdMap.get(assetkey);
			if(dbAsset == null){
				dbAsset = assetMapper.selectByYearAndMonthAndBmOrMc(yearAndMonth, excel.getZcbm(), excel.getZcmc());
				if (dbAsset == null) {
					throw new ServiceException("序号为[" + excel.getXh() + "]的资产不存在");
				}
			}
			assetIdMap.put(assetkey, dbAsset);

			XmIntangibleAsset xmAsset = new XmIntangibleAsset();
			xmAsset.setYearAndMonth(yearAndMonth);
			xmAsset.setXmId(xmId);
			xmAsset.setAssetId(dbAsset.getId());
			xmAsset.setZcbm(dbAsset.getZcbm());
			insertList.add(xmAsset);
		}
		if (CollectionUtil.isEmpty(insertList)) {
			throw new ServiceException("数据已存在，导入失败");
		} else {
			this.saveBatch(insertList);
		}
	}

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

	@Override
	public boolean saveXmIntangibleAsset(XmIntangibleAsset xmAsset) {
		if (StringUtil.isBlank(xmAsset.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		//获取本月数据
		List<XmIntangibleAsset> thisMonthList = baseMapper.selectListByYearAndMonth(xmAsset.getYearAndMonth());
		List<String> zcbmList = thisMonthList.stream().map(XmIntangibleAsset::getZcbm).toList();

		if (CollectionUtil.isNotEmpty(zcbmList) && zcbmList.contains(xmAsset.getZcbm())) {
			throw new ServiceException("资产已配置到项目中");
		}
		return this.save(xmAsset);
	}

	@Override
	public boolean updateXmIntangibleAsset(XmIntangibleAsset xmAsset) {
		if(null == xmAsset.getId()){
			throw new ServiceException("参数id不能为空");
		}
		return this.updateById(xmAsset);
	}

    @Override
    public IPage<XmIntangibleAssetCostVo> keyanwuxingzichantanxiaofeiyongfenpeibiao(IPage<XmIntangibleAssetCostVo> page, XmAssetQueryParam dto) {

		if (StringUtil.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		dto.setTenantId(SecureUtil.getTenantId());
		List<XmIntangibleAssetCostVo> list = baseMapper.keyanwuxingzichantanxiaofeiyongfenpeibiao(page,dto);
		for (XmIntangibleAssetCostVo vo : list) {
			//研发分摊率=月研发工时/月总工时
			if(vo.getAttendanceHours()==0 || vo.getWorkHours()==0){
				vo.setYanfaFenTanLv(0);
			}else {
				vo.setYanfaFenTanLv(vo.getWorkHours() / vo.getAttendanceHours());
			}
			//研发摊销=(月折旧额/月摊销额（元）) * 研发分摊率
			vo.setYanfaTanXiao(vo.getAsset().getYzje().doubleValue() * vo.getYanfaFenTanLv());
		}
        return page.setRecords(list);
    }
}
