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.EnrollmentCertificateInfo;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentLanguageInfo;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.EnrollmentRewardInfo;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentLanguageInfoMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentRewardInfoMapper;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @version 1.0
 * @date 2023-10-17 8:57
 */
@Service
@Transactional
public class EnrollmentRewardInfoService extends ServiceImpl<EnrollmentRewardInfoMapper, EnrollmentRewardInfo> {

    @Resource
    private EnrollmentRewardInfoMapper mapper;

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

    public EnrollmentRewardInfo findById(String id) throws Exception {
        // 查询基础信息表
        EnrollmentRewardInfo info = mapper.getById(id);
        // 查询附件信息
        List<WorkAttachmentInfoDTO> files = mapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            info.setFiles(files);
        }
        return info;
    }

    /**
     * 根据关联id查询所有数据
     * @return
     */
    public List<EnrollmentRewardInfo> findByUserId(String id,String status)  {
        QueryWrapper<EnrollmentRewardInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(id)) {
            queryWrapper.eq("user_id", id);
        }
        if(com.jeeplus.utils.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")
                                .or().eq("status", "4")
                );
            }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<EnrollmentRewardInfo> infos = mapper.selectList(queryWrapper);
        // 查询附件信息
        for (EnrollmentRewardInfo eduInfo : infos) {
            List<WorkAttachmentInfoDTO> files = mapper.findDtos(eduInfo.getId());
            if (CollectionUtils.isNotEmpty(files)) {
                eduInfo.setFiles(files);
            }
        }
        return infos;
    }


    public void saveOrUpdateInfo(EnrollmentRewardInfo info) {
        if (info == null) {
            return ;
        }

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

    /**
     * 新增
     * @param info
     */
    public void add(EnrollmentRewardInfo info){
        String id = UUID.randomUUID().toString().replace("-", "");
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        // 保存附件
        if (ObjectUtil.isNotEmpty(info.getFiles())) {
            AtomicInteger sort = new AtomicInteger(1);
            info.getFiles().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 = "reward";
                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();
            });
        }
        info.setId(id);
        mapper.insert(info);
    }

    public void update(EnrollmentRewardInfo info){
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        mapper.updateById(info);
        // 附件
        if (ObjectUtil.isNotEmpty(info.getFiles())) {
            SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(info.getId());
            AtomicInteger sort = new AtomicInteger(1);
            info.getFiles().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 = info.getId();
                String attachmentFlag = "reward";
                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 saveOrUpdateWorkAttachment(EnrollmentRewardInfo info){
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        // 附件
        if (ObjectUtil.isNotEmpty(info.getFiles())) {
            SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(info.getId());
            AtomicInteger sort = new AtomicInteger(1);
            info.getFiles().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 = info.getId();
                String attachmentFlag = "reward";
                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();
            });
        }

    }

}
