
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.CgZlExcel;
import org.sky.scientific.mapper.CgZlMapper;
import org.sky.scientific.mapper.XmMapper;
import org.sky.scientific.pojo.dto.CgZlDTO;
import org.sky.scientific.pojo.entity.CgZlEntity;
import org.sky.scientific.pojo.entity.XmEntity;
import org.sky.scientific.service.ICgZlService;
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 CgZlServiceImpl extends BaseServiceImpl<CgZlMapper, CgZlEntity> implements ICgZlService {

	@Resource
	private XmMapper xmMapper;

	@Override
	public List<CgZlExcel> export(Wrapper<CgZlEntity> queryWrapper) {
		List<CgZlExcel> cgZlList = baseMapper.exportCgZl(queryWrapper);
		//cgZlList.forEach(cgZl -> {
		//	cgZl.setTypeName(DictCache.getValue(DictEnum.YES_NO, CgZl.getType()));
		//});
		return cgZlList;
	}

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

	@Override
	public boolean save(CgZlEntity cgZl) {
		return super.save(cgZl);
	}

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

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

}
