
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.XmFixedAssetMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsZjfyycqdtfyMapper;
import org.sky.scientific.pojo.dto.XmAssetQueryParam;
import org.sky.scientific.pojo.entity.AssetEntity;
import org.sky.scientific.pojo.entity.XmFixedAsset;
import org.sky.scientific.pojo.entity.YsZjfyycqdtfyEntity;
import org.sky.scientific.pojo.vo.XmFixedAssetCostVo;
import org.sky.scientific.service.IXmFixedAssetService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 研发项目固定资产表 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Slf4j
@Service
public class XmFixedAssetServiceImpl extends BaseServiceImpl<XmFixedAssetMapper, XmFixedAsset> implements IXmFixedAssetService {

	@Resource
	private YsZjfyycqdtfyMapper ysZjfyycqdtfyMapper;
	@Resource
	private XmMapper xmMapper;
	@Resource
	private AssetMapper assetMapper;

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

		return page.setRecords(list);
	}

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

		List<String> zcbmList = thisMonthList.stream().map(XmFixedAsset::getZcbm).toList();
		if (!CollectionUtil.isEmpty(lastMonthList)) {
			//复制上个月数据到本月
			List<XmFixedAsset> insertList = new ArrayList<>();
			for (XmFixedAsset dbAsset : lastMonthList) {
				//dbAsset已存在，则跳过
				if (CollectionUtil.isNotEmpty(zcbmList) && zcbmList.contains(dbAsset.getZcbm())) {
					continue;
				}
				XmFixedAsset asset = new XmFixedAsset();
				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 {
			//若无，则获取预算表中的科研仪器设备，研发项目周期（含变更）包含本月的
			List<YsZjfyycqdtfyEntity> ysList = ysZjfyycqdtfyMapper.selectByYearAndMonth(yearAndMonth, zclb);
			if (CollectionUtil.isEmpty(ysList)) {
				throw new ServiceException("项目预算表中无科研仪器设备");
			}
			List<XmFixedAsset> insertList = new ArrayList<>();
			for (YsZjfyycqdtfyEntity ys : ysList) {
				if (CollectionUtil.isNotEmpty(zcbmList) && zcbmList.contains(ys.getZcbm())) {
					continue;
				}
				XmFixedAsset asset = new XmFixedAsset();
				asset.setYearAndMonth(yearAndMonth);
				asset.setXmId(ys.getXmId());
				asset.setAssetId(ys.getAssetId());
				asset.setZcbm(ys.getZcbm());
				insertList.add(asset);
			}
			if (CollectionUtil.isNotEmpty(insertList)) {
				return this.saveBatch(insertList);
			}
		}
		return true;
	}

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

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

		List<XmFixedAsset> insertList = new ArrayList<>();
		Map<String, Long> xmIdMap = new HashMap<>();
		Map<String, AssetEntity> assetIdMap = new HashMap<>();
		for (XmFixedAssetExcel excel : data) {
			if (CollectionUtil.isNotEmpty(zcbmList) && zcbmList.contains(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.getZcmc(), excel.getZcbm());
				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);

			XmFixedAsset xmAsset = new XmFixedAsset();
			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 saveXmFixedAsset(XmFixedAsset xmAsset, String zclb) {
		if (StringUtil.isBlank(xmAsset.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		//获取本月数据
		List<XmFixedAsset> thisMonthList = baseMapper.selectXmFixedAssetByYearAndMonth(xmAsset.getYearAndMonth(), zclb);

		long count = thisMonthList.stream().filter(e -> Objects.equals(e.getXmId(), xmAsset.getXmId()) && Objects.equals(e.getZcbm(), xmAsset.getZcbm())).count();

		if (count > 0) {
			throw new ServiceException("资产已配置到项目中");
		}
		return this.save(xmAsset);
	}

	@Override
	public IPage<XmFixedAssetCostVo> keyanyiqishebeizhejiufeiyongfenpeibiao(IPage<XmFixedAssetCostVo> page, XmAssetQueryParam dto) {
		if (StringUtil.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		dto.setTenantId(SecureUtil.getTenantId());
		List<XmFixedAssetCostVo> list = baseMapper.keyanyiqishebeizhejiufeiyongfenpeibiao(page, dto);
//		for (XmFixedAssetCostVo vo : list) {
//			//研发分摊率=月研发工时/月总工时
//			vo.setYanfaFenTanLv(CommonUtil.divide(vo.getWorkHours(), vo.getAsset().getZgs()));
//			//研发摊销=(月折旧额或月摊销额（元）) * 研发分摊率
//			vo.setYanfaTanXiao(CommonUtil.multiply(vo.getWorkHours(), 1.0 / vo.getAsset().getZgs()));
//		}
		return page.setRecords(list);
	}

	@Override
	public IPage<XmFixedAssetCostVo> keyanfangwujianzhuwuzhejiufeiyongfenpeibiao(IPage<XmFixedAssetCostVo> page, XmAssetQueryParam dto) {
		if (StringUtil.isBlank(dto.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		dto.setTenantId(SecureUtil.getTenantId());
		List<XmFixedAssetCostVo> list = baseMapper.keyanfangwujianzhuwuzhejiufeiyongfenpeibiao(page, dto);

		return page.setRecords(list);
	}

	@Override
	public boolean keyanfangwujianzhuwuzhejiufeiyongfenpeibiaoEdit(XmFixedAssetCostVo dto) {
		if (Func.isNull(dto.getId())) {
			throw new ServiceException("id不能为空");
		}
		if(Func.notNull(dto.getYanfaFenTanLv()) && (dto.getYanfaFenTanLv() <0||dto.getYanfaFenTanLv()>1.0)){
			throw new ServiceException("研发分摊率只能是[0,1]之间");
		}
		XmFixedAsset fixedAsset = new XmFixedAsset();
		fixedAsset.setId(dto.getId());
		fixedAsset.setYanfaFenTanLv(dto.getYanfaFenTanLv());
		fixedAsset.setFenTanLvQueDingYiJu(dto.getFenTanLvQueDingYiJu());
		return baseMapper.updateById(fixedAsset) == 1;
	}
}
