
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.BeanUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.excel.YsZjtrfyExcel;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.mapper.YsZjtrfyMapper;
import org.sky.scientific.pojo.entity.YsZjtrfyEntity;
import org.sky.scientific.pojo.vo.XmVO;
import org.sky.scientific.pojo.vo.YsZjtrfyVO;
import org.sky.scientific.service.IYsZjtrfyService;
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 YsZjtrfyServiceImpl extends BaseServiceImpl<YsZjtrfyMapper, YsZjtrfyEntity> implements IYsZjtrfyService {

	private final XmMapper xmMapper;

	@Override
	public IPage<YsZjtrfyVO> selectYsZjtrfyPage(IPage<YsZjtrfyVO> page, YsZjtrfyVO ysZjtrfy) {
		return page.setRecords(baseMapper.selectYsZjtrfyPage(page, ysZjtrfy));
	}


	@Override
	public List<YsZjtrfyExcel> exportYsZjtrfy(Wrapper<YsZjtrfyEntity> queryWrapper) {
		List<YsZjtrfyExcel> ysZjtrfyList = baseMapper.exportYsZjtrfy(queryWrapper);
		//ysZjtrfyList.forEach(ysZjtrfy -> {
		//	ysZjtrfy.setTypeName(DictCache.getValue(DictEnum.YES_NO, YsZjtrfy.getType()));
		//});
		return ysZjtrfyList;
	}

    @Override
    public boolean saveZjtrfy(YsZjtrfyEntity ysZjtrfy) {
		// 检查物资名称是否重复
		if(this.isFieldDuplicate(YsZjtrfyEntity::getWzmc, ysZjtrfy.getWzmc())){
			throw new ServiceException("物资名称已存在");
		}
		return this.save(ysZjtrfy);
    }

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

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

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

		List<YsZjtrfyExcel> dataList = ExcelUtil.read(file, 0, 3, YsZjtrfyExcel.class);

		List<YsZjtrfyEntity> insertList = new ArrayList<>();
		int batchCount = 20;
		for (YsZjtrfyExcel excel : dataList) {
			YsZjtrfyEntity entity = new YsZjtrfyEntity();
			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);
		}
	}
}
