
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.YsSjfyExcel;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsSjfyMapper;
import org.sky.scientific.pojo.entity.YsSjfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsSjfyVO;
import org.sky.scientific.service.IYsSjfyService;
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 YsSjfyServiceImpl extends BaseServiceImpl<YsSjfyMapper, YsSjfyEntity> implements IYsSjfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsSjfyVO> selectYsSjfyPage(IPage<YsSjfyVO> page, YsSjfyVO ysSjfy) {
		return page.setRecords(baseMapper.selectYsSjfyPage(page, ysSjfy));
	}

	@Override
	public List<YsSjfyExcel> exportYsSjfy(Wrapper<YsSjfyEntity> queryWrapper) {
		List<YsSjfyExcel> ysSjfyList = baseMapper.exportYsSjfy(queryWrapper);
		//ysSjfyList.forEach(ysSjfy -> {
		//	ysSjfy.setTypeName(DictCache.getValue(DictEnum.YES_NO, YsSjfy.getType()));
		//});
		return ysSjfyList;
	}

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

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

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


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

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

			YsSjfyEntity entity = new YsSjfyEntity();
			entity.setXmId(xmId);
			entity.setSjnr(excel.getSjnr());
			entity.setYsje(excel.getYsje());

			insertList.add(entity);

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

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

}
