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

import cn.hutool.core.collection.CollectionUtil;
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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.human.enrollment.enrollmentRegistration.domain.*;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentRegistrationMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentSkillInfoMapper;
import com.jeeplus.human.enrollment.enrollmentRegistration.mapper.EnrollmentUserInfoAuditMapper;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.PostDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
import com.taobao.api.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @version 1.0
 * @date 2023-10-17 8:57
 */
@Service
@Transactional
public class EnrollmentUserInfoAuditService extends ServiceImpl<EnrollmentUserInfoAuditMapper, EnrollmentUserInfoAudit> {

    @Resource
    private EnrollmentUserInfoAuditMapper mapper;
    @Resource
    private EnrollmentRegistrationService enrollmentRegistrationService;

    @Resource
    private EnrollmentEduInfoService eduInfoService;

    @Resource
    private EnrollmentWorkInfoService workInfoService;
    @Resource
    private EnrollmentTrainingInfoService trainingInfoService;

    @Resource
    private EnrollmentCertificateInfoService certificateInfoService;
    @Resource
    private EnrollmentSkillInfoService skillInfoService;

    @Resource
    private EnrollmentLanguageInfoService languageInfoService;
    @Resource
    private EnrollmentFamilyInfoService familyInfoService;
    @Resource
    private EnrollmentRewardInfoService rewardInfoService;

    @Resource
    private EnrollmentSocietyInfoService societyInfoService;

    @Resource
    private EnrollmentPerformanceInfoService performanceInfoService;

    @Resource
    private EnrollmentRegistrationMapper registrationMapper;

    @Resource
    private IFlowableApi flowTaskService;

    @Resource
    private EnrollmentRegistrationMapper enrollmentRegistrationMapper;


    public void updateInfoAgree(EnrollmentUserInfoAudit registration) throws ApiException {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(registration.getUserId());
        EnrollmentRegistration enrollmentRegistration = new EnrollmentRegistration();
        BeanUtils.copyProperties(registration, enrollmentRegistration);
        enrollmentRegistration.setId(registration.getRegistrationId());
        ArrayList<String> roles = new ArrayList<>();
        ArrayList<String> posts = new ArrayList<>();
        if (userDTO != null) {
            if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())) {
                for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                    roles.add(roleDTO.getId());
                }
            }
            if (CollectionUtil.isNotEmpty(userDTO.getPostDTOList())) {
                for (PostDTO postDTO : userDTO.getPostDTOList()) {
                    posts.add(postDTO.getId());
                }
            }
        }
        enrollmentRegistration.setRoleIdList(roles);
        enrollmentRegistration.setPostIdList(posts);
        //更新到主表
        enrollmentRegistrationService.updateRegistration(enrollmentRegistration);
        //删除备份的附件数据
        SpringUtil.getBean(IWorkAttachmentApi.class).deleteByAttachmentId(registration.getId());
        IWorkAttachmentApi workAttachmentApi = SpringUtil.getBean(IWorkAttachmentApi.class);
        //重新保存附件数据作为主数据
        saveAttachments(registration.getIdCardFront(), "idCardFront", enrollmentRegistration.getId(), userDTO, workAttachmentApi);
        saveAttachments(registration.getIdCardBack(), "idCardBack", enrollmentRegistration.getId(), userDTO, workAttachmentApi);
        EnrollmentUserInfoAudit entity = new EnrollmentUserInfoAudit();
        entity.setId(registration.getId()); // 目标记录ID
        String status = registration.getStatus();
        mapper.deleteById(registration.getId());
        //更新提交审批的时间
        enrollmentRegistrationMapper.updateApprovalTime(registration.getUserId());
        String userId = registration.getUserId();
        //删除旧数据
        eduInfoService.remove(
                new QueryWrapper<EnrollmentEduInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        workInfoService.remove(
                new QueryWrapper<EnrollmentWorkInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        trainingInfoService.remove(
                new QueryWrapper<EnrollmentTrainingInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        certificateInfoService.remove(
                new QueryWrapper<EnrollmentCertificateInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        skillInfoService.remove(
                new QueryWrapper<EnrollmentSkillInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        languageInfoService.remove(
                new QueryWrapper<EnrollmentLanguageInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        familyInfoService.remove(
                new QueryWrapper<EnrollmentFamilyInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        rewardInfoService.remove(
                new QueryWrapper<EnrollmentRewardInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        societyInfoService.remove(
                new QueryWrapper<EnrollmentSocietyInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        performanceInfoService.remove(
                new QueryWrapper<EnrollmentPerformanceInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "5")
                                        .or().eq("status", "1")
                                        .or().eq("status", "6")
                                        .or().eq("status", "4")
                                        .or().isNull("status")
                                        .or().eq("status", "")
                        )
        );

        //  修改数据状态
        eduInfoService.update(
                new LambdaUpdateWrapper<EnrollmentEduInfo>()
                        .eq(EnrollmentEduInfo::getUserId, userId)
                        .eq(EnrollmentEduInfo::getStatus, status)
                        .set(EnrollmentEduInfo::getStatus, "5")
        );
        workInfoService.update(
                new LambdaUpdateWrapper<EnrollmentWorkInfo>()
                        .eq(EnrollmentWorkInfo::getUserId, userId)
                        .eq(EnrollmentWorkInfo::getStatus, status)
                        .set(EnrollmentWorkInfo::getStatus, "5")
        );

        trainingInfoService.update(
                new LambdaUpdateWrapper<EnrollmentTrainingInfo>()
                        .eq(EnrollmentTrainingInfo::getUserId, userId)
                        .eq(EnrollmentTrainingInfo::getStatus, status)
                        .set(EnrollmentTrainingInfo::getStatus, "5")
        );

        certificateInfoService.update(
                new LambdaUpdateWrapper<EnrollmentCertificateInfo>()
                        .eq(EnrollmentCertificateInfo::getUserId, userId)
                        .eq(EnrollmentCertificateInfo::getStatus, status)
                        .set(EnrollmentCertificateInfo::getStatus, "5")
        );

        skillInfoService.update(
                new LambdaUpdateWrapper<EnrollmentSkillInfo>()
                        .eq(EnrollmentSkillInfo::getUserId, userId)
                        .eq(EnrollmentSkillInfo::getStatus, status)
                        .set(EnrollmentSkillInfo::getStatus, "5")
        );

        languageInfoService.update(
                new LambdaUpdateWrapper<EnrollmentLanguageInfo>()
                        .eq(EnrollmentLanguageInfo::getUserId, userId)
                        .eq(EnrollmentLanguageInfo::getStatus, status)
                        .set(EnrollmentLanguageInfo::getStatus, "5")
        );

        familyInfoService.update(
                new LambdaUpdateWrapper<EnrollmentFamilyInfo>()
                        .eq(EnrollmentFamilyInfo::getUserId, userId)
                        .eq(EnrollmentFamilyInfo::getStatus, status)
                        .set(EnrollmentFamilyInfo::getStatus, "5")
        );

        rewardInfoService.update(
                new LambdaUpdateWrapper<EnrollmentRewardInfo>()
                        .eq(EnrollmentRewardInfo::getUserId, userId)
                        .eq(EnrollmentRewardInfo::getStatus, status)
                        .set(EnrollmentRewardInfo::getStatus, "5")
        );

        societyInfoService.update(
                new LambdaUpdateWrapper<EnrollmentSocietyInfo>()
                        .eq(EnrollmentSocietyInfo::getUserId, userId)
                        .eq(EnrollmentSocietyInfo::getStatus, status)
                        .set(EnrollmentSocietyInfo::getStatus, "5")
        );

        performanceInfoService.update(
                new LambdaUpdateWrapper<EnrollmentPerformanceInfo>()
                        .eq(EnrollmentPerformanceInfo::getUserId, userId)
                        .eq(EnrollmentPerformanceInfo::getStatus, status)
                        .set(EnrollmentPerformanceInfo::getStatus, "5")
        );

    }

    public void updateInfoReject(EnrollmentUserInfoAudit registration) throws ApiException {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(registration.getUserId());
        EnrollmentUserInfoAudit enrollmentUserInfoAudit = new EnrollmentUserInfoAudit();
        enrollmentUserInfoAudit.setId(registration.getId());
        enrollmentUserInfoAudit.setStatus("4");
        mapper.updateById(enrollmentUserInfoAudit);
        String userId = registration.getUserId();
        String status = "4";
        sendNotify(userDTO,registration.getProcessDefinitionId());
        enrollmentRegistrationMapper.updateApprovalTime(registration.getUserId());
        eduInfoService.remove(
                new QueryWrapper<EnrollmentEduInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.or().eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        workInfoService.remove(
                new QueryWrapper<EnrollmentWorkInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        trainingInfoService.remove(
                new QueryWrapper<EnrollmentTrainingInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        certificateInfoService.remove(
                new QueryWrapper<EnrollmentCertificateInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        skillInfoService.remove(
                new QueryWrapper<EnrollmentSkillInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        languageInfoService.remove(
                new QueryWrapper<EnrollmentLanguageInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        familyInfoService.remove(
                new QueryWrapper<EnrollmentFamilyInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        rewardInfoService.remove(
                new QueryWrapper<EnrollmentRewardInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        societyInfoService.remove(
                new QueryWrapper<EnrollmentSocietyInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")
                        )
        );

        performanceInfoService.remove(
                new QueryWrapper<EnrollmentPerformanceInfo>()
                        .eq("user_id", userId)
                        .and(wrapper ->
                                wrapper.eq("status", "1")
                                        .or().eq("status", "4")

                        )
        );
        //  修改数据状态
        eduInfoService.update(
                new LambdaUpdateWrapper<EnrollmentEduInfo>()
                        .eq(EnrollmentEduInfo::getUserId, userId)
                        .eq(EnrollmentEduInfo::getStatus, "2")
                        .set(EnrollmentEduInfo::getStatus,status)
        );
        workInfoService.update(
                new LambdaUpdateWrapper<EnrollmentWorkInfo>()
                        .eq(EnrollmentWorkInfo::getUserId, userId)
                        .eq(EnrollmentWorkInfo::getStatus, "2")
                        .set(EnrollmentWorkInfo::getStatus,status)
        );

        trainingInfoService.update(
                new LambdaUpdateWrapper<EnrollmentTrainingInfo>()
                        .eq(EnrollmentTrainingInfo::getUserId, userId)
                        .eq(EnrollmentTrainingInfo::getStatus, "2")
                        .set(EnrollmentTrainingInfo::getStatus,status)
        );

        certificateInfoService.update(
                new LambdaUpdateWrapper<EnrollmentCertificateInfo>()
                        .eq(EnrollmentCertificateInfo::getUserId, userId)
                        .eq(EnrollmentCertificateInfo::getStatus, "2")
                        .set(EnrollmentCertificateInfo::getStatus, status)
        );

        skillInfoService.update(
                new LambdaUpdateWrapper<EnrollmentSkillInfo>()
                        .eq(EnrollmentSkillInfo::getUserId, userId)
                        .eq(EnrollmentSkillInfo::getStatus, "2")
                        .set(EnrollmentSkillInfo::getStatus,status)
        );

        languageInfoService.update(
                new LambdaUpdateWrapper<EnrollmentLanguageInfo>()
                        .eq(EnrollmentLanguageInfo::getUserId, userId)
                        .eq(EnrollmentLanguageInfo::getStatus, "2")
                        .set(EnrollmentLanguageInfo::getStatus, status)
        );

        familyInfoService.update(
                new LambdaUpdateWrapper<EnrollmentFamilyInfo>()
                        .eq(EnrollmentFamilyInfo::getUserId, userId)
                        .eq(EnrollmentFamilyInfo::getStatus, "2")
                        .set(EnrollmentFamilyInfo::getStatus, status)
        );

        rewardInfoService.update(
                new LambdaUpdateWrapper<EnrollmentRewardInfo>()
                        .eq(EnrollmentRewardInfo::getUserId, userId)
                        .eq(EnrollmentRewardInfo::getStatus, "2")
                        .set(EnrollmentRewardInfo::getStatus, status)
        );

        societyInfoService.update(
                new LambdaUpdateWrapper<EnrollmentSocietyInfo>()
                        .eq(EnrollmentSocietyInfo::getUserId, userId)
                        .eq(EnrollmentSocietyInfo::getStatus, "2")
                        .set(EnrollmentSocietyInfo::getStatus, status)
        );

        performanceInfoService.update(
                new LambdaUpdateWrapper<EnrollmentPerformanceInfo>()
                        .eq(EnrollmentPerformanceInfo::getUserId, userId)
                        .eq(EnrollmentPerformanceInfo::getStatus, "2")
                        .set(EnrollmentPerformanceInfo::getStatus, status)
        );
    }

    private void saveAttachments(List<WorkAttachmentInfoDTO> attachmentList, String flag, String attachmentId, UserDTO userDTO, IWorkAttachmentApi workAttachmentApi) {
        if (ObjectUtil.isEmpty(attachmentList)) return;
        AtomicInteger sort = new AtomicInteger(1);
        for (WorkAttachmentInfoDTO item : attachmentList) {
            WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
            workAttachmentDto.setName(item.getName());
            workAttachmentDto.setSize(item.getSize());
            workAttachmentDto.setUrl(item.getUrl());
            Map<String, String> map = new HashMap<>();
            map.put("workAttachmentDtoInfo", JSON.toJSONString(workAttachmentDto));
            map.put("userDTOInfo", JSON.toJSONString(userDTO));
            map.put("attachmentId", attachmentId);
            map.put("attachmentFlag", flag);
            map.put("sortInfo", String.valueOf(sort.getAndIncrement()));
            workAttachmentApi.saveFile(map);
        }
    }


    public void sendNotify(UserDTO userDto,String defId){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String day = format.format(new Date());
        String title = "管理员驳回了-[个人信息审批]";
        Map<String ,String > map = new HashMap<>();
        String uuid = UUID.randomUUID().toString();
        map.put("taskId",uuid);
        map.put("title",title);
        map.put("defId",defId);
        map.put("taskName","个人信息审批");
        map.put("createUser",userDto.getName());
        map.put("createTime",day);
        map.put("noticeName",userDto.getLoginName());
        map.put("noticeId",userDto.getId());
        map.put("createById",userDto.getId());
        flowTaskService.add(map);
    }


    public void updateStatusByIdUserInfo(EnrollmentRegistration registration){
        enrollmentRegistrationService.updateStatusByIdUserInfo(registration);
    }


}
