package com.xiaoniu.subsystem.business.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.Demand;
import com.xiaoniu.subsystem.business.domain.ExamQuestion;
import com.xiaoniu.subsystem.business.domain.Flight;
import com.xiaoniu.subsystem.business.domain.StudentInfo;
import com.xiaoniu.subsystem.business.mapper.StudentInfoMapper;
import com.xiaoniu.subsystem.business.service.IFlightService;
import com.xiaoniu.subsystem.business.service.IStudentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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;

/**
 * <p>
 * 学员信息表 服务实现类
 * </p>
 *
 * @author haoxuyang
 * @since 2024-12-23 05:36:11
 */
@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo> implements IStudentInfoService {
    protected final Validator validator;
    protected final IUnitService unitService;
    protected final IFlightService flightService;
    protected final StudentInfoMapper studentInfoMapper;

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

    @Override
    public String importData(List<StudentInfo> 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 (StudentInfo 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 (null == flight) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、未查询到年度：" + d.getYear() +
                            "度,开训时间：" + DateUtils.dateTime(d.getTrainingTime()) +
                            ",专业（班次）名称：" + d.getFlightName() + "的班次，导入失败");
                    continue;
                }
                // 验证是否存在这个数据
                StudentInfo u = baseMapper.selectOne(new LambdaQueryWrapper<StudentInfo>()
                        .eq(StudentInfo::getIdCard,d.getIdCard())
                        .eq(StudentInfo::getFlightName, d.getFlightName())
                        .eq(StudentInfo::getYear,d.getYear())
                        .eq(StudentInfo::getTrainingTime, d.getTrainingTime()));
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, d);
                    //设置主责单位Id
                    Unit mainUnit = unitService.getUnitByName(d.getMainUnitName());
                    if (mainUnit != null){
                        d.setMainUnitId(mainUnit.getUnitId());
                    }
                    d.setFlightId(flight.getFlightId());
                    d.setSendingUnitId(map.get(d.getSendingUnitName()));
                    d.setEducationalSystem(flight.getEducationalSystem());
                    d.setMainUnitId(flight.getMainUnitId());
                    d.setMainUnitName(flight.getMainUnitName());
                    d.setTrainingUnitId(map1.get(d.getTrainingUnitName()));
                    d.setCreateUser(getUserId());
                    d.setCreateDept(unit.getUnitId());
                    d.setCreateTime(new Date());
                    this.save(d);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + " 学员 " + d.getUserName() + "导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, d);
                    d.setFlightId(flight.getFlightId());
                    d.setEducationalSystem(flight.getEducationalSystem());
                    d.setMainUnitId(flight.getMainUnitId());
                    d.setMainUnitName(flight.getMainUnitName());
                    d.setTrainingUnitId(map1.get(d.getTrainingUnitName()));
                    d.setUpdateUser(getUserId());
                    d.setUpdateTime(new Date());
                    d.setStudentId(u.getStudentId());
                    this.updateById(d);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + " 学员 " + d.getUserName() + "更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、" + " 学员 " + d.getUserName() + "已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、" + " 学员 " + d.getUserName() + " 导入失败：";
                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();
    }

    @Override
    public StudentInfo getStudentInfoByFlightIdAndUserName(Long flightId, String userName) {
        return studentInfoMapper.getStudentInfoByFlightIdAndUserName(flightId,userName);
    }
}
