package com.cool.store.service.impl.workflow;

import cn.hutool.core.date.DateUtil;
import com.cool.store.context.CurrentUserHolder;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.dto.calendar.CreateCalendarEventDTO;
import com.cool.store.dto.calendar.DeleteCalendarEventDTO;
import com.cool.store.dto.calendar.UserCalendarsEventDTO;
import com.cool.store.dto.log.ReInterviewDTO;
import com.cool.store.dto.log.RejectInterviewDTO;
import com.cool.store.entity.HyInspectionDO;
import com.cool.store.entity.HyPartnerInterviewDO;
import com.cool.store.enums.*;
import com.cool.store.exception.ApiException;
import com.cool.store.exception.ServiceException;
import com.cool.store.http.ISVHttpRequest;
import com.cool.store.mapper.HyInspectionMapper;
import com.cool.store.mapper.HyPartnerInterviewMapper;
import com.cool.store.mapper.HyPartnerInterviewPlanMapper;
import com.cool.store.request.CloseFollowRequest;
import com.cool.store.request.EntrustOthersReq;
import com.cool.store.request.TransferInvestmentManagerRequest;
import com.cool.store.service.InterviewService;
import com.cool.store.service.LogService;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.vo.interview.InterviewVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author zhangchenbiao
 * @FileName: InterviewWorkFlowService
 * @Description:面试流程
 * @date 2023-06-26 21:24
 */
@Slf4j
@Service
public class InterviewWorkFlowService extends WorkFlowBaseService {

    @Autowired
    private HyPartnerInterviewMapper hyPartnerInterviewMapper;

    @Autowired
    private HyPartnerInterviewPlanMapper hyPartnerInterviewPlanMapper;

    @Autowired
    private HyInspectionMapper inspectionMapper;

    @Autowired
    private InterviewService interviewService;

    @Autowired
    private ISVHttpRequest isvHttpRequest;

    @Autowired
    private LogService logService;
    @Override
    public WorkflowStageEnum getWorkFlowStage() {
        return WorkflowStageEnum.RESERVATION;
    }

    @Override
    public void endProcess(CloseFollowRequest request) throws  ApiException {
        Long lineId = request.getLineId();
        //根据线索id查询面试信息
        List<HyPartnerInterviewDO> interviewBaseInfos = hyPartnerInterviewMapper.getInterviewBaseInfoListByLineIds(Arrays.asList(lineId));
        if (CollectionUtils.isEmpty(interviewBaseInfos)) {
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        HyPartnerInterviewDO interviewBaseInfo = interviewBaseInfos.get(0);
        InterviewVO interviewInfo = hyPartnerInterviewPlanMapper.getInterviewInfo(String.valueOf(interviewBaseInfo.getInterviewPlanId()));
        if(Integer.parseInt(WorkflowStatusEnum.INTERVIEW_2.getCode()) == interviewBaseInfo.getStatus()
            && StringUtils.isNotEmpty(interviewInfo.getRoomStatus())
                && String.valueOf(RoomStatus.WAIT_FOR_OPEN.getCode()).equals(interviewInfo.getRoomStatus())
            && StringUtils.isNotEmpty(interviewInfo.getFeishuCalendarId())
            && StringUtils.isNotEmpty(interviewInfo.getFeishuScheduleId())){
            // 原面试官日程删除
            DeleteCalendarEventDTO deleteCalendarEventDTO = new DeleteCalendarEventDTO();
            deleteCalendarEventDTO.setCalendarId(interviewInfo.getFeishuCalendarId());
            deleteCalendarEventDTO.setEventId(interviewInfo.getFeishuScheduleId());
            deleteCalendarEventDTO.setUserId(interviewInfo.getInterviewerId());
            UserCalendarsEventDTO userCalendarsEventDTO = isvHttpRequest.deleteUserCalendarEvent(deleteCalendarEventDTO);
            if(userCalendarsEventDTO == null ){
                throw new ApiException(ErrorCodeEnum.FEISHU_DELETE_SCHEDULE_ERROR);
            }
        } else if (Integer.parseInt(WorkflowStatusEnum.INTERVIEW_6.getCode()) == interviewBaseInfo.getStatus()) {
            //删除稽核信息
            HyInspectionDO rawHyInspection = inspectionMapper.selectByInterviewPlanId(interviewBaseInfo.getInterviewPlanId());
            HyInspectionDO hyInspection = new HyInspectionDO();
            hyInspection.setId(rawHyInspection.getId());
            hyInspection.setDeleted(Boolean.TRUE);
            inspectionMapper.updateByPrimaryKeySelective(hyInspection);
        }
        interviewService.rejectInterviewAndSuspendLine(interviewBaseInfo.getId(),interviewBaseInfo.getInterviewPlanId(),null);
        //记录日志
        LoginUserInfo operator = CurrentUserHolder.getUser();
        RejectInterviewDTO log = RejectInterviewDTO.builder().mobile(operator.getMobile()).operateUserId(operator.getUserId()).operateUsername(operator.getName()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC))
                .rejectRealReason(request.getRejectRealReason()).rejectPublicReason(request.getRejectPublicReason()).certifyFile(request.getCertifyFile()).build();
        logService.recordBizLog(operator,request.getLineId(), OperateTypeEnum.REJECT_INTERVIEW,log);
    }

    @Override
    public void transferInvestmentManager(TransferInvestmentManagerRequest request) throws ServiceException, ApiException {
        Long lineId = request.getLineId();
        //根据线索id查询面试信息
        List<HyPartnerInterviewDO> interviewBaseInfos = hyPartnerInterviewMapper.getInterviewBaseInfoListByLineIds(Arrays.asList(lineId));
        if (CollectionUtils.isEmpty(interviewBaseInfos)) {
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        HyPartnerInterviewDO interviewBaseInfo = interviewBaseInfos.get(0);
        InterviewVO interviewInfo = hyPartnerInterviewPlanMapper.getInterviewInfo(String.valueOf(interviewBaseInfo.getInterviewPlanId()));
        if(null == interviewInfo){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        Integer status = interviewInfo.getStatus();
        Date now = new Date();
        if (status == Integer.parseInt(WorkflowStatusEnum.INTERVIEW_3.getCode()) ||
                (interviewInfo.getRoomStatus()!=null && String.valueOf(RoomStatus.OPEN.getCode()).equals(interviewInfo.getRoomStatus())) ||
                (DateUtil.compare(DateUtil.parse(interviewInfo.getStartTime()), now) <= 0
                && DateUtil.compare(DateUtil.parse(interviewInfo.getEndTime()), now) >= 0)) {
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_STATUS_ERROR);
        } else if (status == Integer.parseInt(WorkflowStatusEnum.INTERVIEW_2.getCode())) {
            EntrustOthersReq entrustOthersReq = new EntrustOthersReq();
            entrustOthersReq.setInterviewPlanId(interviewInfo.getInterviewPlanId());
            entrustOthersReq.setNewInterviewerId(request.getUserId());
            entrustOthersReq.setPartnerLineId(interviewInfo.getPartnerLineId());
            interviewService.entrustOthers(entrustOthersReq);
        }
    }
}
