/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xiaoniu.subsystem.business.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoniu.common.core.exception.ServiceException;
import com.xiaoniu.common.core.utils.DateUtils;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.common.core.utils.bean.BeanValidators;
import com.xiaoniu.subsystem.business.domain.Flight;
import com.xiaoniu.subsystem.business.domain.Project;
import com.xiaoniu.subsystem.business.domain.vo.ProjectVO;
import com.xiaoniu.subsystem.business.mapper.ProjectMapper;
import com.xiaoniu.subsystem.business.service.IFlightService;
import com.xiaoniu.subsystem.business.service.IProjectService;
import com.xiaoniu.subsystem.system.domain.Unit;
import com.xiaoniu.subsystem.system.service.IUnitService;
import jakarta.validation.Validator;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.xiaoniu.common.security.utils.SecurityUtils.getUnitId;
import static com.xiaoniu.common.security.utils.SecurityUtils.getUserId;

/**
 * 培训计划管理表 服务实现类
 *
 * @author sst
 * @since 2024-11-26
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

	protected final IUnitService unitService;
	protected final Validator validator;
	protected final IFlightService flightService;

	public ProjectServiceImpl(IUnitService unitService, Validator validator, IFlightService flightService) {
		this.unitService = unitService;
		this.validator = validator;
		this.flightService = flightService;
	}

	@Override
	public IPage<ProjectVO> selectProjectPage(IPage<ProjectVO> page, ProjectVO project) {
		return page.setRecords(baseMapper.selectProjectPage(page, project));
	}

	@Override
	public String importData(List<Project> list, boolean isUpdateSupport) {
		if (CollectionUtils.isEmpty(list)) {
			throw new ServiceException("导入人员信息确认数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		Map<String, Long> map = new HashMap<String, Long>();
		Map<String, Long> map1 = new HashMap<String, Long>();
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		Unit unit = unitService.getById(getUnitId());
		List<Unit> unitList = unitService.list();
		List<Unit> units =
				unitList.stream().filter(u -> StringUtils.equals("0", u.getType())).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(units)) {
			map.putAll(units.stream().collect(Collectors.toMap(Unit::getUnitName, Unit::getUnitId)));
		}
		List<Unit> units1 =
				unitList.stream().filter(u -> StringUtils.equals("1", u.getType())).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(units1)) {
			map1.putAll(units1.stream().collect(Collectors.toMap(Unit::getUnitName, Unit::getUnitId)));
		}
		for (Project d : list) {
			try {
				//查询班次是否存在
				Flight flight = flightService.getOne(new LambdaQueryWrapper<Flight>()
						.eq(Flight::getFlightName,d.getFlightName())
						.eq(Flight::getYear,d.getYear())
						.eq(Flight::getTrainingTime,d.getTrainingTime())
				);
				if (flight != null){
					d.setFlightId(flight.getFlightId());
				}

				//根据承训单位名称查询送训单位信息
				Unit unit1 = unitService.getUnitByName(d.getTrainingUnitName());
				if (unit1 != null){
					d.setTrainingUnitId(unit1.getUnitId());
				}
				// 验证是否存在这个数据
				Project u = baseMapper.selectOne(new LambdaQueryWrapper<Project>()
						.eq(Project::getFlightName, d.getFlightName())
						.eq(Project::getTrainingTime, d.getTrainingTime())
						.eq(Project::getParentId, 0)
						.eq(Project::getYear, d.getYear()));
				if (StringUtils.isNull(u)) {
					BeanValidators.validateWithException(validator, d);
					d.setCreateUser(getUserId());
					d.setCreateUser(getUserId());
					d.setCreateDept(unit.getUnitId());
					d.setCreateTime(new Date());
					this.save(d);
					successNum++;
					successMsg.append("<br/>" + successNum +"、" + d.getYear() +
							"度,开训时间：" + DateUtils.dateTime(d.getTrainingTime()) +
							",专业（班次）名称：" + d.getFlightName() + "的计划 "+"导入成功");
				} else if (isUpdateSupport) {
					BeanValidators.validateWithException(validator, d);
					d.setUpdateUser(getUserId());
					d.setUpdateTime(new Date());
					this.updateById(d);
					successNum++;
					successMsg.append("<br/>" + successNum + "、" +d.getYear() +
							"度,开训时间：" + DateUtils.dateTime(d.getTrainingTime()) +
							",专业（班次）名称：" + d.getFlightName() + "的计划 " +  "更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、" + d.getYear() +
							"度,开训时间：" + DateUtils.dateTime(d.getTrainingTime()) +
							",专业（班次）名称：" + d.getFlightName() + "的计划 " + "已存在");
				}
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum +  " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new ServiceException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();

	}

}
