
package org.sky.scientific.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.BeanUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.excel.YsWtwbyjkffyExcel;
import org.sky.scientific.mapper.YsWtwbyjkffyMapper;
import org.sky.scientific.pojo.entity.YsWtwbyjkffyEntity;
import org.sky.scientific.pojo.vo.YsWtwbyjkffyVO;
import org.sky.scientific.service.IYsWtwbyjkffyService;
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
public class YsWtwbyjkffyServiceImpl extends BaseServiceImpl<YsWtwbyjkffyMapper, YsWtwbyjkffyEntity> implements IYsWtwbyjkffyService {

	@Override
	public IPage<YsWtwbyjkffyVO> selectYsWtwbyjkffyPage(IPage<YsWtwbyjkffyVO> page, YsWtwbyjkffyVO ysWtwbyjkffy) {
		return page.setRecords(baseMapper.selectYsWtwbyjkffyPage(page, ysWtwbyjkffy));
	}


	@Override
	public List<YsWtwbyjkffyExcel> exportYsWtwbyjkffy(Wrapper<YsWtwbyjkffyEntity> queryWrapper) {
		List<YsWtwbyjkffyExcel> ysWtwbyjkffyList = baseMapper.exportYsWtwbyjkffy(queryWrapper);
		//ysWtwbyjkffyList.forEach(ysWtwbyjkffy -> {
		//	ysWtwbyjkffy.setTypeName(DictCache.getValue(DictEnum.YES_NO, YsWtwbyjkffy.getType()));
		//});
		return ysWtwbyjkffyList;
	}

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

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

	@Override
	public void importWtwbyjkffy(MultipartFile file, Long xmId) {
		if (Func.isNull(xmId)) {
			throw new ServiceException("请选择研发项目");
		}

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

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

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

			BeanUtil.copyProperties(excel, entity);
 			insertList.add(entity);

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

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

}
