
package org.sky.scientific.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.mp.base.BaseServiceImpl;
import org.sky.core.mp.support.Condition;
import org.sky.core.mp.support.Query;
import org.sky.core.tool.utils.BeanUtil;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.e.AssetStatusEnum;
import org.sky.scientific.excel.YsZjfyycqdtfyExcel;
import org.sky.scientific.excel.listener.YsZjfyycqdtfyImportListener;
import org.sky.scientific.mapper.AssetMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsZjfyycqdtfyMapper;
import org.sky.scientific.pojo.entity.AssetEntity;
import org.sky.scientific.pojo.entity.YsZjfyycqdtfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsZjfyycqdtfyVO;
import org.sky.scientific.service.IYsZjfyycqdtfyService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目预算-折旧费用与长期待摊费用 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
@AllArgsConstructor
public class YsZjfyycqdtfyServiceImpl extends BaseServiceImpl<YsZjfyycqdtfyMapper, YsZjfyycqdtfyEntity> implements IYsZjfyycqdtfyService {

	private final XmMapper xmMapper;
	private final AssetMapper assetMapper;

	@Override
	public IPage<YsZjfyycqdtfyVO> selectPageByXmId(IPage<YsZjfyycqdtfyVO> page, Long xmId) {
		return page.setRecords(baseMapper.selectPageByXmId(page, xmId));
	}

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

	@Override
	public boolean submit(YsZjfyycqdtfyEntity entity) {
		if(entity.getXmId() == null){
			throw new ServiceException("请选择科研项目");
		}

		XmVO xmVO = xmMapper.selectByXmId(entity.getXmId());
		if(Func.isNull(xmVO)){
			throw new ServiceException("研发项目不存在");
		}
		judgeZzsc(xmVO, entity.getZzsc());

		AssetEntity dbAsset = assetMapper.selectById(entity.getAssetId());
		if(Func.isNull(dbAsset)){
			throw new ServiceException("资产不存在");
		}
		if(!Func.equals(AssetStatusEnum.正常.getCode(),dbAsset.getStatus())){
			throw new ServiceException("资产状态非正常");
		}
		if(entity.getCqdtfyysje()!=null){
			entity.setCqdtfyysje(entity.getCqdtfyysje().multiply(BigDecimal.valueOf(10000)));
		}
		List<YsZjfyycqdtfyEntity> dbList = baseMapper.selectList(Wrappers.<YsZjfyycqdtfyEntity>lambdaQuery().eq(YsZjfyycqdtfyEntity::getXmId, entity.getXmId()));
		if(Func.isEmpty(dbList)){
			return this.saveOrUpdate( entity);
		}

		if(entity.getId() == null){
			//新增
			List<Long> dbAssetIdList = dbList.stream().map(YsZjfyycqdtfyEntity::getAssetId).toList();
			if(dbAssetIdList.contains(entity.getAssetId())){
				throw new ServiceException("资产已在预算表中");
			}
		}else {
			//修改
			Optional<YsZjfyycqdtfyEntity> optional = dbList.stream().filter(tmp -> (Func.equals(tmp.getAssetId(), entity.getAssetId()))).findFirst();
			if(optional.isPresent()){
				YsZjfyycqdtfyEntity byAssetId = optional.get();
				if(!Func.equals(byAssetId.getId(), entity.getId())){
					throw new ServiceException("资产已在预算表中");
				}
			}
		}
		return this.saveOrUpdate(entity);
	}

	@SneakyThrows
	@Override
	public void importZjfyycqdtfy(MultipartFile file, Long xmId) {
		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}
		XmVO xmVO = xmMapper.selectByXmId(xmId);
		if (Func.isNull(xmVO)) {
			throw new ServiceException("研发项目不存在");
		}
		YsZjfyycqdtfyImportListener listener = new YsZjfyycqdtfyImportListener();
		EasyExcel.read(new BufferedInputStream(file.getInputStream()))
			.registerReadListener(listener)
			.sheet(0)
			.headRowNumber(3) // 重要：设置表头行数(0-based)
			.doRead();
		List<Object> dataList = listener.getDataList();
 		if(Func.isEmpty(dataList)){
			throw new ServiceException("未能读取到数据，请检查");
		}

		//查询项目开始时间对应月份的资产清单
		List<AssetEntity> dbAssetList = assetMapper.selectList(Wrappers.<AssetEntity>lambdaQuery().eq(AssetEntity::getYearAndMonth, DateUtil.format(xmVO.getXmkssj(), DateUtil.PATTERN_YYYYMM)));

		if (Func.isEmpty(dbAssetList)) {
			throw new ServiceException(xmVO.getXmkssj() + "资产清单无数据");
		}

		List<YsZjfyycqdtfyEntity> dbYsList = baseMapper.selectList(Wrappers.<YsZjfyycqdtfyEntity>lambdaQuery().eq(YsZjfyycqdtfyEntity::getXmId, xmId));

		List<YsZjfyycqdtfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (Object o : dataList) {
			YsZjfyycqdtfyExcel excel = (YsZjfyycqdtfyExcel) o;
			if(Func.isBlank(excel.getZcmc())){
				throw new ServiceException("序号["+excel.getXh()+"]的资产名称为空");
			}

			judgeZzsc(xmVO, excel.getZzsc());

			YsZjfyycqdtfyEntity entity = new YsZjfyycqdtfyEntity();
			entity.setXmId(xmId);

			List<AssetEntity> list = dbAssetList.stream()
				.filter(asset -> Func.equals(asset.getZcmc(), excel.getZcmc()))
				.toList();
			if (Func.isEmpty(list)) {
				throw new ServiceException("资产[" + excel.getZcmc() + "]不存在");
			}

			AssetEntity dbAsset = list.get(0);

			if(!AssetServiceImpl.isFixedAsset(dbAsset.getZclb())){
				throw new ServiceException("只能导入仪器设备/房屋建筑物，请检查模板数据");
			}

			Long assetId = dbAsset.getId();

			if(dbYsList.stream().anyMatch(ys -> Func.equals(ys.getAssetId(), assetId))){
				throw new ServiceException("序号["+excel.getXh()+"]的资产已在预算表中");
			}

			//todo 判断资产状态是否正常
			Optional<Integer> any = dbAssetList.stream()
				.filter(asset -> Func.equals(asset.getZcmc(), excel.getZcmc()))
				.map(AssetEntity::getStatus).findAny();
			if(any.isPresent()){
				Integer assetStatus = any.get();
				if(!Func.equals(assetStatus, AssetStatusEnum.正常.getCode())){
					continue;
				}
			}

			BeanUtil.copyProperties(excel, entity);
			entity.setAssetId(assetId);

			insertList.add(entity);

			if (insertList.size() % batchCount == 0 && this.saveBatch(insertList)) {
				insertList.clear();
			}
		}

		if (Func.isNotEmpty(insertList)) {
			this.saveBatch(insertList);
		}
	}

    @SneakyThrows
	@Override
    public void exportYsZjfyycqdtfy(OutputStream os, YsZjfyycqdtfyVO dto) {
		List<YsZjfyycqdtfyVO> list = this.selectPageByXmId(Condition.getPage(new Query().setCurrent(1).setSize(Integer.MAX_VALUE)), dto.getXmId()).getRecords();
		AtomicInteger index = new AtomicInteger(1);

		for (YsZjfyycqdtfyVO temp : list) {
			temp.setXh(index.getAndIncrement() + "");
			if(temp.getYzje()!=null){
				temp.setYzje(temp.getYzje().divide(BigDecimal.valueOf(10000), 4, RoundingMode.UP));
			}
			temp.setZichanTotal(BigDecimal.valueOf(temp.getZzsc()).multiply(temp.getYzje()));
			if(temp.getCqdtfyysje()!=null){
				temp.setCqdtfyysje(temp.getCqdtfyysje().divide(BigDecimal.valueOf(10000), 4, RoundingMode.UP));
			}
		}
		InputStream templateFileName = this.getClass().getClassLoader().getResourceAsStream("export-template/研发项目管理/预算编制/折旧费用与长期待摊费用.xls");
		ExcelWriter excelWriter = EasyExcel.write(os)
			.withTemplate((templateFileName))
			.excelType(ExcelTypeEnum.XLS)
			.build();
		WriteSheet writeSheet = EasyExcel.writerSheet().build();
		FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
		//设置list集合数据
		excelWriter.fill(list, fillConfig, writeSheet);
		Map<String, Object> map = new HashMap<>();
		JSONObject xm = xmMapper.getXmmcAndXmbhByXmId(dto.getXmId());
		map.put("xmmc", Func.notNull(xm)?xm.getString("xmmc"): "");
		map.put("xmbh", Func.notNull(xm)?xm.getString("xmbh"): "");
		excelWriter.fill(map, writeSheet);
		excelWriter.finish();
		if (templateFileName != null) {
			templateFileName.close();
		}
    }

	private void judgeZzsc(XmVO xmVO, Integer zzsc){
		long betweenMonth = cn.hutool.core.date.DateUtil.betweenMonth(xmVO.getXmkssj(), xmVO.getXmjssj(), true) + 1;
		if(betweenMonth < zzsc){
			throw new ServiceException("工作时长不能大于研发项目【"+xmVO.getXmbh()+"】的周期【" + betweenMonth +"】个月");
		}
	}

}
