package com.cool.store.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.context.CurrentUserHolder;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.context.PartnerUserHolder;
import com.cool.store.dao.EnterpriseUserDAO;
import com.cool.store.dao.HyIntendDevMappingDAO;
import com.cool.store.dao.HyInterviewDAO;
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.calendar.UserFreeBusyInfoDTO;
import com.cool.store.dto.log.*;
import com.cool.store.dto.message.SendCardMessageDTO;
import com.cool.store.dto.partner.EnterInterviewDto;
import com.cool.store.entity.*;
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.*;
import com.cool.store.request.*;
import com.cool.store.service.EnterpriseUserService;
import com.cool.store.service.InterviewService;
import com.cool.store.service.LogService;
import com.cool.store.service.SmsService;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.utils.StringUtil;
import com.cool.store.utils.TRTCUtils;
import com.cool.store.vo.EnterInterviewVO;
import com.cool.store.vo.EnterpriseUserBaseInfoVO;
import com.cool.store.vo.PartnerUserInfoVO;
import com.cool.store.vo.interview.CreateAppointmentVO;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: young.yu
 * @Date: 2023-06-06  15:19
 * @Description:
 */
@Slf4j
@Service
public class InterviewServiceImpl implements InterviewService {

    @Value("${trtc.sdkAppId:null}")
    private Long sdkAppId;

    @Value("${trtc.secretKey:null}")
    private String key;

    @Value("${hs.sms.templateCode:null}")
    private String templateCode;

    @Value("${feishu.notice.link.url:null}")
    private String linkUrl;

    @Autowired
    private HyPartnerInterviewPlanMapper hyPartnerInterviewPlanMapper;

    @Autowired
    private HyPartnerInterviewMapper hyPartnerInterviewMapper;

    @Autowired
    private ISVHttpRequest isvHttpRequest;

    @Autowired
    private HyPartnerLineInfoMapper hyPartnerLineInfoMapper;

    @Autowired
    private HyPartnerBaseInfoMapper hyPartnerBaseInfoMapper;

    @Autowired
    private EnterpriseUserService enterpriseUserService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private HyInterviewDAO interviewDAO;

    @Autowired
    private LogService logService;

    @Autowired
    private EnterpriseUserDAO enterpriseUserDAO;
    @Override
    public List<InterviewVO> getInterviewList(GetInterviewListReq request) {
        List<InterviewVO> interviewList = hyPartnerInterviewPlanMapper.getInterviewList(request);
        return interviewList;
    }

    @Resource
    HyIntendDevMappingDAO hyIntendDevMappingDAO;

    @Override
    public InterviewVO getInterviewInfo(QueryByInterviewPlanIdReq request) throws ApiException {
        String interviewPlanId = request.getInterviewPlanId();
        InterviewVO vo = hyPartnerInterviewPlanMapper.getInterviewInfo(interviewPlanId);
        //如果面试信息为空，抛出异常
        if (vo == null) {
            throw new ApiException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
        }
        //将 processInfo 解析为 List
        if (!StringUtils.isEmpty(vo.getProcessInfo())) {
            List<String> split = Arrays.asList(vo.getProcessInfo().split(","));
            vo.setVideoList(split);
            vo.setProcessInfo("");
        }
        //查询面试官和记录人信息（面试官必须有）
        EnterpriseUserBaseInfoVO interviewerInfo = hyPartnerInterviewPlanMapper.getEnterpriseUserBaseInfo(vo.getInterviewerId());
        vo.setInterviewerName(interviewerInfo.getName());
        vo.setInterviewerMobile(interviewerInfo.getMobile());
        if (!ObjectUtil.isEmpty(vo.getRecorderId())) {
            EnterpriseUserBaseInfoVO recorderInfo = hyPartnerInterviewPlanMapper.getEnterpriseUserBaseInfo(vo.getRecorderId());
            if (recorderInfo != null) {
                vo.setRecorderName(recorderInfo.getName());
                vo.setRecorderMobile(recorderInfo.getMobile());
            }
        }
        //查询开发主管信息
        if (request.getNeedDevelopmentDirector() != null && request.getNeedDevelopmentDirector()) {
            //查询所属战区

            String wantShopArea = hyPartnerLineInfoMapper.getAffiliationZoneIdByInterviewPlanId(interviewPlanId);
            HyIntendDevelopementMappingDO hyIntendDevelopementMappingDO = hyIntendDevMappingDAO.selectByOpenAreaMappingId(Long.valueOf(wantShopArea), "dev");
            if (hyIntendDevelopementMappingDO == null) {
                return vo;
            }
            //查询开发主管
            EnterpriseUserDO development = enterpriseUserService.getDevelopmentByZoneId(hyIntendDevelopementMappingDO.getMappingId());
            vo.setDevelopmentDirector(development);
        }
        return vo;
    }

    @Override
    @Transactional
    public void entrustOthers(EntrustOthersReq request) throws ApiException {
        //只有房间状态是待开放才可以委托他人
        Integer roomStatus = hyPartnerInterviewPlanMapper.getRoomStatus(request.getInterviewPlanId());
        if (!roomStatus.equals(RoomStatus.WAIT_FOR_OPEN.getCode())) {
            throw new ApiException(ErrorCodeEnum.ROOM_STATUS_ERROR);
        }
        InterviewVO interviewInfo = hyPartnerInterviewPlanMapper.getInterviewInfo(request.getInterviewPlanId());
        //如果面试信息为空，抛出异常
        if (interviewInfo == null) {
            throw new ApiException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
        }
        if(RoomStatus.WAIT_FOR_OPEN.getCode() != Integer.parseInt(interviewInfo.getRoomStatus())){
            throw new ApiException(ErrorCodeEnum.ROOM_STATUS_ERROR);
        }
        //1.新面试官日程新增
        CreateCalendarEventDTO createCalendarEventDTO = new CreateCalendarEventDTO();
        createCalendarEventDTO.setStartTime(DateUtil.parse(interviewInfo.getStartTime()).getTime());
        createCalendarEventDTO.setEndTime(DateUtil.parse(interviewInfo.getEndTime()).getTime());
        createCalendarEventDTO.setUserId(request.getNewInterviewerId());
        createCalendarEventDTO.setJoinUserIds(Arrays.asList(request.getNewInterviewerId()));
        createCalendarEventDTO.setSummary(generateInterviewTitle(request.getPartnerLineId()));
        UserCalendarsEventDTO userCalendarEvent = isvHttpRequest.createUserCalendarEvent(createCalendarEventDTO);
        if(userCalendarEvent == null ){
            throw new ApiException(ErrorCodeEnum.CREATE_CALENDAR_EVENT_FAIL);
        }
        //2.原面试官日程删除
        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);
        }

        // 3.面试信息计划变更
        HyPartnerInterviewPlanDO record = new HyPartnerInterviewPlanDO();
        record.setId(Long.valueOf(request.getInterviewPlanId()));
        record.setInterviewer(request.getNewInterviewerId());
        record.setUpdateTime(new Date());
        record.setFeishuCalendarId(userCalendarEvent.getCalendarId());
        record.setFeishuScheduleId(userCalendarEvent.getEventId());
        hyPartnerInterviewPlanMapper.updateByPrimaryKeySelective(record);

        //更新面试信息
        HyPartnerInterviewDO hyPartnerInterviewDO = new HyPartnerInterviewDO();
        hyPartnerInterviewDO.setInterviewPlanId(Long.valueOf(request.getInterviewPlanId()));
        hyPartnerInterviewDO.setInterviewer(request.getNewInterviewerId());
        hyPartnerInterviewDO.setUpdateTime(new Date());
        hyPartnerInterviewMapper.updateByPrimaryKeySelective(hyPartnerInterviewDO);

        //记录日志
        LoginUserInfo operator = CurrentUserHolder.getUser();
        EnterpriseUserDO enterpriseUserDO = enterpriseUserDAO.getUserInfoById(request.getNewInterviewerId());
        EntrustOthersDTO log = EntrustOthersDTO.builder().operateUserId(operator.getUserId()).operateUsername(operator.getName())
                .operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC))
                .beforeInterviwerMobile(interviewInfo.getInterviewerMobile())
                .beforeInterviwerName(interviewInfo.getInterviewerName())
                .afterInterviwerMobile(enterpriseUserDO.getMobile())
                .afterInterviwerName(enterpriseUserDO.getName()).build();
        logService.recordBizLog(operator,interviewInfo.getPartnerLineId(),OperateTypeEnum.ENTRUST_OTHERS,log);
    }

    /**
     * PC端修改面试时间，和小程序端逻辑不一致，PC端修改需要修改日程信息
     * @param request
     * @throws ApiException
     */
    @Override
    public void modifyInterviewTime(ModifyInterviewTimeReq request) throws ApiException {
        //只有房间状态是待开放才可以修改时间
//        Integer roomStatus = hyPartnerInterviewPlanMapper.getRoomStatus(request.getInterviewPlanId());
//        if (!roomStatus.equals(RoomStatus.WAIT_FOR_OPEN.getCode())) {
//            throw new ApiException(ErrorCodeEnum.ROOM_STATUS_ERROR);
//        }
        InterviewVO interviewInfo = hyPartnerInterviewPlanMapper.getInterviewInfo(request.getInterviewPlanId());
        //如果面试信息为空，抛出异常
        if (interviewInfo == null) {
            throw new ApiException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
        }
        if(RoomStatus.WAIT_FOR_OPEN.getCode() != Integer.parseInt(interviewInfo.getRoomStatus())){
            throw new ApiException(ErrorCodeEnum.ROOM_STATUS_ERROR);
        }
        HyPartnerInterviewPlanDO record = new HyPartnerInterviewPlanDO();
        if(StringUtils.isNotEmpty(interviewInfo.getFeishuCalendarId())&&StringUtils.isNotEmpty(interviewInfo.getFeishuScheduleId())) {
            //1.原面试官日程删除
            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);
            }
            //2.新面试官日程新增
            CreateCalendarEventDTO createCalendarEventDTO = new CreateCalendarEventDTO();
            createCalendarEventDTO.setStartTime(DateUtil.parse(request.getNewStartBookingTime()).getTime());
            createCalendarEventDTO.setEndTime(DateUtil.parse(request.getNewEndBookingTime()).getTime());
            createCalendarEventDTO.setUserId(interviewInfo.getInterviewerId());
            createCalendarEventDTO.setJoinUserIds(Arrays.asList(interviewInfo.getInterviewerId()));
            createCalendarEventDTO.setSummary(generateInterviewTitle(interviewInfo.getPartnerLineId()));
            UserCalendarsEventDTO userCalendarEvent = isvHttpRequest.createUserCalendarEvent(createCalendarEventDTO);
            if (userCalendarEvent == null) {
                throw new ApiException(ErrorCodeEnum.CREATE_CALENDAR_EVENT_FAIL);
            }
            record.setFeishuCalendarId(userCalendarEvent.getCalendarId());
            record.setFeishuScheduleId(userCalendarEvent.getEventId());
        }

        record.setId(Long.valueOf(request.getInterviewPlanId()));
        record.setStartTime(Convert.toDate(request.getNewStartBookingTime()));
        record.setInterviewDate(Convert.toDate(request.getNewStartBookingTime()));
        record.setEndTime(Convert.toDate(request.getNewEndBookingTime()));
        record.setUpdateTime(new Date());
        hyPartnerInterviewPlanMapper.updateByPrimaryKeySelective(record);

        //更新面试信息
        HyPartnerInterviewDO hyPartnerInterviewDO = new HyPartnerInterviewDO();
        hyPartnerInterviewDO.setInterviewPlanId(Long.valueOf(request.getInterviewPlanId()));
        hyPartnerInterviewDO.setInterviewer(interviewInfo.getInterviewerId());
        hyPartnerInterviewDO.setUpdateTime(new Date());
        hyPartnerInterviewMapper.updateByPrimaryKeySelective(hyPartnerInterviewDO);

        //记录日志
        LoginUserInfo operator = CurrentUserHolder.getUser();
        ModifyInterviewTimeDTO log = ModifyInterviewTimeDTO.builder().mobile(operator.getMobile()).operateUserId(operator.getUserId()).operateUsername(operator.getName())
                .operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC))
                .beforeInterviewTime(interviewInfo.getStartTime()).afterInterviewTime(request.getNewStartBookingTime()).build();
        logService.recordBizLog(operator,interviewInfo.getPartnerLineId(),OperateTypeEnum.MODIFY_INTERVIEW_TIME,log);
    }

    @Override
    public void finishInterview(FinishInterviewReq request) throws ApiException {
        InterviewVO interviewInfo = hyPartnerInterviewPlanMapper.getInterviewInfo(request.getInterviewPlanId());
        //如果面试信息为空，抛出异常
        if (interviewInfo == null) {
            throw new ApiException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
        }
        Date now = new Date();
        //更新面试计划信息
        HyPartnerInterviewPlanDO record = new HyPartnerInterviewPlanDO();
        record.setId(Long.valueOf(request.getInterviewPlanId()));
        record.setRoomStatus(RoomStatus.CLOSED.getCode());
        record.setUpdateTime(now);
        record.setActualEndTime(now);
        hyPartnerInterviewPlanMapper.updateByPrimaryKeySelective(record);

        //更新面试信息
        HyPartnerInterviewDO hyPartnerInterviewDO = new HyPartnerInterviewDO();
        hyPartnerInterviewDO.setInterviewPlanId(Long.valueOf(interviewInfo.getInterviewPlanId()));
        interviewDAO.updateInterviewWorkflowStatus(interviewInfo.getInterviewPlanId(), WorkflowStatusEnum.INTERVIEW_4);
//        hyPartnerInterviewDO.setStatus(Integer.parseInt(WorkflowStatusEnum.INTERVIEW_4.getCode()));
        hyPartnerInterviewDO.setUpdateTime(now);
        hyPartnerInterviewMapper.updateByPrimaryKeySelective(hyPartnerInterviewDO);

        //记录日志
        LoginUserInfo operator = CurrentUserHolder.getUser();
        LogBasicDTO log = LogBasicDTO.builder().mobile(operator.getMobile()).operateUserId(operator.getUserId()).operateUsername(operator.getName()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC)).build();
        logService.recordBizLog(operator,interviewInfo.getPartnerLineId(),OperateTypeEnum.FINISH_INTERVIEW,log);
    }

    /**
     * 进入面试间的方法
     * 修改一些面试状态
     * 最后返回 userSign 用于进入腾讯云音视频房间
     *
     * @return userSign 进入视频所需签名
     */
    @Override
    @Transactional
    public EnterInterviewVO enterInterviewRoom(EnterInterviewDto dto) throws ApiException {
        try {
            //房间状态
            Integer roomStatus = hyPartnerInterviewPlanMapper.getRoomStatus(dto.getInterviewPlanId());
            //面试流程状态
            String status = hyPartnerInterviewMapper.getStatus(dto.getInterviewPlanId());
            //如果面试间状态是 0 待开放或者面试流程状态是 2 待面试，就不让进
            //再判断时间是否是正确的时间
            if (roomStatus.equals(RoomStatus.WAIT_FOR_OPEN.getCode()) || WorkflowStatusEnum.INTERVIEW_2.getCode().equals(status)) {
                HyPartnerInterviewPlanDO interviewPlan = hyPartnerInterviewPlanMapper.getInterviewPlanById(dto.getInterviewPlanId());
                //面试预期开始时间
                DateTime exceptTime = DateUtil.offsetMinute(interviewPlan.getStartTime(), -5);
                //面试结束时间
                DateTime endTime = DateUtil.parseDateTime(DateUtil.formatDateTime(interviewPlan.getEndTime()));
                DateTime now = DateUtil.date();
                //如果当前时间在预期开始时间和结束时间之间
                //修改面试状态和房间状态（修改房间状态在后面 hyPartnerInterviewPlanDO 中一并修改）
                if (exceptTime.isBefore(now) && now.isBefore(endTime)) {
                    //1. 将面试状态改为 --> 2 已开始
                    interviewDAO.updateInterviewWorkflowStatus(dto.getInterviewPlanId(), WorkflowStatusEnum.INTERVIEW_3);
                    //hyPartnerInterviewDO.setStatus(Integer.parseInt(WorkflowStatusEnum.INTERVIEW_3.getCode()));
                } else {
                    throw new ApiException(ErrorCodeEnum.ROOM_STATUS_ERROR);
                }
            }
            HyPartnerInterviewDO hyPartnerInterviewDO = new HyPartnerInterviewDO();
            hyPartnerInterviewDO.setInterviewPlanId(Long.parseLong(dto.getInterviewPlanId()));
            //2. 修改加盟商或面试官进入面试时间
            //加盟商
            if (dto.getUserType().equals(2)) {
                hyPartnerInterviewDO.setPartnerEnterTime(DateUtil.date());
            } else if (dto.getUserType().equals(1)) {
                hyPartnerInterviewDO.setInterviewerEnterTime(DateUtil.date());
            }
            //更新
            hyPartnerInterviewMapper.updateByPrimaryKeySelective(hyPartnerInterviewDO);
            HyPartnerInterviewPlanDO hyPartnerInterviewPlanDO = new HyPartnerInterviewPlanDO();
            hyPartnerInterviewPlanDO.setId(Long.parseLong(dto.getInterviewPlanId()));
            //修改面试房间状态
            hyPartnerInterviewPlanDO.setRoomStatus(RoomStatus.OPEN.getCode());
            //3. TODO（待确认） 修改面试实际开始时间，以第一个人进来的时间为准，后续不再修改
            hyPartnerInterviewPlanMapper.updateActualStartTime(hyPartnerInterviewPlanDO.getId(), DateUtil.now());
            //4. 加盟商如果进入了，就修改面试计划表 is_partner_interview 字段
            if (dto.getUserType().equals(2)) {
                hyPartnerInterviewPlanDO.setIsPartnerInterview(1);
            }
            hyPartnerInterviewPlanMapper.updateByPrimaryKeySelective(hyPartnerInterviewPlanDO);
            //5. 查询对应的面试官id、姓名及加盟商姓名
            EnterInterviewVO vo = hyPartnerInterviewMapper.getInterviewerByInterviewPlanId(dto.getInterviewPlanId());
            //6. 生成 userSign
            String userSig = TRTCUtils.genUserSig(sdkAppId, key, dto.getUserId());
            vo.setUserSign(userSig);
            return vo;
        } catch (ApiException apiException) {
            throw apiException;
        } catch (Exception e) {
            throw new ApiException(ErrorCodeEnum.INTERVIEW_ENTER_FAIL);
        }
    }

    @Override
    @Transactional
    public CreateAppointmentVO createAppointment(CreateAppointmentReq request) throws ApiException {
        if(request.getPartnerLineId() == null || request.getPartnerLineId()<=0){
            throw new ApiException(ErrorCodeEnum.INTERVIEW_LINE_ID_IS_NULL);
        }
        HyPartnerInterviewPlanDO hyPartnerInterviewPlanDO = new HyPartnerInterviewPlanDO();
        hyPartnerInterviewPlanDO.setPartnerLineId(request.getPartnerLineId());
        hyPartnerInterviewPlanDO.setDeleted(false);
        List<HyPartnerInterviewPlanDO> hyPartnerInterviewPlanDOS = hyPartnerInterviewPlanMapper.selectBySelective(hyPartnerInterviewPlanDO);
        if(CollectionUtils.isNotEmpty(hyPartnerInterviewPlanDOS)&&hyPartnerInterviewPlanDOS.get(0).getId()!=null){
            throw new ApiException(ErrorCodeEnum.INTERVIEW_PLAN_ALREADY_EXIST);
        }
        String interviewrId = request.getInterviewerId();
        if(StringUtils.isEmpty(interviewrId)){
            interviewrId = getInterviewerByPartner(request.getPartnerId(),String.valueOf(request.getPartnerLineId()));
        }
        CreateAppointmentVO vo = new CreateAppointmentVO();
        //1.创建面试计划
        HyPartnerInterviewPlanDO record = new HyPartnerInterviewPlanDO();
        String startBookingTime = request.getStartBookingTime();
        String startDate = startBookingTime.substring(0, 10);
        record.setInterviewDate(Convert.toDate(startDate));
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        record.setStartTime(Convert.toDate(request.getStartBookingTime()));
        record.setEndTime(Convert.toDate(request.getEndBookingTime()));
        record.setPartnerId(request.getPartnerId());
        record.setPartnerLineId(request.getPartnerLineId());
        record.setInterviewer(interviewrId);
        record.setIsPartnerInterview(0);
        //生成房间号
        record.setRoomId(StringUtil.generateRoomId(startBookingTime));
        record.setRoomStatus(RoomStatus.WAIT_FOR_OPEN.getCode());
        record.setDeleted(false);
        record.setApplicationApproved(0);
        hyPartnerInterviewPlanMapper.insertSelective(record);

        List<HyPartnerInterviewPlanDO> interviewPlanDOS = hyPartnerInterviewPlanMapper.selectBySelective(hyPartnerInterviewPlanDO);
        if(CollectionUtils.isEmpty(interviewPlanDOS)){
            throw new ApiException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
        }
        Long interviewPlanId = interviewPlanDOS.get(0).getId();
        vo.setInterviewPlanId(String.valueOf(interviewPlanId));

        //2.创建面试信息
        HyPartnerInterviewDO hyPartnerInterviewDO = new HyPartnerInterviewDO();
        hyPartnerInterviewDO.setInterviewPlanId(interviewPlanId);
        hyPartnerInterviewDO.setPartnerLineId(request.getPartnerLineId());
        hyPartnerInterviewDO.setPartnerId(request.getPartnerId());
        hyPartnerInterviewDO.setInterviewer(interviewrId);
        hyPartnerInterviewDO.setCreateTime(new Date());
        hyPartnerInterviewDO.setUpdateTime(new Date());
        hyPartnerInterviewDO.setStatus(Integer.valueOf(WorkflowStatusEnum.RESERVATION_1.getCode()));
        hyPartnerInterviewDO.setDeleted(false);
        hyPartnerInterviewMapper.insertSelective(hyPartnerInterviewDO);

        //修改线索状态
        HyPartnerLineInfoDO hyPartnerLineDO = new HyPartnerLineInfoDO();
        hyPartnerLineDO.setId(request.getPartnerLineId());
        hyPartnerLineDO.setWorkflowStatus(WorkflowStatusEnum.RESERVATION_1.getCode());
        hyPartnerLineDO.setUpdateTime(new Date());
        hyPartnerLineInfoMapper.updateByPrimaryKeySelective(hyPartnerLineDO);

        //异步发送飞书信息给面试官
        InterviewVO interviewVO = hyPartnerInterviewPlanMapper.getInterviewInfo(String.valueOf(interviewPlanId));
        List<String> userIds = new ArrayList<>();
        userIds.add(interviewrId);
        SendCardMessageDTO sendCardMessageDTO = new SendCardMessageDTO();
        sendCardMessageDTO.setUserIds(userIds);
        sendCardMessageDTO.setMessageType(MessageTypeEnum.SCHEDULE_REMINDER);
        sendCardMessageDTO.setMessageUrl(linkUrl);
        sendCardMessageDTO.setTitle("面试预约申请");
        sendCardMessageDTO.setContent(generateFeiShuInterviewMsg(interviewVO.getPartnerName(), interviewVO.getPartnerMobile(), interviewVO.getStartTime()));
        isvHttpRequest.sendFeiShuCardMessage(sendCardMessageDTO);

        //记录日志
        PartnerUserInfoVO operator = PartnerUserHolder.getUser();
        LogBasicDTO log = LogBasicDTO.builder().mobile(operator.getMobile()).operateUserId(operator.getPartnerId()).operateUsername(operator.getUsername()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC)).mobile(operator.getMobile()).build();
        logService.recordPartnerBizLog(operator,interviewVO.getPartnerLineId(),OperateTypeEnum.INTERVIEW_APPOINTMENT,log);

        return vo;
    }

    @Override
    @Transactional
    public void approveAppointment(ApproveAppointmentReq request) throws ApiException {

        //查询面试计划信息
        InterviewVO interviewVO = hyPartnerInterviewPlanMapper.getInterviewInfo(request.getInterviewPlanId());
        //如果面试计划不存在，抛出异常
        if (interviewVO == null||StringUtil.isEmpty(interviewVO.getInterviewPlanId())) {
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
        }
        HyPartnerBaseInfoDO partnerBaseInfo = hyPartnerBaseInfoMapper.getByPartnerLineId(interviewVO.getPartnerLineId());
        if(partnerBaseInfo == null){
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_PARTNER_NOT_EXIST);
        }

        List<UserFreeBusyInfoDTO> userFreeBusyInfoList = isvHttpRequest.getFreeBusyList(request.getInterviewerId(), DateUtil.parse(interviewVO.getStartTime()).getTime(), DateUtil.parse(interviewVO.getEndTime()).getTime());
        if (CollectionUtils.isNotEmpty(userFreeBusyInfoList)) {
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_INTERVIEW_TIME_IS_UNUSABLE,partnerBaseInfo.getUsername(),partnerBaseInfo.getMobile());
        }
        //创建日程信息
        CreateCalendarEventDTO createCalendarEventDTO = new CreateCalendarEventDTO();
        createCalendarEventDTO.setStartTime(DateUtil.parse(interviewVO.getStartTime()).getTime());
        createCalendarEventDTO.setEndTime(DateUtil.parse(interviewVO.getEndTime()).getTime());
        createCalendarEventDTO.setUserId(request.getInterviewerId());
        createCalendarEventDTO.setJoinUserIds(Arrays.asList(request.getInterviewerId()));
        createCalendarEventDTO.setSummary(generateInterviewTitle(request.getPartnerLineId()));
        UserCalendarsEventDTO userCalendarEvent = isvHttpRequest.createUserCalendarEvent(createCalendarEventDTO);
        if (userCalendarEvent == null || StringUtil.isEmpty(userCalendarEvent.getEventId())) {
            throw new ServiceException(ErrorCodeEnum.CREATE_CALENDAR_EVENT_FAIL);
        }
        //更新面试计划信息
        HyPartnerInterviewPlanDO record = new HyPartnerInterviewPlanDO();
        record.setId(Long.valueOf(request.getInterviewPlanId()));
        record.setFeishuCalendarId(userCalendarEvent.getCalendarId());
        record.setFeishuScheduleId(userCalendarEvent.getEventId());
        record.setApplicationApproved(1);
        record.setUpdateTime(new Date());
        hyPartnerInterviewPlanMapper.updateByPrimaryKeySelective(record);

        //更新面试信息
        HyPartnerInterviewDO hyPartnerInterviewDO = new HyPartnerInterviewDO();
        hyPartnerInterviewDO.setId(Long.valueOf(interviewVO.getInterviewId()));
        //更新面试状态和线索子流程状态
        interviewDAO.updateInterviewWorkflowStatus(request.getInterviewPlanId(), WorkflowStatusEnum.INTERVIEW_2);
//        hyPartnerInterviewDO.setStatus(Integer.valueOf(WorkflowStatusEnum.INTERVIEW_2.getCode()));
        hyPartnerInterviewDO.setUpdateTime(new Date());
        hyPartnerInterviewMapper.updateByPrimaryKeySelective(hyPartnerInterviewDO);

        //更新线索状态
        HyPartnerLineInfoDO hyPartnerLineDO = new HyPartnerLineInfoDO();
        hyPartnerLineDO.setId(request.getPartnerLineId());
        hyPartnerLineDO.setWorkflowStage(WorkflowStageEnum.INTERVIEW.getCode());
//        hyPartnerLineDO.setWorkflowStatus(WorkflowStatusEnum.INTERVIEW_2.getCode());
        hyPartnerLineDO.setUpdateTime(new Date());
        hyPartnerLineInfoMapper.updateByPrimaryKeySelective(hyPartnerLineDO);
        //异步发送短信给加盟商
        InterviewSmsReq interviewSmsReq = new InterviewSmsReq();
        interviewSmsReq.setInterviewStartTime(DateUtil.format(DateUtil.parse(interviewVO.getStartTime()), DatePattern.NORM_DATETIME_MINUTE_PATTERN));
        smsService.sendSms(JSON.toJSONString(interviewSmsReq),templateCode, partnerBaseInfo.getMobile());

    }

    @Override
    @Transactional
    public void reInterview(ReInterviewReq request) throws ApiException {
        //查询面试计划信息
        InterviewVO interviewVO = hyPartnerInterviewPlanMapper.getInterviewInfo(request.getInterviewPlanId());
        //如果面试计划不存在，抛出异常
        if (interviewVO == null||StringUtil.isEmpty(interviewVO.getInterviewPlanId())) {
            throw new ServiceException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
        }
        rejectInterviewAndSuspendLine(Long.parseLong(interviewVO.getInterviewId()),Long.parseLong(request.getInterviewPlanId()),request.getCertifyFile());
        //更新线索状态
        HyPartnerLineInfoDO hyPartnerLineDO = new HyPartnerLineInfoDO();
        hyPartnerLineDO.setId(interviewVO.getPartnerLineId());
        hyPartnerLineDO.setWorkflowStage(WorkflowStageEnum.RESERVATION.getCode());
        hyPartnerLineDO.setWorkflowStatus(WorkflowStatusEnum.RESERVATION_0.getCode());
        hyPartnerLineDO.setUpdateTime(new Date());
        hyPartnerLineDO.setDeadline(CoolDateUtils.getDateFormatDay(new Date(),2));
        hyPartnerLineInfoMapper.updateByPrimaryKeySelective(hyPartnerLineDO);
        //记录日志
        LoginUserInfo operator = CurrentUserHolder.getUser();
        ReInterviewDTO log = ReInterviewDTO.builder().mobile(operator.getMobile()).operateUserId(operator.getUserId()).operateUsername(operator.getName()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC))
                .rejectRealReason(request.getReason()).certifyFile(request.getCertifyFile()).build();
        logService.recordBizLog(operator,interviewVO.getPartnerLineId(),OperateTypeEnum.REINTERVIEW,log);
    }

//    @Override
//    @Transactional
//    public void rejectInterview(RejectInterviewReq request) throws ApiException {
        //查询面试计划信息
//        InterviewVO interviewVO = hyPartnerInterviewPlanMapper.getInterviewInfo(request.getInterviewPlanId());
//        //如果面试计划不存在，抛出异常
//        if (interviewVO == null||StringUtil.isEmpty(interviewVO.getInterviewPlanId())) {
//            throw new ServiceException(ErrorCodeEnum.INTERVIEW_PLAN_NOT_EXIST);
//        }
//
//        rejectInterviewAndSuspendLine(Long.parseLong(request.getInterviewId()),Long.parseLong(request.getInterviewPlanId()),request.getCertifyFile())
//        //更新线索状态
//        CloseFollowRequest closeFollowRequest = new CloseFollowRequest();
//        closeFollowRequest.setRejectPublicReason(request.getRejectPublicReason());
//        closeFollowRequest.setRejectRealReason(request.getRejectRealReason());
//        closeFollowRequest.setLineId(Long.valueOf(request.getLineId()));
//        closeFollowRequest.setType("reject");
//        if(StringUtils.isNotEmpty(request.getCertifyFile())){
//            closeFollowRequest.setCertifyFile(Arrays.asList(request.getCertifyFile().split(",")));
//        }
//        hyPartnerLineInfoService.closeOrPassFollow(request.getOperatorId(),closeFollowRequest);
//    }

    @Override
    public String generateFeiShuInterviewMsg(String partnerName, String partnerMobile, String interviewTime){
        //"您有一个【面试预约申请】待处理，预约人【姓名】手机号【13xxxxxxxxx】，预约面试时间【YYYY年MM月DD日 hh:mm】，请及时处理】"
        StringBuffer sb = new StringBuffer();
        sb.append("您有一个【面试预约申请】待处理，预约人 ")
                .append(partnerName)
                .append(" 手机号 ")
                .append(partnerMobile)
                .append("，预约面试时间")
                .append(DateUtil.format(DateUtil.parse(interviewTime), "yyyy年MM月dd日 HH:mm"));
        return sb.toString();
    }
    @Override
    public String getInterviewerByPartner(String partnerId,String lineId){
        String interviewerId = null;
        if (StringUtils.isNotEmpty(partnerId) && StringUtils.isNotEmpty(lineId)) {
            //根据加盟商用户ID查询面试官ID
            HyPartnerInterviewPlanDO hyPartnerInterviewPlanDO = new HyPartnerInterviewPlanDO();
            hyPartnerInterviewPlanDO.setPartnerId(partnerId);
            hyPartnerInterviewPlanDO.setPartnerLineId(Long.valueOf(lineId));
            hyPartnerInterviewPlanDO.setDeleted(false);
            List<HyPartnerInterviewPlanDO> hyPartnerInterviewPlanDOS = hyPartnerInterviewPlanMapper.selectBySelective(hyPartnerInterviewPlanDO);
            //如果查询结果为空，则去线索中获取招商经理，面试官只有两个阶段，一个是在第一次申请时不存在面试安排直接取招商经理，第二个时面试信息中可修改面试官信息，这个时候以面试信息中为准
            if (CollectionUtils.isEmpty(hyPartnerInterviewPlanDOS)) {
                HyPartnerLineInfoDO hyPartnerLineInfoDO = hyPartnerLineInfoMapper.selectByPrimaryKeySelective(Long.valueOf(lineId));
                interviewerId = hyPartnerLineInfoDO.getInvestmentManager();
            }else {
                interviewerId = hyPartnerInterviewPlanDOS.get(0).getInterviewer();
            }
        }
        return interviewerId;
    }


    public String generateInterviewTitle(Long partnerLineId){
        HyPartnerBaseInfoDO partnerBaseInfo = hyPartnerBaseInfoMapper.getByPartnerLineId(partnerLineId);
        return "意向 "+partnerBaseInfo.getUsername()+" 线上面试";
    }

    //拒绝面试更新相关信息

    @Override
    public void rejectInterviewAndSuspendLine(Long iterviewId,Long interviewPlanId,String certifyFile){
        //更新面试信息
        HyPartnerInterviewDO hyPartnerInterviewDO = new HyPartnerInterviewDO();
        hyPartnerInterviewDO.setId(iterviewId);
        hyPartnerInterviewDO.setDeleted(true);
        hyPartnerInterviewDO.setUpdateTime(new Date());
        hyPartnerInterviewDO.setStatus(Integer.valueOf(WorkflowStatusEnum.INTERVIEW_7.getCode()));
        hyPartnerInterviewDO.setCertifyFile(certifyFile);
        hyPartnerInterviewMapper.updateByPrimaryKeySelective(hyPartnerInterviewDO);
        //更新面试计划信息
        HyPartnerInterviewPlanDO hyPartnerInterviewPlanDO = new HyPartnerInterviewPlanDO();
        hyPartnerInterviewPlanDO.setId(interviewPlanId);
        hyPartnerInterviewPlanDO.setDeleted(true);
        hyPartnerInterviewPlanDO.setUpdateTime(new Date());
        hyPartnerInterviewPlanMapper.updateByPrimaryKeySelective(hyPartnerInterviewPlanDO);
    }

}
