
package org.sky.scientific.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
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.tool.utils.Func;
import org.sky.scientific.excel.YsQtfyExcel;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsQtfyMapper;
import org.sky.scientific.pojo.entity.YsQtfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsQtfyVO;
import org.sky.scientific.service.IYsQtfyService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目预算-其他费用 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
@AllArgsConstructor
public class YsQtfyServiceImpl extends BaseServiceImpl<YsQtfyMapper, YsQtfyEntity> implements IYsQtfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsQtfyVO> selectYsQtfyPage(IPage<YsQtfyVO> page, YsQtfyVO ysQtfy) {
		return page.setRecords(baseMapper.selectYsQtfyPage(page, ysQtfy));
	}


	@Override
	public List<YsQtfyExcel> exportYsQtfy(Wrapper<YsQtfyEntity> queryWrapper) {
		List<YsQtfyExcel> ysQtfyList = baseMapper.exportYsQtfy(queryWrapper);
		//ysQtfyList.forEach(ysQtfy -> {
		//	ysQtfy.setTypeName(DictCache.getValue(DictEnum.YES_NO, YsQtfy.getType()));
		//});
		return ysQtfyList;
	}

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

	@Override
	public boolean updateQtfy(YsQtfyEntity ysQtfy) {
		if(ysQtfy.getXmId() == null){
			throw new ServiceException("请选择科研项目");
		}
		return this.updateById(ysQtfy);
	}

    @Override
    public void importQtfy(MultipartFile file, Long xmId) {
		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}
		XmVO xmVO = xmMapper.selectByXmId(xmId);
		if (Func.isNull(xmVO)) {
			throw new ServiceException("研发项目不存在");
		}

		List<YsQtfyExcel> dataList = ExcelUtil.read(file, 0, 3, YsQtfyExcel.class);
		if (Func.isEmpty(dataList)) {
			throw new ServiceException("读取导入数据失败，请检查数据");
		}

		List<YsQtfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (YsQtfyExcel excel : dataList) {

			YsQtfyEntity entity = new YsQtfyEntity();
			entity.setXmId(xmId);
			entity.setFynr(excel.getFynr());
 			entity.setYsje(excel.getYsje());
 			insertList.add(entity);

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

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

}
