
package org.sky.scientific.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.secure.utils.SecureUtil;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.mapper.DepartmentMapper;
import org.sky.scientific.pojo.entity.DepartmentEntity;
import org.sky.scientific.service.IDepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 二级单位/部门 服务类 服务实现类
 *
 * @author Kd
 * @since 2025-08-14
 */
@Service
@AllArgsConstructor
public class DepartmentServiceImpl  implements IDepartmentService {

	private final DepartmentMapper mapper;
	@Override
	@Transactional
	public Boolean fetchLastYearData(DepartmentEntity department) {
		if (Func.isBlank(department.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}
		String lastYear = DateUtil.format(DateUtil.minusYears(DateUtil.parse(department.getYearAndMonth(), DateUtil.PATTERN_YYYY), 1), DateUtil.PATTERN_YYYY);
		LambdaQueryWrapper<DepartmentEntity> eq = Wrappers.<DepartmentEntity>lambdaQuery()
			.eq(DepartmentEntity::getYearAndMonth, lastYear);
		List<DepartmentEntity> list = mapper.selectList(eq);
		if (Func.isEmpty(list)) {
			throw new ServiceException("上年度没有数据");
		}

		//管他有没有，先清除本年度数据
		mapper.deleteByYearAndTenantId(department.getYearAndMonth(), SecureUtil.getTenantId());

		List<DepartmentEntity> parentList = list.stream().filter(item -> Func.equals(item.getParentId(), 0L)).toList();
		for (DepartmentEntity parent : parentList) {
			Long oldParentId = parent.getId();
			parent.setId(null);
			parent.setYearAndMonth(department.getYearAndMonth());
			mapper.insert(parent);

			List<DepartmentEntity> tmpList = list.stream().filter(item -> Func.equals(item.getParentId(), oldParentId)).toList();
			for (DepartmentEntity entity : tmpList) {
				entity.setId(null);
				entity.setParentId(parent.getId());
				entity.setYearAndMonth(department.getYearAndMonth());
				mapper.insert(entity);
			}
		}
		return true;
	}

	@Override
	public boolean submit(DepartmentEntity department) {
		if (Func.isBlank(department.getYearAndMonth())) {
			throw new ServiceException("参数yearAndMonth不能为空");
		}

		LambdaQueryWrapper<DepartmentEntity> wrapper = Wrappers.<DepartmentEntity>lambdaQuery()
			.eq(DepartmentEntity::getName, department.getName())
			.eq(DepartmentEntity::getYearAndMonth, department.getYearAndMonth());
		DepartmentEntity dbEntity = mapper.selectOne(wrapper);
		if (department.getId() == null) {
			//新增
			if (dbEntity != null) {
				throw new ServiceException("名称[" + department.getName() + "]已存在");
			}
			return mapper.insert(department) == 1;
		} else {
			//修改
			if (dbEntity!=null && Func.equals(department.getName(), dbEntity.getName()) && !Func.equals(dbEntity.getId(), department.getId())) {
				throw new ServiceException("名称[" + department.getName() + "]已存在");
			}
			return mapper.updateById(department) == 1;
		}
	}

	@Override
	public List<DepartmentEntity> selectDepartmentList(String yearAndMonth) {
		return mapper.selectList(Wrappers.<DepartmentEntity>lambdaQuery()
			.eq(DepartmentEntity::getYearAndMonth, yearAndMonth));
	}

	@Override
	public boolean deleteByIds(List<Long> ids) {
		for (Long id : ids) {
			Long count = mapper.selectCount(Wrappers.<DepartmentEntity>lambdaQuery().eq(DepartmentEntity::getParentId, id));
			if (count > 0) {
				throw new ServiceException("请先删除下级部门");
			}
		}
		return  mapper.deleteByIds(ids) > 0;
	}
}
