
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 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.CgJsbzExcel;
import org.sky.scientific.mapper.CgJsbzMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.CgJsbzDTO;
import org.sky.scientific.pojo.entity.CgJsbzEntity;
import org.sky.scientific.pojo.entity.XmEntity;
import org.sky.scientific.service.ICgJsbzService;
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 CgJsbzServiceImpl extends BaseServiceImpl<CgJsbzMapper, CgJsbzEntity> implements ICgJsbzService {

	@Resource
	private XmMapper xmMapper;

	@Override
	public List<CgJsbzExcel> export(Wrapper<CgJsbzEntity> queryWrapper) {
		List<CgJsbzExcel> cgJsbzList = baseMapper.exportCgJsbz(queryWrapper);
		return cgJsbzList;
	}

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

	@Override
	public boolean save(CgJsbzEntity cgJsbz) {

		return super.save(cgJsbz);
	}

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

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