package com.cool.store.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.dto.interview.LineInterviewPageDTO;
import com.cool.store.entity.*;
import com.cool.store.enums.*;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.AuditStatusMapper;
import com.cool.store.request.*;
import com.cool.store.service.*;
import com.cool.store.utils.TRTCUtils;
import com.cool.store.utils.UUIDUtils;
import com.cool.store.utils.poi.DateUtils;
import com.cool.store.vo.LineAuditInfoVO;
import com.cool.store.vo.interview.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zhangchenbiao
 * @FileName: LineInterviewServiceImpl
 * @Description:
 * @date 2024-03-15 16:04
 */
@Slf4j
@Service
public class LineInterviewServiceImpl extends LineFlowService implements LineInterviewService {

    @Value("${trtc.sdkAppId}")
    private Long sdkAppId;
    @Value("${trtc.secretKey}")
    private String key;
    @Resource
    private LineInfoDAO lineInfoDAO;
    @Resource
    private LineInterviewDAO lineInterviewDAO;
    @Resource
    private LineCalendarsEventDAO lineCalendarsEventDAO;
    @Resource
    private LabelService labelService;
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private HyOpenAreaInfoDAO hyOpenAreaInfoDAO;
    @Resource
    private LineAuditInfoDAO lineAuditInfoDAO;
    @Resource
    private CommonService commonService;
    @Resource
    private UserAuthMappingService userAuthMappingService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private TransferLogService transferLogService;
    @Resource
    private HyPartnerUserChannelDAO hyPartnerUserChannelDAO;
    @Resource
    private ShopService shopService;

    @Resource
    AuditStatusService auditStatusService;

    @Override
    public List<AppointmentTimeVO> getAppointmentTime(Long lineId, Integer interviewType, LocalDate appointmentDate) {
        InterviewTypeEnum interviewTypeEnum = InterviewTypeEnum.match(interviewType);
        List<Pair<String, Boolean>> timeSlots = InterviewTypeEnum.getTimeSlots(interviewTypeEnum, appointmentDate);
        List<LineCalendarsEventDO> eventList = null;
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(lineId);
        if(Objects.isNull(lineInfo)){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        //如果是面谈 获取招商经理的时间  如果是面试 获取大区的时间
        if(InterviewTypeEnum.MEET.equals(interviewTypeEnum)){
            eventList = lineCalendarsEventDAO.getInterviewerLineCalendarsEvent(lineInfo.getInvestmentManager(), appointmentDate);
        }else{
            eventList = lineCalendarsEventDAO.getRegionLineCalendarsEvent(lineInfo.getRegionId(), appointmentDate);
        }
        List<AppointmentTimeVO> resultList = AppointmentTimeVO.getAppointmentTime(appointmentDate, timeSlots, eventList);
        return resultList;
    }

    @Override
    public List<AppointmentTimeListVO> getAppointmentTime(Long lineId, Integer interviewType, LocalDate appointmentStartDate, LocalDate appointmentEndDate) {
        if(Objects.isNull(lineId) || Objects.isNull(interviewType) || Objects.isNull(appointmentStartDate) || Objects.isNull(appointmentEndDate)){
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        List<AppointmentTimeListVO> resultList = new ArrayList<>();
        while (appointmentEndDate.isAfter(appointmentStartDate) || appointmentStartDate.equals(appointmentEndDate)){
            List<AppointmentTimeVO> appointmentTime = getAppointmentTime(lineId, interviewType, appointmentStartDate);
            AppointmentTimeListVO appointmentTimeList = new AppointmentTimeListVO(appointmentStartDate.toString(), appointmentStartDate.getDayOfWeek().getValue(), appointmentTime);
            resultList.add(appointmentTimeList);
            appointmentStartDate = appointmentStartDate.plusDays(1);
        }
        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean appointmentTime(AppointmentTimeRequest request) {
        Date startTime = DateUtils.strToDate(request.getStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        Date endTime = DateUtils.strToDate(request.getEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        Date now = new Date();
        if(now.getTime() >= startTime.getTime()){
            throw new ServiceException(ErrorCodeEnum.APPOINTMENT_TIME_FAIL);
        }
        //查询线索信息
        //如果是面谈获取招商经理  如果是面试获取大区经理
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(request.getLineId());
        if(Objects.isNull(lineInfo)){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        //判断是否存在当前类型的面审如果存在 删除面审信息 生成新的面审
        if(!WorkflowSubStageEnum.isInterviewStage(lineInfo.getWorkflowSubStage())){
            log.info("线索当前所处阶段不可预约日程");
            throw new ServiceException(ErrorCodeEnum.LINE_STATUS_NOT_ALLOW_OPERATE);
        }
        InterviewTypeEnum interviewType = WorkflowSubStageEnum.getInterviewType(lineInfo.getWorkflowSubStage());
        String interviewerUserId = lineInfo.getInvestmentManager(), firstInterviewer = null, secondInterviewer = null;
        if(!InterviewTypeEnum.MEET.equals(interviewType)){
            EnterpriseUserDO enterpriseUser = userAuthMappingService.getUserByRoleEnumAndWantShopAreaId(UserRoleEnum.REGION_MANAGER, lineInfo.getWantShopAreaId());
            interviewerUserId = Optional.ofNullable(enterpriseUser).map(EnterpriseUserDO::getUserId).orElse(null);
        }
        firstInterviewer = InterviewTypeEnum.INTERVIEW.equals(interviewType) ? interviewerUserId : null;
        secondInterviewer = InterviewTypeEnum.SECOND_INTERVIEW.equals(interviewType) ? interviewerUserId : null;
        Boolean occupied = lineCalendarsEventDAO.isOccupied(interviewType.getCode(), lineInfo.getRegionId(), interviewerUserId, request.getStartTime(), request.getEndTime(), null);
        if(occupied){
            throw new ServiceException(ErrorCodeEnum.TIME_OCCUPIED);
        }
        LineCalendarsEventDO calendarsEvent = LineCalendarsEventDO.convertDO(lineInfo, interviewType.getCode(), startTime, endTime, interviewerUserId);
        Long eventId = lineCalendarsEventDAO.addCalendarsEvent(calendarsEvent);
        WorkflowSubStageStatusEnum workflowSubStageStatus = InterviewTypeEnum.getWorkflowSubStageStatus(interviewType);
        //跟新线索状态为已预约
        lineInfoDAO.updateWorkflowStageAndInterviewer(lineInfo.getId(), workflowSubStageStatus, firstInterviewer, secondInterviewer);
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfo(lineInfo.getId(), interviewType);
        if(Objects.nonNull(interviewInfo)){
            if(!WorkflowSubStageStatusEnum.isReappointmentStatus(lineInfo.getWorkflowSubStageStatus())){
                log.info("当前线索状态不是重新预约状态");
                throw new ServiceException(ErrorCodeEnum.LINE_STATUS_NOT_ALLOW_OPERATE);
            }
            //删除该面试记录
            lineInterviewDAO.deleteInterviewInfo(interviewInfo.getId());
        }
        LineInterviewDO addInterview = LineInterviewDO.convertDO(lineInfo, startTime, endTime, UUIDUtils.get8UUID(), interviewerUserId, interviewType.getCode(), eventId);
        lineInterviewDAO.addInterviewInfo(addInterview);
        MessageEnum messageEnum = MessageEnum.MESSAGE_2;
        MessageEnum investmentManagerMessageEnum = null;
        if(InterviewTypeEnum.INTERVIEW.equals(interviewType)){
            messageEnum = MessageEnum.MESSAGE_3;
            investmentManagerMessageEnum = MessageEnum.MESSAGE_3_1;
        }
        if(InterviewTypeEnum.SECOND_INTERVIEW.equals(interviewType)){
            messageEnum = MessageEnum.MESSAGE_10;
            investmentManagerMessageEnum = MessageEnum.MESSAGE_10_1;
        }
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("lineId", String.valueOf(lineInfo.getId()));
        messageMap.put("partnerUsername", lineInfo.getUsername());
        messageMap.put("appointmentTime", DateUtils.parseDateToStr(DateUtils.NOTICE_DATE, startTime));
        messageMap.put("interviewUsername", enterpriseUserDAO.getUserName(interviewerUserId));
        commonService.sendMessage(Arrays.asList(interviewerUserId), messageEnum, messageMap);
        if(Objects.nonNull(investmentManagerMessageEnum)){
            commonService.sendMessage(Arrays.asList(lineInfo.getInvestmentManager()), investmentManagerMessageEnum, messageMap);
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyAppointmentTime(AppointmentTimeRequest request) {
        Date startTime = DateUtils.strToDate(request.getStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        Date endTime = DateUtils.strToDate(request.getEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        Date nowTime = new Date();
        if(nowTime.getTime() >= startTime.getTime()){
            throw new ServiceException(ErrorCodeEnum.APPOINTMENT_TIME_FAIL);
        }
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(request.getLineId());
        if(Objects.isNull(lineInfo)){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        if(!WorkflowSubStageEnum.isInterviewStage(lineInfo.getWorkflowSubStage())){
            //当前线索状态不允许修改面审时间
            log.info("当前线索所处阶段不允许修改面审时间");
            throw new ServiceException(ErrorCodeEnum.LINE_STATUS_NOT_ALLOW_OPERATE);
        }
        if(!WorkflowSubStageStatusEnum.isModifyAppointmentTime(lineInfo.getWorkflowSubStageStatus())){
            log.info("当前线索所处子状态不允许修改面审时间");
            throw new ServiceException(ErrorCodeEnum.LINE_STATUS_NOT_ALLOW_OPERATE);
        }
        InterviewTypeEnum interviewType = WorkflowSubStageEnum.getInterviewType(lineInfo.getWorkflowSubStage());
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfo(request.getLineId(), interviewType);
        if(Objects.isNull(interviewInfo)){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        Boolean occupied = lineCalendarsEventDAO.isOccupied(interviewType.getCode(), lineInfo.getRegionId(), interviewInfo.getInterviewerUserId(), request.getStartTime(), request.getEndTime(), interviewInfo.getId());
        if(occupied){
            throw new ServiceException(ErrorCodeEnum.TIME_OCCUPIED);
        }
        LocalDateTime startDateTime = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault()).minusMinutes(10);
        LocalDateTime now = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());
        if(startDateTime.isBefore(now)){
            throw new ServiceException(ErrorCodeEnum.FEISHU_UPDATE_SCHEDULE_ERROR);
        }
        LineInterviewDO updateInterview = new LineInterviewDO();
        updateInterview.setId(interviewInfo.getId());
        updateInterview.setInterviewDate(startTime);
        updateInterview.setStartTime(startTime);
        updateInterview.setEndTime(endTime);
        lineInterviewDAO.updateInterviewInfo(updateInterview);
        LineCalendarsEventDO updateEvent = new LineCalendarsEventDO();
        updateEvent.setId(interviewInfo.getCalendarsEventId());
        updateEvent.setStartTime(startTime);
        updateEvent.setEndTime(endTime);
        updateEvent.setInterviewDate(startTime);
        lineCalendarsEventDAO.updateCalendarsEvent(updateEvent);
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("interviewTime", DateUtils.parseDateToStr(DateUtils.NOTICE_DATE, startTime));
        SMSMsgEnum smsMsgEnum = null;
        if(InterviewTypeEnum.MEET.equals(interviewType)){
            smsMsgEnum = SMSMsgEnum.INTERVIEW_TIME_MODIFY;
        }
        if(InterviewTypeEnum.INTERVIEW.equals(interviewType)){
            smsMsgEnum = SMSMsgEnum.FIRST_INTERVIEW_TIME_MODIFY;
        }
        if(InterviewTypeEnum.SECOND_INTERVIEW.equals(interviewType)){
            smsMsgEnum = SMSMsgEnum.SECOND_INTERVIEW_TIME_MODIFY;
        }
        commonService.sendSms(lineInfo.getMobile(), smsMsgEnum, templateParam);
        return true;
    }

    @Override
    public Boolean modifyInterviewer(ModifyInterviewerRequest request) {
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(request.getLineId());
        if(Objects.isNull(lineInfo)){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        InterviewTypeEnum interviewType = InterviewTypeEnum.match(request.getInterviewType());
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfo(request.getLineId(), interviewType);
        if(Objects.isNull(interviewInfo)){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        LineInterviewDO updateInterview = new LineInterviewDO();
        updateInterview.setId(interviewInfo.getId());
        updateInterview.setInterviewerUserId(request.getInterviewerUserId());
        lineInterviewDAO.updateInterviewInfo(updateInterview);
        LineCalendarsEventDO update = new LineCalendarsEventDO();
        update.setId(interviewInfo.getCalendarsEventId());
        update.setInterviewerUserId(request.getInterviewerUserId());
        lineCalendarsEventDAO.updateCalendarsEvent(update);
        LineInfoDO updateLineInfo = new LineInfoDO();
        updateLineInfo.setId(request.getLineId());
        if(InterviewTypeEnum.INTERVIEW.equals(interviewType)){
            updateLineInfo.setFirstInterviewer(request.getInterviewerUserId());
        }
        if(InterviewTypeEnum.SECOND_INTERVIEW.equals(interviewType)){
            updateLineInfo.setSecondInterviewer(request.getInterviewerUserId());
        }
        lineInfoDAO.updateLineInfo(updateLineInfo);
        transferLogService.addLog(lineInfo, request.getOperatorUserId(), request.getInterviewerUserId(), OperationLogTypeEnum.ENTRUST_INTERVIEW);
        return true;
    }

    @Override
    public PageInfo<LineInterviewPageVO> getInterviewerPage(LineInterviewPageRequest request, String userId, Boolean isTeam) {
        if(isTeam && !sysRoleService.checkIsAdmin(userId)){
            List<Long> wantShopAreaIds = userAuthMappingService.listWantShopAreaIdByUserId(userId);
            if(CollectionUtils.isEmpty(wantShopAreaIds)){
                request.setInterviewerUserId(userId);
            }else{
                request.setWantShopAreaIds(wantShopAreaIds);
            }
        }
        if(Objects.nonNull(request.getWantShopAreaId())){
            HyOpenAreaInfoDO areaInfo = hyOpenAreaInfoDAO.selectById(request.getWantShopAreaId());
            if(Objects.nonNull(areaInfo)){
                request.setAreaPath(areaInfo.getAreaPath());
            }
        }
        Page<LineInterviewPageDTO> pageInfo = lineInterviewDAO.getInterviewerPage(request);
        List<String> userPortraitList  = pageInfo.stream().filter(x -> StringUtils.isNotEmpty(x.getUserPortrait() )).map(LineInterviewPageDTO::getUserPortrait).collect(Collectors.toList());
        List<String> investmentManagerUserIds = pageInfo.stream().filter(x -> StringUtils.isNotEmpty(x.getInvestmentManager() )).map(LineInterviewPageDTO::getInvestmentManager).collect(Collectors.toList());
        List<String> interviewerUserIds = pageInfo.stream().filter(x -> StringUtils.isNotEmpty(x.getInterviewerUserId() )).map(LineInterviewPageDTO::getInterviewerUserId).collect(Collectors.toList());
        List<Long> wantShopAreaIds = pageInfo.stream().filter(x -> Objects.nonNull(x.getWantShopAreaId() )).map(LineInterviewPageDTO::getWantShopAreaId).collect(Collectors.toList());
        List<Integer> lineSourceIds = pageInfo.stream().filter(lineInfoDO -> lineInfoDO.getLineSource() != null).map(LineInterviewPageDTO::getLineSource).collect(Collectors.toList());
        Map<Long, String> cityNameMap = hyOpenAreaInfoDAO.selectNameMapByIds(wantShopAreaIds);
        List<String> userIds = Stream.concat(investmentManagerUserIds.stream(), interviewerUserIds.stream()).distinct().collect(Collectors.toList());
        Map<String, String> userNameMap = enterpriseUserDAO.getUserNameMap(userIds);
        Map<Long, String> userPortraitMap = labelService.getUserPortraitMap(userPortraitList);
        Map<Integer, String> channelMap = hyPartnerUserChannelDAO.getChannelMapByIds(lineSourceIds);
        List<LineInterviewPageVO> resultList = LineInterviewPageVO.convertList(pageInfo, userPortraitMap, userNameMap, cityNameMap, channelMap);
        PageInfo resultPage = new PageInfo(pageInfo);
        resultPage.setList(resultList);
        return resultPage;
    }

    @Override
    public EnterInterviewVO enterInterviewRoom(Long interviewId, String interviewUserId, InterviewUserTypeEnum userType) {
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfoById(interviewId);
        if(Objects.isNull(interviewInfo)){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        //已关闭就禁止进入房间了
        if (interviewInfo.getRoomStatus().equals(RoomStatus.CLOSED.getCode())) {
            throw new ServiceException(ErrorCodeEnum.ROOM_STATUS_ERROR);
        }
        if(InterviewUserTypeEnum.INTERVIEWER.equals(userType) && !interviewUserId.equals(interviewInfo.getInterviewerUserId())){
            throw new ServiceException(ErrorCodeEnum.USER_NOT_ALLOW_ENTER_ROOM);
        }
        if(InterviewUserTypeEnum.LINE.equals(userType) && !interviewUserId.equals(interviewInfo.getPartnerId())){
            throw new ServiceException(ErrorCodeEnum.USER_NOT_ALLOW_ENTER_ROOM);
        }
        String userName = enterpriseUserDAO.getUserName(interviewInfo.getInterviewerUserId());
        Long lineId = interviewInfo.getLineId();
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(lineId);
        if(Objects.isNull(lineInfo)){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        Integer joinInterviewStatus = JoinInterviewStatusEnum.getJoinInterviewStatus(interviewInfo.getJoinInterviewStatus(), userType);
        if(Objects.isNull(interviewInfo.getActualStartTime())){
            interviewInfo.setActualStartTime(new Date());
        }
        interviewInfo.setRoomStatus(RoomStatus.OPEN.getCode());
        interviewInfo.setJoinInterviewStatus(joinInterviewStatus);
        lineInterviewDAO.updateInterviewInfo(interviewInfo);
        String userSig = TRTCUtils.genUserSig(sdkAppId, key, interviewUserId);
        return new EnterInterviewVO(interviewInfo.getLineId(), lineInfo.getPartnerId(), interviewInfo.getRoomId(), userSig, interviewInfo.getInterviewerUserId(), userName, lineInfo.getUsername());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer finishInterview(Long interviewId, String userId) {
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfoById(interviewId);
        if(Objects.isNull(interviewInfo)){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        //已关闭就禁止进入房间了
        if (interviewInfo.getRoomStatus().equals(RoomStatus.CLOSED.getCode())) {
            throw new ServiceException(ErrorCodeEnum.ROOM_STATUS_ERROR);
        }
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(interviewInfo.getLineId());
        if(!WorkflowSubStageEnum.isReappointmentStage(lineInfo.getWorkflowSubStage())){
            throw new ServiceException(ErrorCodeEnum.LINE_STATUS_NOT_ALLOW_OPERATE);
        }
        LineInterviewDO updateInterviewInfo = new LineInterviewDO();
        updateInterviewInfo.setId(interviewId);
        updateInterviewInfo.setRoomStatus(RoomStatus.CLOSED.getCode());
        updateInterviewInfo.setActualEndTime(new Date());
        updateInterviewInfo.setInterviewStatus(InterviewStatusEnum.WAIT_AUDIT.getCode());
        //更新线索状态
        WorkflowSubStageStatusEnum workflowSubStageStatus = null;
        if(InterviewTypeEnum.INTERVIEW.getCode().equals(interviewInfo.getInterviewType())){
            workflowSubStageStatus = WorkflowSubStageStatusEnum.FIRST_INTERVIEWS_35;
        }
        if(InterviewTypeEnum.SECOND_INTERVIEW.getCode().equals(interviewInfo.getInterviewType())){
            workflowSubStageStatus = WorkflowSubStageStatusEnum.SECOND_INTERVIEWS_110;
        }
        lineInfoDAO.updateWorkflowStage(interviewInfo.getLineId(), null, workflowSubStageStatus,userId);
        return lineInterviewDAO.updateInterviewInfo(updateInterviewInfo);
    }

    @Override
    public InterviewDetailVO getInterviewDetail(Long lineId, Integer interviewType) {
        InterviewTypeEnum interviewTypeEnum = InterviewTypeEnum.match(interviewType);
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(lineId);
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfo(lineId, interviewTypeEnum);
        if(Objects.isNull(lineInfo) || Objects.isNull(interviewInfo)){
            return null;
        }
        InterviewDetailVO result = InterviewDetailVO.convertVO(lineInfo, interviewInfo);
        result.setInterviewerUsername(enterpriseUserDAO.getUserName(interviewInfo.getInterviewerUserId()));
        Long auditId = interviewInfo.getAuditId();
        if(Objects.nonNull(auditId) && auditId > CommonConstants.ZERO_LONG){
            LineAuditInfoDO auditInfo = lineAuditInfoDAO.getAuditInfo(auditId);
            result.setAuditInfo(LineAuditInfoVO.convertVO(auditInfo));
        }
        return result;
    }

    @Override
    public Integer uploadVideo(Long interviewId, List<String> videoUrlList) {
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfoById(interviewId);
        if(Objects.isNull(interviewInfo)){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        List<String> videoList = JSONObject.parseArray(interviewInfo.getVideoUrl(), String.class);
        if(videoList == null){
            videoList = new ArrayList<>();
        }
        videoList.addAll(videoUrlList);
        LineInterviewDO updateInterviewInfo = new LineInterviewDO();
        updateInterviewInfo.setId(interviewId);
        updateInterviewInfo.setVideoUrl(JSONObject.toJSONString(videoList.stream().distinct().collect(Collectors.toList())));
        return lineInterviewDAO.updateInterviewInfo(updateInterviewInfo);
    }

    @Override
    public Integer reappointment(Long lineId) {
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(lineId);
        if(Objects.isNull(lineInfo)){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        if(!WorkflowSubStageEnum.isReappointmentStage(lineInfo.getWorkflowSubStage())){
            log.info("当前线索状态不允许重新预约");
            throw new ServiceException(ErrorCodeEnum.LINE_STATUS_NOT_ALLOW_OPERATE);
        }
        WorkflowSubStageStatusEnum workflowSubStageStatus = null;
        if(WorkflowSubStageEnum.FIRST_INTERVIEWS.getCode().equals(lineInfo.getWorkflowSubStage())){
            workflowSubStageStatus = WorkflowSubStageStatusEnum.FIRST_INTERVIEWS_42;
            commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.FIRST_INTERVIEW_REAPPOINTMENT, null);
        }
        if(WorkflowSubStageEnum.SECOND_INTERVIEWS.getCode().equals(lineInfo.getWorkflowSubStage())){
            workflowSubStageStatus = WorkflowSubStageStatusEnum.SECOND_INTERVIEWS_120;
            commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.SECOND_INTERVIEW_REAPPOINTMENT, null);
        }
        return lineInfoDAO.updateWorkflowStage(lineInfo.getId(), null, workflowSubStageStatus,null);
    }

    @Override
    protected Boolean auditPass(Long auditId, LineInfoDO lineInfo, String userId) {
        InterviewTypeEnum interviewType = WorkflowSubStageEnum.getInterviewType(lineInfo.getWorkflowSubStage());
        WorkflowSubStageEnum workflowSubStageEnum = WorkflowSubStageEnum.getWorkflowSubStageEnum(lineInfo.getWorkflowSubStage());
        WorkflowSubStageEnum nextStage = workflowSubStageEnum.getNextStage();
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfo(lineInfo.getId(), interviewType);
        if(Objects.isNull(interviewInfo)){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        if(!InterviewStatusEnum.WAIT_AUDIT.getCode().equals(interviewInfo.getInterviewStatus())){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_STATUS_WAS_AUDITED);
        }
        LineInterviewDO updateInterviewInfo = new LineInterviewDO();
        updateInterviewInfo.setId(interviewInfo.getId());
        updateInterviewInfo.setAuditId(auditId);
        updateInterviewInfo.setInterviewStatus(InterviewStatusEnum.PASS.getCode());
        if(WorkflowSubStageEnum.INVITING_INTERVIEWS.equals(workflowSubStageEnum)){
            //更新线索阶段
            lineInfoDAO.updateWorkflowStage(lineInfo.getId(), nextStage, nextStage.getInitStatus(),userId);
            commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.FIRST_INTERVIEW_APPOINTMENT_SUCCESS, null);
        }
        if(WorkflowSubStageEnum.FIRST_INTERVIEWS.equals(workflowSubStageEnum)){
            //更新线索阶段
            lineInfoDAO.updateWorkflowStage(lineInfo.getId(), nextStage, nextStage.getInitStatus(),userId);
            //一审稽核
            auditStatusService.insert(lineInfo.getId(),interviewInfo.getId(),auditId,AuditStageEnum.ONE.getCode());
            commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.INTENTION_PAYMENT, null);
        }
        if(WorkflowSubStageEnum.SECOND_INTERVIEWS.equals(workflowSubStageEnum)){
            LineInfoDO updateLine = new LineInfoDO();
            updateLine.setId(lineInfo.getId());
            updateLine.setWorkflowStage(WorkflowStageEnum.STORE.getCode());
            updateLine.setWorkflowSubStageStatus(WorkflowSubStageStatusEnum.SECOND_INTERVIEWS_125.getCode());
            EnterpriseUserDO enterpriseUser = userAuthMappingService.getUserByRoleEnumAndWantShopAreaId(UserRoleEnum.SELECT_SITE_COMMISSIONER, lineInfo.getWantShopAreaId());
            String developmentManager = Optional.ofNullable(enterpriseUser).map(EnterpriseUserDO::getUserId).orElse(null);
            updateLine.setDevelopmentManager(developmentManager);
            updateLine.setUpdateUserId(userId);
            lineInfoDAO.updateLineInfo(updateLine);
            //初始化店铺
            shopService.initShop(lineInfo);
            //发送短信
            commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.TRAINING_REGISTER_SUCCESS, null);
            //二审稽核
            auditStatusService.insert(lineInfo.getId(),interviewInfo.getId(),auditId,AuditStageEnum.TWO.getCode());
            //发送短信
            commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.SECOND_INTERVIEW_SUCCESS, null);
            String wantShopName = hyOpenAreaInfoDAO.selectNameMapById(lineInfo.getWantShopAreaId());
            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("lineId", String.valueOf(lineInfo.getId()));
            messageMap.put("partnerUsername", lineInfo.getUsername());
            messageMap.put("partnerMobile", lineInfo.getMobile());
            messageMap.put("wantShopName", wantShopName);
            commonService.sendMessage(Arrays.asList(developmentManager), MessageEnum.MESSAGE_14, messageMap);
        }
        return lineInterviewDAO.updateInterviewInfo(updateInterviewInfo) > 0;
    }

    @Override
    protected Boolean auditReject(Long auditId, LineInfoDO lineInfo,String userId) {
        InterviewTypeEnum interviewType = WorkflowSubStageEnum.getInterviewType(lineInfo.getWorkflowSubStage());
        if(InterviewTypeEnum.MEET.equals(interviewType)){
            return Boolean.FALSE;
        }
        LineInterviewDO interviewInfo = lineInterviewDAO.getInterviewInfo(lineInfo.getId(), interviewType);
        if(Objects.isNull(interviewInfo)){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_NOT_EXIST);
        }
        LineInterviewDO updateInterviewInfo = new LineInterviewDO();
        updateInterviewInfo.setId(interviewInfo.getId());
        updateInterviewInfo.setAuditId(auditId);
        updateInterviewInfo.setInterviewStatus(InterviewStatusEnum.NOT_PASS.getCode());
        lineInfoDAO.updateWorkflowStage(lineInfo.getId(), null, WorkflowSubStageStatusEnum.getInterviewRejectStatus(interviewType),userId);
        String noticeTime = DateUtils.parseDateToStr(DateUtils.NOTICE_DATE, interviewInfo.getStartTime());
        String interviewUserName = enterpriseUserDAO.getUserName(interviewInfo.getInterviewerUserId());
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("lineId", String.valueOf(lineInfo.getId()));
        messageMap.put("partnerUsername", lineInfo.getUsername());
        messageMap.put("interviewTime", noticeTime);
        messageMap.put("interviewUsername", interviewUserName);
        commonService.sendMessage(Arrays.asList(lineInfo.getInvestmentManager()), MessageEnum.MESSAGE_4, messageMap);
        return lineInterviewDAO.updateInterviewInfo(updateInterviewInfo) > 0;
    }

}
