package com.yida.data.school.smart.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.constant.StringConstant;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideRoster;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideRosterRelationStep;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideStep;
import com.yida.data.common.core.entity.smart.EduSmartWelcomeGuideStepStaff;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.enums.AuditStatusEnum;
import com.yida.data.common.core.enums.GuideStepTypeEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.school.dto.smart.AddUploadFileStepDTO;
import com.yida.data.school.smart.mapper.EduSmartWelcomeGuideRosterMapper;
import com.yida.data.school.smart.mapper.EduSmartWelcomeGuideStepMapper;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideRosterRelationService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideRosterRelationStepService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideStepService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideStepStaffService;
import com.yida.data.school.vo.smart.GuideStepColVO;
import com.yida.data.user.feign.RemoteStaffService;
import java.util.ArrayList;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 智慧迎新指南步骤表Service实现
 *
 * @author ZYJ
 * @date 2023-05-15 15:33:18
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EduSmartWelcomeGuideStepServiceImpl extends ServiceImpl
    <EduSmartWelcomeGuideStepMapper, EduSmartWelcomeGuideStep> implements EduSmartWelcomeGuideStepService {

    private final EduSmartWelcomeGuideStepStaffService eduSmartWelcomeGuideStepStaffService;
    private final EduSmartWelcomeGuideRosterRelationStepService eduSmartWelcomeGuideRosterRelationStepService;
    private final RemoteStaffService remoteStaffService;
    private final EduSmartWelcomeGuideRosterMapper eduSmartWelcomeGuideRosterMapper;

    @Override
    public void addUploadFile(AddUploadFileStepDTO dto) {
        //判断前提步骤
        EduSmartWelcomeGuideStep preStep = getById(dto.getStepId());
        if (Objects.isNull(preStep)) {
            throw new FebsException("步骤信息错误！");
        }
        if (Objects.nonNull(preStep.getPremiseStepId())) {
            EduSmartWelcomeGuideRosterRelationStep premiseRelationStep = eduSmartWelcomeGuideRosterRelationStepService
                .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideRosterRelationStep())
                    .eq(EduSmartWelcomeGuideRosterRelationStep::getRosterId, dto.getRosterId())
                    .eq(EduSmartWelcomeGuideRosterRelationStep::getStepId, preStep.getPremiseStepId())
                    .eq(EduSmartWelcomeGuideRosterRelationStep::getStatus, AuditStatusEnum.PASS_STATUS.getStatus())
                );
            if (Objects.isNull(premiseRelationStep)) {
                EduSmartWelcomeGuideStep premiseStep = getById(preStep.getPremiseStepId());
                throw new FebsException(String.format("请审核通过【%s】后执行其它步骤！", premiseStep.getStepName()));
            }
        }

        EduSmartWelcomeGuideRosterRelationStep relationStep = eduSmartWelcomeGuideRosterRelationStepService
            .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideRosterRelationStep())
                .eq(EduSmartWelcomeGuideRosterRelationStep::getRelationId, dto.getRelationId())
                .eq(EduSmartWelcomeGuideRosterRelationStep::getStepId, dto.getStepId()));

        if (ObjectUtil.isNull(relationStep)) {
            if (CollUtil.isNotEmpty(dto.getUpLoadFileUrlList())) {
                relationStep = new EduSmartWelcomeGuideRosterRelationStep();
                BeanUtils.copyProperties(dto, relationStep);
                relationStep.setUploadFileUrl(CollUtil.join(dto.getUpLoadFileUrlList(), ","));
                eduSmartWelcomeGuideRosterRelationStepService.save(relationStep);
            }
        } else {
            if (CollUtil.isNotEmpty(dto.getUpLoadFileUrlList())) {
                eduSmartWelcomeGuideRosterRelationStepService
                    .update(Wrappers.lambdaUpdate(new EduSmartWelcomeGuideRosterRelationStep())
                        .eq(EduSmartWelcomeGuideRosterRelationStep::getId, relationStep.getId())
                        .set(EduSmartWelcomeGuideRosterRelationStep::getUploadFileUrl,
                            CollUtil.join(dto.getUpLoadFileUrlList(), ",")));
            }
        }
    }

    @Override
    public List<EduSmartWelcomeGuideStep> listStepInfo(Long relationId, Long guideId) {
        // 查询步骤信息
        List<EduSmartWelcomeGuideStep> stepList = list(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStep())
            .eq(EduSmartWelcomeGuideStep::getGuideId, guideId));
        // 查询步骤状态
        int current = 0;
        if (CollUtil.isNotEmpty(stepList)) {
            for (EduSmartWelcomeGuideStep step : stepList) {
                EduSmartWelcomeGuideRosterRelationStep relationStep = eduSmartWelcomeGuideRosterRelationStepService
                    .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideRosterRelationStep())
                        .eq(EduSmartWelcomeGuideRosterRelationStep::getRelationId, relationId)
                        .eq(EduSmartWelcomeGuideRosterRelationStep::getStepId, step.getId()));
                step.setUploadFileUrl(Objects.isNull(relationStep) ? null : relationStep.getUploadFileUrl());
                // 执行状态. -1:未执行, 0:通过
                if (Objects.isNull(relationStep) || relationStep.getStatus() == 1) {
                    step.setStatus(-1);
                } else {
                    step.setStatus(relationStep.getStatus());
                }

                if (current == 0) {
                    if (ObjectUtil.isNotNull(relationStep)) {
                        EduSmartWelcomeGuideRoster roster = eduSmartWelcomeGuideRosterMapper
                            .selectById(relationStep.getRosterId());
                        step.setRoster(roster);
                    }
                }
                current++;
            }
        }
        return stepList;
    }

    @Override
    public List<GuideStepColVO> listGuideRosterTableCol(Long guideId) {
        return list(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStep())
            .eq(EduSmartWelcomeGuideStep::getGuideId, guideId))
            .stream().map(step -> {
                GuideStepColVO vo = new GuideStepColVO();
                BeanUtils.copyProperties(step, vo);
                return vo;
            }).collect(Collectors.toList());
    }

    @Override
    public List<EduSmartWelcomeGuideStep> listStepDetailInfo(Long rosterId, Long guideId) {
        // 查询步骤信息
        List<EduSmartWelcomeGuideStep> stepList = list(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStep())
            .eq(EduSmartWelcomeGuideStep::getGuideId, guideId));
        // 查询步骤状态
        if (CollUtil.isNotEmpty(stepList)) {
            for (EduSmartWelcomeGuideStep step : stepList) {
                EduSmartWelcomeGuideRosterRelationStep relationStep = eduSmartWelcomeGuideRosterRelationStepService
                    .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideRosterRelationStep())
                        .eq(EduSmartWelcomeGuideRosterRelationStep::getRosterId, rosterId)
                        .eq(EduSmartWelcomeGuideRosterRelationStep::getStepId, step.getId()));
                // 查询可以审核的职工信息
                List<EduSmartWelcomeGuideStepStaff> stepStaffList = eduSmartWelcomeGuideStepStaffService
                    .list(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStepStaff())
                        .eq(EduSmartWelcomeGuideStepStaff::getStepId, step.getId()));
                if (CollUtil.isNotEmpty(stepStaffList)) {
                    List<EduStaff> eduStaffs = remoteStaffService.getStaffList(stepStaffList.stream()
                        .map(EduSmartWelcomeGuideStepStaff::getStaffId).collect(Collectors.toList())).getData();
                    step.setStaffNameStr(CollUtil.isNotEmpty(eduStaffs) ?
                        eduStaffs.stream().map(EduStaff::getName).collect(Collectors.joining(StringConstant.COMMA)) : "");
                } else {
                    step.setStaffNameStr("");
                }
                // 执行状态. -1:未执行, 0:通过
                if (Objects.isNull(relationStep) || relationStep.getStatus() == 1) {
                    step.setStatus(-1);
                } else {
                    step.setStatus(relationStep.getStatus());
                }
                if (step.getStatus() == 0) {
                    step.setOperateTime(relationStep.getOperateTime());
                    // 查询审核人信息
                    EduStaff staff = remoteStaffService.getStaff(relationStep.getStaffId()).getData();
                    if (Objects.nonNull(staff)) {
                        step.setStaffName(staff.getName());
                    }
                }
            }
        }
        return stepList;
    }

    @Override
    public List<EduSmartWelcomeGuideStep> listExamineStepInfo(Long rosterId, Long guideId, Long staffId) {
        // 查询步骤信息
        List<EduSmartWelcomeGuideStep> stepList = list(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStep())
            .eq(EduSmartWelcomeGuideStep::getGuideId, guideId));
        // 查询步骤状态
        if (CollUtil.isNotEmpty(stepList)) {
            for (EduSmartWelcomeGuideStep step : stepList) {
                EduSmartWelcomeGuideRosterRelationStep relationStep = eduSmartWelcomeGuideRosterRelationStepService
                    .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideRosterRelationStep())
                        .eq(EduSmartWelcomeGuideRosterRelationStep::getRosterId, rosterId)
                        .eq(EduSmartWelcomeGuideRosterRelationStep::getStepId, step.getId()));
                step.setCommentContent(Objects.isNull(relationStep) ? null : relationStep.getCommentContent());
                step.setUploadFileUrl(Objects.isNull(relationStep) ? null : relationStep.getUploadFileUrl());
                // 执行状态. -1:未执行, 0:通过
                if (Objects.isNull(relationStep) || relationStep.getStatus() != 0) {
                    step.setStatus(-1);
                } else {
                    step.setStatus(0);
                }

                if (step.getStatus() == 0) {
                    step.setOperateTime(relationStep.getOperateTime());
                    // 查询审核人信息
                    EduStaff staff = remoteStaffService.getStaff(relationStep.getStaffId()).getData();
                    if (Objects.nonNull(staff)) {
                        step.setStaffName(staff.getName());
                    }
                    step.setButtonStatus(1);
                    continue;
                }
                // 判断是否显示通过按钮. 没有人通过的情况下
                EduSmartWelcomeGuideStepStaff stepStaff = eduSmartWelcomeGuideStepStaffService
                    .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideStepStaff())
                        .eq(EduSmartWelcomeGuideStepStaff::getStepId, step.getId())
                        .eq(EduSmartWelcomeGuideStepStaff::getStaffId, staffId));
                // 判断按钮状态. 0-代表显示通过按钮，1-代表不显示通过按钮
                if (Objects.isNull(stepStaff)) {
                    step.setButtonStatus(1);
                } else {
                    // 判断是否有前提步骤
                    if (Objects.isNull(step.getPremiseStepId())) {
                        step.setButtonStatus(0);
                    } else {
                        // 判断前提步骤是否通过
                        EduSmartWelcomeGuideStep premiseStep = premiseStep(step.getPremiseStepId(),
                            new EduSmartWelcomeGuideStep());
                        if (ObjectUtil.isNotNull(premiseStep)) {
                            if (ObjectUtil.equals(GuideStepTypeEnum.EXAMINE_TYPE.getType(), premiseStep.getStepType())
                                || ObjectUtil
                                .equals(GuideStepTypeEnum.CLASS.getType(), premiseStep.getStepType()) ||
                                ObjectUtil.equals(GuideStepTypeEnum.DORM.getType(), premiseStep.getStepType()) ||
                                ObjectUtil.equals(GuideStepTypeEnum.MATCH_FACE.getType(), premiseStep.getStepType())) {
                                //需要审核
                                EduSmartWelcomeGuideRosterRelationStep premiseRelationStep = eduSmartWelcomeGuideRosterRelationStepService
                                    .getOne(Wrappers.lambdaQuery(new EduSmartWelcomeGuideRosterRelationStep())
                                        .eq(EduSmartWelcomeGuideRosterRelationStep::getRosterId, rosterId)
                                        .eq(EduSmartWelcomeGuideRosterRelationStep::getStatus, 0)
                                        .eq(EduSmartWelcomeGuideRosterRelationStep::getStepId, premiseStep.getId()));
                                step.setButtonStatus(Objects.isNull(premiseRelationStep) ? 1 : 0);
                            } else {
                                step.setButtonStatus(0);
                            }
                        } else {
                            step.setButtonStatus(0);
                        }
                    }
                }
            }
        }
        return stepList;
    }

    @Override
    public EduSmartWelcomeGuideStep premiseStep(Long stepId, EduSmartWelcomeGuideStep step) {
        EduSmartWelcomeGuideStep currentStep = getById(stepId);
        if (ObjectUtil.equals(GuideStepTypeEnum.EXAMINE_TYPE.getType(), currentStep.getStepType()) || ObjectUtil
            .equals(GuideStepTypeEnum.CLASS.getType(), currentStep.getStepType()) ||
            ObjectUtil.equals(GuideStepTypeEnum.DORM.getType(), currentStep.getStepType())
            || ObjectUtil.equals(GuideStepTypeEnum.MATCH_FACE.getType(), currentStep.getStepType())) {
            step = currentStep;
        } else {
            if (ObjectUtil.isNotNull(currentStep.getPremiseStepId())) {
                step = premiseStep(currentStep.getPremiseStepId(), step);
            } else {
                step = currentStep;
            }
        }
        return step;
    }


    /**
     * 递归获取上一步需要审核的步骤
     *
     * @param stepId
     * @return
     */
    public EduSmartWelcomeGuideStep loopPremiseStep(Long stepId) {
        EduSmartWelcomeGuideStep currentStep = getById(stepId);
        if (ObjectUtil.isNull(currentStep.getPremiseStepId())) {
            return null;
        }

        return null;
    }

}
