
package org.sky.scientific.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
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.CollectionUtil;
import org.sky.core.tool.utils.StringUtil;
import org.sky.scientific.excel.CgKylwExcel;
import org.sky.scientific.mapper.CgKylwMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.CgKylwDTO;
import org.sky.scientific.pojo.entity.CgKylwEntity;
import org.sky.scientific.pojo.entity.XmEntity;
import org.sky.scientific.service.ICgKylwService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
 * 科研成果-科研论文 服务实现类
 *
 * @author Kd
 * @since 2025-06-29
 */
@Service
public class CgKylwServiceImpl extends BaseServiceImpl<CgKylwMapper, CgKylwEntity> implements ICgKylwService {

	@Resource
	private XmMapper xmMapper;


	@Override
	public List<CgKylwExcel> export(Wrapper<CgKylwEntity> queryWrapper) {
		List<CgKylwExcel> cgKylwList = baseMapper.exportCgKylw(queryWrapper);
		return cgKylwList;
	}

	@Transactional
	@SneakyThrows
	@Override
	public void importCgKylw(MultipartFile file) {
		List<CgKylwExcel> data = ExcelUtil.read(file, 0, 2, CgKylwExcel.class);
		if(CollectionUtil.isEmpty(data)){
			throw new ServiceException("未能从模板中读取数据，请检查模板格式是否正确");
		}
		for (CgKylwExcel excel : data) {
			CgKylwEntity kylwDTO = Objects.requireNonNull(BeanUtil.copyProperties(excel, CgKylwDTO.class));
			if (!StringUtil.isAllBlank(excel.getXmbh(), excel.getXmmc())) {
				Long xmId = xmMapper.getXmIdByXmmcOrXmbh(null, excel.getXmmc(), excel.getXmbh());
				if (xmId == null) {
					throw new ServiceException("项目不存在，导入失败，请检查数据");
				}
				kylwDTO.setXmId(xmId);
			}
			this.save(kylwDTO);
		}
	}

	@Override
	public boolean save(CgKylwEntity cgKylw) {

		return super.save(cgKylw);
	}

	@Override
	public boolean update(CgKylwEntity cgKylw) {
		CgKylwEntity dbKylw = this.getById(cgKylw.getId());
		if (!Objects.equals(dbKylw.getXmbh(), cgKylw.getXmbh())) {
			XmEntity dbXm = xmMapper.selectOne(Wrappers.<XmEntity>lambdaQuery().eq(XmEntity::getXmbh, cgKylw.getXmbh()));
			cgKylw.setXmId(dbXm != null ? dbXm.getId() : null);
			cgKylw.setXmmc(dbXm != null ? dbXm.getXmmc() : null);
		}
		return updateById(cgKylw);
	}

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

}
