package com.jeeplus.human.enrollment.enrollmentRegistration.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentEduInfo;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentRegistration;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentEduInfoMapper;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @date 2023-10-17 8:57
 */
@Service
@Transactional
public class EnrollmentEduInfoService extends ServiceImpl<EnrollmentEduInfoMapper, EnrollmentEduInfo> {

    @Resource
    private EnrollmentEduInfoMapper eduInfoMapper;

    public void deleteByRegistrationId(String id) {
        QueryWrapper<EnrollmentEduInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enrollment_registration_id", id);
        eduInfoMapper.delete(queryWrapper);
    }

    public EnrollmentEduInfo findById(String id) throws Exception {
        // 查询基础信息表
        EnrollmentEduInfo info = eduInfoMapper.getById(id);
        // 查询附件信息
        List<WorkAttachmentInfoDTO> files = eduInfoMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfoDTO i : files) {
                i.setCreateBy(SpringUtil.getBean(IUserApi.class).getById(i.getBy()));
            }
            Map<String, List<WorkAttachmentInfoDTO>> groupedMap = files.stream()
                    .collect(Collectors.groupingBy(WorkAttachmentInfoDTO::getAttachmentFlag));
            List<WorkAttachmentInfoDTO> educationFiles = groupedMap.getOrDefault("education", new ArrayList<>());
            List<WorkAttachmentInfoDTO> degreeFiles = groupedMap.getOrDefault("degree", new ArrayList<>());
            info.setEducationFile(educationFiles);
            info.setDegreeFile(degreeFiles);
        }
        return info;
    }

    public List<EnrollmentEduInfo> findByUserId(String id,String status) {
        QueryWrapper<EnrollmentEduInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(id)) {
            queryWrapper.eq("user_id", id);
        }
        if(StringUtils.isNotBlank(status)){
            if("5".equals(status)){
                queryWrapper.and(wrapper ->
                        wrapper.eq("status", "5")
                                .or().isNull("status")
                                .or().eq("status", "")
                                .or().eq("status", "6")
                );
            } else if("1".equals(status)) {
                queryWrapper.and(wrapper ->
                        wrapper.eq("status", "5")
                                .or().isNull("status")
                                .or().eq("status", "")
                                .or().eq("status", "1")
                );
            } else if("2".equals(status)) {
                queryWrapper.and(wrapper ->
                        wrapper.eq("status", "2")
                );
            }else{
                queryWrapper.and(wrapper ->
                        wrapper.eq("status", "2")
                                .or().eq("status", "4")
                                .or().eq("status", "1")
                );
            }
        }
        List<EnrollmentEduInfo> enrollmentEduInfos = eduInfoMapper.selectList(queryWrapper);
        // 查询附件信息
        for (EnrollmentEduInfo eduInfo : enrollmentEduInfos) {
            List<WorkAttachmentInfoDTO> files = eduInfoMapper.findDtos(eduInfo.getId());
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentInfoDTO i : files) {
                    i.setCreateBy(SpringUtil.getBean(IUserApi.class).getById(i.getBy()));
                }
                Map<String, List<WorkAttachmentInfoDTO>> groupedMap = files.stream()
                        .collect(Collectors.groupingBy(WorkAttachmentInfoDTO::getAttachmentFlag));
                List<WorkAttachmentInfoDTO> educationFiles = groupedMap.getOrDefault("education", new ArrayList<>());
                List<WorkAttachmentInfoDTO> degreeFiles = groupedMap.getOrDefault("degree", new ArrayList<>());
                eduInfo.setEducationFile(educationFiles);
                eduInfo.setDegreeFile(degreeFiles);
            }
        }
        return enrollmentEduInfos;
    }

    public void saveOrUpdateEduInfo(EnrollmentEduInfo enrollmentEduInfo) {
        if (enrollmentEduInfo == null) {
            return;
        }

        if (!StringUtils.isNotBlank(enrollmentEduInfo.getId())) {
            // 新增
            add(enrollmentEduInfo);
        } else {
            // 更新
            update(enrollmentEduInfo);
        }
    }

    /**
     * 新增
     *
     * @param enrollmentEduInfo
     */
    public void add(EnrollmentEduInfo enrollmentEduInfo) {
        String id = UUID.randomUUID().toString().replace("-", "");
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        // 保存学历证书
        if (ObjectUtil.isNotEmpty(enrollmentEduInfo.getEducationFile())) {
            AtomicInteger sort = new AtomicInteger(1);
            enrollmentEduInfo.getEducationFile().stream().forEach(item -> {
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String, String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = id;
                String attachmentFlag = "education";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo", workAttachmentDtoInfo);
                map.put("userDTOInfo", userDTOInfo);
                map.put("attachmentId", attachmentId);
                map.put("attachmentFlag", attachmentFlag);
                map.put("sortInfo", sortInfo);
                String fileId = SpringUtil.getBean(IWorkAttachmentApi.class).saveFile(map);
                sort.getAndIncrement();
            });
        }
        // 保存学位证书
        if (ObjectUtil.isNotEmpty(enrollmentEduInfo.getDegreeFile())) {
            AtomicInteger sort = new AtomicInteger(1);
            enrollmentEduInfo.getDegreeFile().stream().forEach(item -> {
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String, String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = id;
                String attachmentFlag = "degree";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo", workAttachmentDtoInfo);
                map.put("userDTOInfo", userDTOInfo);
                map.put("attachmentId", attachmentId);
                map.put("attachmentFlag", attachmentFlag);
                map.put("sortInfo", sortInfo);
                String fileId = SpringUtil.getBean(IWorkAttachmentApi.class).saveFile(map);
                sort.getAndIncrement();
            });
        }
        enrollmentEduInfo.setId(id);
        eduInfoMapper.insert(enrollmentEduInfo);
    }

    public void update(EnrollmentEduInfo enrollmentEduInfo) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        eduInfoMapper.updateById(enrollmentEduInfo);
        SpringUtil.getBean(IWorkAttachmentApi.class).deleteByAttachmentId(enrollmentEduInfo.getId());
        // 保存学历证明
        if (ObjectUtil.isNotEmpty(enrollmentEduInfo.getEducationFile())) {
            AtomicInteger sort = new AtomicInteger(1);
            enrollmentEduInfo.getEducationFile().stream().forEach(item -> {
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String, String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = enrollmentEduInfo.getId();
                String attachmentFlag = "education";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo", workAttachmentDtoInfo);
                map.put("userDTOInfo", userDTOInfo);
                map.put("attachmentId", attachmentId);
                map.put("attachmentFlag", attachmentFlag);
                map.put("sortInfo", sortInfo);
                String fileId = SpringUtil.getBean(IWorkAttachmentApi.class).saveFile(map);
                sort.getAndIncrement();
            });
        }
        // 保存学位证明
        if (ObjectUtil.isNotEmpty(enrollmentEduInfo.getDegreeFile())) {
            AtomicInteger sort = new AtomicInteger(1);
            enrollmentEduInfo.getDegreeFile().stream().forEach(item -> {
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String, String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = enrollmentEduInfo.getId();
                String attachmentFlag = "degree";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo", workAttachmentDtoInfo);
                map.put("userDTOInfo", userDTOInfo);
                map.put("attachmentId", attachmentId);
                map.put("attachmentFlag", attachmentFlag);
                map.put("sortInfo", sortInfo);
                String fileId = SpringUtil.getBean(IWorkAttachmentApi.class).saveFile(map);
                sort.getAndIncrement();
            });
        }
    }

    public void saveOrUpdateEduWorkAttachment(EnrollmentEduInfo enrollmentEduInfo) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        SpringUtil.getBean(IWorkAttachmentApi.class).deleteByAttachmentId(enrollmentEduInfo.getId());
        // 保存学历证明
        if (ObjectUtil.isNotEmpty(enrollmentEduInfo.getEducationFile())) {
            AtomicInteger sort = new AtomicInteger(1);
            enrollmentEduInfo.getEducationFile().stream().forEach(item -> {
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String, String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = enrollmentEduInfo.getId();
                String attachmentFlag = "education";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo", workAttachmentDtoInfo);
                map.put("userDTOInfo", userDTOInfo);
                map.put("attachmentId", attachmentId);
                map.put("attachmentFlag", attachmentFlag);
                map.put("sortInfo", sortInfo);
                String fileId = SpringUtil.getBean(IWorkAttachmentApi.class).saveFile(map);
                sort.getAndIncrement();
            });
        }
        // 保存学位证明
        if (ObjectUtil.isNotEmpty(enrollmentEduInfo.getDegreeFile())) {
            AtomicInteger sort = new AtomicInteger(1);
            enrollmentEduInfo.getDegreeFile().stream().forEach(item -> {
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String, String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = enrollmentEduInfo.getId();
                String attachmentFlag = "degree";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo", workAttachmentDtoInfo);
                map.put("userDTOInfo", userDTOInfo);
                map.put("attachmentId", attachmentId);
                map.put("attachmentFlag", attachmentFlag);
                map.put("sortInfo", sortInfo);
                String fileId = SpringUtil.getBean(IWorkAttachmentApi.class).saveFile(map);
                sort.getAndIncrement();
            });
        }
    }

    /**
     * 新增或者更新教育经历数据
     *
     * @param aDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate1(EnrollmentRegistration aDto) {
        // 删除旧数据
        deleteByRegistrationId(aDto.getId());
        //插入
        for (EnrollmentEduInfo b : aDto.getEduInfoList()) {
            b.setId(null);
            b.setEnrollmentRegistrationId(aDto.getId());
            eduInfoMapper.insert(b);
        }
    }

}
