package com.cool.store.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.constants.RedisConstant;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.dao.*;
import com.cool.store.dto.buser.UserPositionAndUserScopeDTO;
import com.cool.store.dto.log.*;
import com.cool.store.dto.partner.*;
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.request.*;
import com.cool.store.service.*;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.StringUtil;
import com.cool.store.vo.*;
import com.cool.store.vo.interview.InterviewVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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 org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author suzhuhong
 * @Date 2023/6/9 10:30
 * @Version 1.0
 */
@Service
@Slf4j
public class HyPartnerLineInfoServiceImpl implements HyPartnerLineInfoService {

    @Resource
    HyPartnerLineInfoDAO hyPartnerLineInfoDAO;
    @Resource
    HyPartnerUserInfoDAO hyPartnerUserInfoDAO;
    @Resource
    EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private RedisUtilPool redisUtilPool;
    @Resource
    HyOpenAreaInfoDAO hyOpenAreaInfoDAO;
    @Resource
    EnterpriseUserService enterpriseUserService;
    @Resource
    AliyunService aliyunService;
    @Resource
    HyPartnerBaseInfoDAO hyPartnerBaseInfoDAO;
    @Resource
    HyIntendDevMappingDAO hyIntendDevMappingDAO;
    @Resource
    HyIntendDevZoneInfoDAO hyIntendDevZoneInfoDAO;
    @Resource
    InterviewService interviewService;
    @Resource
    HyPartnerInterviewPlanDAO hyPartnerInterviewPlanDAO;
    @Resource
    private HyPartnerBaseInfoService hyPartnerBaseInfoService;
    @Resource
    WorkFlowService workFlowService;
    @Resource
    HyPartnerTaskInfoLogDAO hyPartnerTaskInfoLogDAO;
    @Resource
    HyPhoneLocationService hyPhoneLocationService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private SmsService smsService;

    @Override
    public StageCountVO selectStagePendingCount(String userId) {
        StageCountDTO stageCountDTO = hyPartnerLineInfoDAO.selectStagePendingCount(userId);
        return stageCountDTOToVo(stageCountDTO);
    }

    @Override
    public StageCountVO selectStageFollowCount(String userId) {
        StageCountDTO stageCountDTO = hyPartnerLineInfoDAO.selectStageFollowCount(userId);
        return stageCountDTOToVo(stageCountDTO);
    }

    @Override
    public PartnerLineInfoAndBaseInfoVO selectPartnerLineInfoAndBaseInfo(Long lineId) {
        PartnerLineInfoAndBaseInfoDTO partnerLineInfoAndBaseInfoDTO = hyPartnerLineInfoDAO.selectPartnerLineInfoAndBaseInfo(lineId);
        if (partnerLineInfoAndBaseInfoDTO==null){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        PartnerLineInfoAndBaseInfoVO partnerLineInfoAndBaseInfoVO = convertPartnerLineInfoAndBaseInfoDTOToVo(partnerLineInfoAndBaseInfoDTO);
        List<String> userIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(partnerLineInfoAndBaseInfoDTO.getPassUserId())){
            userIds.add(partnerLineInfoAndBaseInfoDTO.getPassUserId());
        }
        if (StringUtils.isNotEmpty(partnerLineInfoAndBaseInfoVO.getInvestmentManager())){
            userIds.add(partnerLineInfoAndBaseInfoVO.getInvestmentManager());
        }
        if (StringUtils.isNotEmpty(partnerLineInfoAndBaseInfoVO.getDevelopmentDirector())){
            userIds.add(partnerLineInfoAndBaseInfoVO.getDevelopmentDirector());
        }

        List<EnterpriseUserDO> userList = enterpriseUserDAO.getUserInfoByUserIds(userIds);
        Map<String, EnterpriseUserDO> userDOMap = userList.stream().collect(Collectors.toMap(EnterpriseUserDO::getUserId, data -> data));
        partnerLineInfoAndBaseInfoVO.setPassUserName(userDOMap.getOrDefault(partnerLineInfoAndBaseInfoVO.getPassUserId(),new EnterpriseUserDO()).getName());
        partnerLineInfoAndBaseInfoVO.setPassUserMobile(userDOMap.getOrDefault(partnerLineInfoAndBaseInfoVO.getPassUserId(),new EnterpriseUserDO()).getMobile());
        partnerLineInfoAndBaseInfoVO.setInvestmentManagerName(userDOMap.getOrDefault(partnerLineInfoAndBaseInfoVO.getInvestmentManager(),new EnterpriseUserDO()).getName());
        partnerLineInfoAndBaseInfoVO.setInvestmentManagerPhone(userDOMap.getOrDefault(partnerLineInfoAndBaseInfoVO.getInvestmentManager(),new EnterpriseUserDO()).getMobile());
        partnerLineInfoAndBaseInfoVO.setDevelopmentDirectorName(userDOMap.getOrDefault(partnerLineInfoAndBaseInfoVO.getDevelopmentDirector(),new EnterpriseUserDO()).getName());
        partnerLineInfoAndBaseInfoVO.setDevelopmentDirectorMobile(userDOMap.getOrDefault(partnerLineInfoAndBaseInfoVO.getDevelopmentDirector(),new EnterpriseUserDO()).getMobile());
        if (StringUtils.isNotEmpty(partnerLineInfoAndBaseInfoDTO.getWantShopArea())){
        HyOpenAreaInfoDO hyOpenAreaInfoDO = hyOpenAreaInfoDAO.selectById(Long.valueOf(partnerLineInfoAndBaseInfoDTO.getWantShopArea()));
            partnerLineInfoAndBaseInfoVO.setWantShopAreaName(hyOpenAreaInfoDO.getAreaPath().replace("/"," "));
        }
        return partnerLineInfoAndBaseInfoVO;
    }

    @Override
    public PageInfo<PartnerLineInfoVO> lastMonthCloseLine(String userId, Integer pageSize, Integer pageNumber) {
        PageHelper.startPage(pageNumber,pageSize);
        String lastMonthTodayDate = DateUtil.format(CoolDateUtils.getDateBefore(new Date(),-30), CoolDateUtils.DATE_FORMAT_SEC);
        PageInfo hyPartnerLineInfoDOPageInfo = new PageInfo(hyPartnerLineInfoDAO.lastMonthCloseLine(userId, lastMonthTodayDate));
        List<HyPartnerLineInfoDO> list = hyPartnerLineInfoDOPageInfo.getList();
        List<String> closeUserIds = list.stream().filter(o -> Objects.nonNull(o.getCloseUserId())).map(HyPartnerLineInfoDO::getCloseUserId).distinct().collect(Collectors.toList());
        Map<String, String> userNamePhoneMap = enterpriseUserDAO.getUserNameAndMobile(closeUserIds);
        List<String> partnerIdList = list.stream().map(HyPartnerLineInfoDO::getPartnerId).collect(Collectors.toList());
        List<HyPartnerUserInfoDO> hyPartnerList = hyPartnerUserInfoDAO.selectByPartnerIds(partnerIdList);
        Map<String, HyPartnerUserInfoDO> partnerMap = hyPartnerList.stream().collect(Collectors.toMap(HyPartnerUserInfoDO::getPartnerId, data->data));
        List<PartnerLineInfoVO> resultList = PartnerLineInfoVO.convertList(list, userNamePhoneMap, partnerMap);
        hyPartnerLineInfoDOPageInfo.setList(resultList);
        return hyPartnerLineInfoDOPageInfo;
    }

    @Override
    public Boolean transferInvestmentManager(LoginUserInfo user, TransferInvestmentManagerRequest request) throws ApiException {
        if (StringUtil.isBlank(request.getUserId())||request.getLineId()==null){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        HyPartnerLineInfoDO hyPartnerLineInfoDO = hyPartnerLineInfoDAO.selectByPrimaryKeySelective(request.getLineId());
        hyPartnerLineInfoDAO.updateInvestmentManager(request.getUserId(), Arrays.asList(request.getLineId()));

        List<String> userIdList = new ArrayList<>();
        userIdList.add(request.getUserId());
        if (StringUtils.isNotEmpty(hyPartnerLineInfoDO.getInvestmentManager())){
            userIdList.add(hyPartnerLineInfoDO.getInvestmentManager());
        }
        List<EnterpriseUserDO> userList = enterpriseUserDAO.getUserInfoByUserIds(userIdList);
        Map<String, EnterpriseUserDO> userDOMap = userList.stream().collect(Collectors.toMap(EnterpriseUserDO::getUserId, data -> data));

        //更新面试官
        if (WorkflowStageEnum.INTERVIEW.getCode().equals(hyPartnerLineInfoDO.getWorkflowStage())
            && WorkflowStatusEnum.INTERVIEW_2.getCode().equals(hyPartnerLineInfoDO.getWorkflowStatus())){
            workFlowService.transferInvestmentManager(WorkflowStageEnum.getWorkflowStageByCode(hyPartnerLineInfoDO.getWorkflowStage()),request);
        }
        //发送飞书工作通知
        HyPartnerBaseInfoDO hyPartnerBaseInfoDO = hyPartnerBaseInfoDAO.getByPartnerLineId(request.getLineId());
        noticeService.sendFeiShuNotice(FeiShuNoticeMsgEnum.TRANS_INVESTMENT_MANAGER,Arrays.asList(request.getUserId()),DateUtil.formatDateTime(new Date()),hyPartnerBaseInfoDO.getUsername(),hyPartnerBaseInfoDO.getMobile());

        //添加日志
        LineLogInfo lineLogInfo = new LineLogInfo(hyPartnerLineInfoDO.getPartnerId(), hyPartnerLineInfoDO.getId(), user.getUserId(),
                user.getName(), OperateTypeEnum.TRANSFER_INVESTMENT_MANAGER,
                WorkflowStageEnum.getWorkflowStageByCode(hyPartnerLineInfoDO.getWorkflowStage()),
                hyPartnerLineInfoDO.getWorkflowStatus(), "");
        TransferInvestmentManagerLogDTO logDTO = TransferInvestmentManagerLogDTO.builder().operateUserId(user.getUserId()).operateUsername(user.getName())
                .beforeInvestmentManagerUsername(userDOMap.getOrDefault(hyPartnerLineInfoDO.getInvestmentManager(),new EnterpriseUserDO()).getName())
                .beforeInvestmentManagerMobile(userDOMap.getOrDefault(hyPartnerLineInfoDO.getInvestmentManager(),new EnterpriseUserDO()).getMobile())
                .afterInvestmentManagerMobile(userDOMap.getOrDefault(request.getUserId(),new EnterpriseUserDO()).getMobile())
                .afterInvestmentManagerUsername(userDOMap.getOrDefault(request.getUserId(),new EnterpriseUserDO()).getName())
                .mobile(user.getMobile()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC_2)).build();
        lineLogInfo.setData(logDTO);
        hyPartnerTaskInfoLogDAO.addOperateLog(lineLogInfo);
        return Boolean.TRUE;
    }

    @Override
    public Boolean allocationInvestmentManager(LoginUserInfo user, List<Long> lineIdList) {
        if (user==null|| CollectionUtils.isEmpty(lineIdList)){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        //加盟上线索集合
        List<HyPartnerLineInfoDO> partnerLineInfoList= hyPartnerLineInfoDAO.getLineListByLineIds(lineIdList);
        //过滤出已结束的线索 这块线索需要重新生成新的线索
        List<HyPartnerLineInfoDO> closeLineList  = partnerLineInfoList.stream().filter(x -> x.getCloseTime() != null).collect(Collectors.toList());
        List<Long> closeLineIdList = closeLineList.stream().map(HyPartnerLineInfoDO::getId).collect(Collectors.toList());

        //已结束的线索 需要重新生成一条新的线索
        List<HyPartnerLineInfoDO> list = new ArrayList<>();
        closeLineList.stream().forEach(x->{
            HyPartnerLineInfoDO hyPartnerLineInfoDO = new HyPartnerLineInfoDO();
            hyPartnerLineInfoDO.setPartnerId(x.getPartnerId());
            hyPartnerLineInfoDO.setInvestmentManager(user.getUserId());
            hyPartnerLineInfoDO.setWorkflowStage(WorkflowStageEnum.INTENT.getCode());
            hyPartnerLineInfoDO.setWorkflowStatus(WorkflowStatusEnum.INTENT_0.getCode());
            hyPartnerLineInfoDO.setLineStatus(1);
            list.add(hyPartnerLineInfoDO);
        });
        hyPartnerLineInfoDAO.batchInsert(list);
        List<HyPartnerBaseInfoDO> hyPartnerBaseInfoDOS = new ArrayList<>();
        list.forEach(x->{
            HyPartnerBaseInfoDO newHyPartnerBaseInfoDO = new HyPartnerBaseInfoDO();
            newHyPartnerBaseInfoDO.setPartnerId(x.getPartnerId());
            newHyPartnerBaseInfoDO.setPartnerLineId(x.getId());
            hyPartnerBaseInfoDOS.add(newHyPartnerBaseInfoDO);
        });
        hyPartnerBaseInfoDAO.batchInsert(hyPartnerBaseInfoDOS);
        //将老的线索置为删除状态
        hyPartnerLineInfoDAO.batchDeleted(closeLineIdList);
        //没有结束的线索直接分配招商经理
        List<HyPartnerLineInfoDO> otherLineList  = partnerLineInfoList.stream().filter(x -> x.getCloseTime() == null).collect(Collectors.toList());
        List<Long> otherLineIdList = otherLineList.stream().map(HyPartnerLineInfoDO::getId).collect(Collectors.toList());
        hyPartnerLineInfoDAO.updateInvestmentManager(user.getUserId(), otherLineIdList);
        //添加日志
        partnerLineInfoList.forEach(x->{
            //给招商经理发送飞书工作通知
            List<String> userIdList = new ArrayList<>();
            userIdList.add(user.getUserId());
            HyPartnerBaseInfoDO hyPartnerBaseInfoDO = hyPartnerBaseInfoDAO.getByPartnerLineId(x.getId());

            noticeService.sendFeiShuNotice(FeiShuNoticeMsgEnum.ALLOCATION_INVESTMENT_MANAGER,userIdList,DateUtil.formatDateTime(new Date()),hyPartnerBaseInfoDO.getUsername(),hyPartnerBaseInfoDO.getMobile());

            LineLogInfo lineLogInfo = new LineLogInfo(x.getPartnerId(), x.getId(), user.getUserId(),
                    user.getName(), OperateTypeEnum.ALLOCATION_INVESTMENT_MANAGER,
                    WorkflowStageEnum.getWorkflowStageByCode(x.getWorkflowStage()),
                    x.getWorkflowStatus(), "");
            AllocationInvestmentManagerLogDTO logDTO = AllocationInvestmentManagerLogDTO.builder().allocationUserId(user.getUserId()).allocationUsername(user.getName())
                    .mobile(user.getMobile()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC_2)).build();
            lineLogInfo.setData(logDTO);
            hyPartnerTaskInfoLogDAO.addOperateLog(lineLogInfo);
        });
        return Boolean.TRUE;
    }

    @Override
    public PageInfo<BlackListVO> getBlackList(LineRequest LineRequest) {
        String intentAreaName = getIntentAreaName(LineRequest.getIntentArea());
        PageHelper.startPage(LineRequest.getPageNum(),LineRequest.getPageSize());
        PageInfo blackListDTOPageInfo = new PageInfo(hyPartnerLineInfoDAO.getBlackList(LineRequest.getUserNameKeyword(), LineRequest.getPhoneKeyword(),intentAreaName, LineRequest.getAcceptAdjustType()));
        List<PartnerBlackListDTO> list = blackListDTOPageInfo.getList();
        List<String> closeUserIdList = list.stream().map(PartnerBlackListDTO::getCloseUserId).collect(Collectors.toList());
        Map<String, String> userPhoneMap = enterpriseUserDAO.getUserNameAndMobile(closeUserIdList);
        List<BlackListVO> result = new ArrayList<>();
        list.stream().forEach(x->{
            BlackListVO blackListVO = convertPartnerBlackListDTOToVo(x);
            blackListVO.setCloseUserPhone(userPhoneMap.get(x.getCloseUserId()));
            blackListVO.setCloseUserName(userPhoneMap.get(x.getCloseUserId()));
            result.add(blackListVO);
        });
        blackListDTOPageInfo.setList(result);
        return blackListDTOPageInfo;
    }

    @Override
    public Boolean joinBlackList(LoginUserInfo user, Long lineId, Integer status, String joinReason) throws ApiException {
        if (lineId==null){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        HyPartnerLineInfoDO line = hyPartnerLineInfoDAO.selectByPrimaryKeySelective(lineId);
        Integer lineStatus = line.getLineStatus();
        //加入黑名单 阶段回到第一步待提交状态
        HyPartnerLineInfoDO hyPartnerLineInfoDO = new HyPartnerLineInfoDO();
        hyPartnerLineInfoDO.setId(lineId);
        hyPartnerLineInfoDO.setLineStatus(status);
        hyPartnerLineInfoDO.setJoinBlackReason(joinReason);
        hyPartnerLineInfoDO.setRejectRealReason(joinReason);
        hyPartnerLineInfoDO.setCloseTime(new Date());
        hyPartnerLineInfoDO.setCloseUserId(user.getUserId());
        hyPartnerLineInfoDAO.updateByPrimaryKeySelective(hyPartnerLineInfoDO);

        //公海线索不需要处理子流程线索
        if (!LineStatusEnum.PUBLIC_SEAS.getCode().equals(lineStatus)){
            CloseFollowRequest closeFollowRequest = new CloseFollowRequest();
            closeFollowRequest.setLineId(lineId);
            closeFollowRequest.setRejectRealReason(joinReason);
            workFlowService.endProcess(WorkflowStageEnum.getWorkflowStageByCode(line.getWorkflowStage()),closeFollowRequest);
        }

        //添加日志
        LineLogInfo lineLogInfo = new LineLogInfo(line.getPartnerId(), line.getId(), user.getUserId(),
                user.getName(), OperateTypeEnum.ADD_BLACKLIST,
                WorkflowStageEnum.getWorkflowStageByCode(line.getWorkflowStage()),
                line.getWorkflowStatus(), "");
        BlackListLogDTO logDTO = BlackListLogDTO.builder().operateUserId(user.getUserId()).reason(joinReason).operateUsername(user.getName())
                .mobile(user.getMobile()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC_2)).build();
        lineLogInfo.setData(logDTO);
        hyPartnerTaskInfoLogDAO.addOperateLog(lineLogInfo);

        return  Boolean.TRUE;
    }

    @Override
    public Boolean removeBlackList(LoginUserInfo user,Long lineId, Integer status, String removeReason) {
        //移除黑名单  黑名单线索置为删除状态 新增一条线索
        if (lineId==null){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        HyPartnerLineInfoDO hyPartnerLineInfo = hyPartnerLineInfoDAO.selectByPrimaryKeySelective(lineId);
        HyPartnerLineInfoDO hyPartnerLineInfoDO = new HyPartnerLineInfoDO();
        hyPartnerLineInfoDO.setId(lineId);
        hyPartnerLineInfoDO.setRemoveBlackReason(removeReason);
        hyPartnerLineInfoDO.setDeleted(Boolean.TRUE);
        hyPartnerLineInfoDAO.updateByPrimaryKeySelective(hyPartnerLineInfoDO);


        HyPartnerLineInfoDO newHyPartnerLineInfoDO = new HyPartnerLineInfoDO();
        newHyPartnerLineInfoDO.setPartnerId(hyPartnerLineInfo.getPartnerId());
        newHyPartnerLineInfoDO.setWorkflowStage(WorkflowStageEnum.INTENT.getCode());
        newHyPartnerLineInfoDO.setWorkflowStatus(WorkflowStatusEnum.INTENT_0.getCode());
        newHyPartnerLineInfoDO.setLineStatus(status);
        hyPartnerLineInfoDAO.insertSelective(newHyPartnerLineInfoDO);

        HyPartnerBaseInfoDO oldHyPartnerBaseInfoDO = hyPartnerBaseInfoDAO.getByPartnerLineId(lineId);

        HyPartnerBaseInfoDO hyPartnerBaseInfoDO = new HyPartnerBaseInfoDO();
        hyPartnerBaseInfoDO.setPartnerId(hyPartnerLineInfo.getPartnerId());
        hyPartnerBaseInfoDO.setPartnerLineId(newHyPartnerLineInfoDO.getId());
        hyPartnerBaseInfoDO.setUserPortrait(oldHyPartnerBaseInfoDO.getUserPortrait());
        hyPartnerBaseInfoDAO.insertSelective(hyPartnerBaseInfoDO);

        //添加日志
        LineLogInfo lineLogInfo = new LineLogInfo(hyPartnerLineInfo.getPartnerId(), hyPartnerLineInfo.getId(), user.getUserId(),
                user.getName(), OperateTypeEnum.REMOVE_BLACKLIST,
                WorkflowStageEnum.getWorkflowStageByCode(hyPartnerLineInfo.getWorkflowStage()),
                hyPartnerLineInfo.getWorkflowStatus(), "");
        BlackListLogDTO logDTO = BlackListLogDTO.builder().operateUserId(user.getUserId()).reason(removeReason).operateUsername(user.getName())
                .mobile(user.getMobile()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC_2)).build();
        lineLogInfo.setData(logDTO);
        hyPartnerTaskInfoLogDAO.addOperateLog(lineLogInfo);
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean closeOrPassFollow(LoginUserInfo user,CloseFollowRequest closeFollowRequest) throws ApiException {
        //该方法中user可能为空，注意处理空指针的情况
        if(user == null){
            user = new LoginUserInfo();
        }

        HyPartnerLineInfoDO hyPartnerLineInfoDO = hyPartnerLineInfoDAO.selectByPrimaryKeySelective(closeFollowRequest.getLineId());
        if (hyPartnerLineInfoDO==null){
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        if (hyPartnerLineInfoDO.getLineStatus()==0){
            throw new ServiceException(ErrorCodeEnum.PUBLIC_LINE_NOT_OPERATE);
        }
        String oldWorkflowStage = hyPartnerLineInfoDO.getWorkflowStage();
        String oldWorkflowStatus = hyPartnerLineInfoDO.getWorkflowStatus();
        //通过
        if ("pass".equals(closeFollowRequest.getType())){
            hyPartnerLineInfoDO.setWorkflowStage(WorkflowStageEnum.RESERVATION.getCode());
            hyPartnerLineInfoDO.setWorkflowStatus(WorkflowStatusEnum.RESERVATION_0.getCode());
            hyPartnerLineInfoDO.setDeadline(CoolDateUtils.getDateFormatDay(new Date(),2));
            hyPartnerLineInfoDO.setPassReason(closeFollowRequest.getPassReason());
            if (CollectionUtils.isNotEmpty(closeFollowRequest.getCertifyFile())){
                hyPartnerLineInfoDO.setCertifyFile(JSONObject.toJSONString(closeFollowRequest.getCertifyFile()));
            }
            HyPartnerBaseInfoDO hy = hyPartnerBaseInfoDAO.getByPartnerLineId(hyPartnerLineInfoDO.getId());
            hy.setPassReason(closeFollowRequest.getPassReason());
            hy.setPassTime(new Date());
            hy.setPassUserId(user.getUserId());
            if (CollectionUtils.isNotEmpty(closeFollowRequest.getCertifyFile())){
                hy.setCertifyFile(JSONObject.toJSONString(closeFollowRequest.getCertifyFile()));
            }
            hyPartnerBaseInfoDAO.updateByPrimaryKeySelective(hy);
            IntentSmsReq intentSmsReq = new IntentSmsReq();
            intentSmsReq.setDeadLine(DateUtil.formatDateTime(hyPartnerLineInfoDO.getDeadline()));
            smsService.sendSms(JSON.toJSONString(intentSmsReq),CommonConstants.SMS_TEMPLATE_CODE_INTENT, hy.getMobile());
        }

        //拒绝
        if ("reject".equals(closeFollowRequest.getType())){
            //当前节点 拒绝的子状态
            String workflowStatus = WorkflowStageEnum.getWorkflowStageMap().get(hyPartnerLineInfoDO.getWorkflowStage());
            hyPartnerLineInfoDO.setWorkflowStatus(workflowStatus);
            //15天 冷静期 
            String coolingPeriodFirstLoginCacheKey = MessageFormat.format(RedisConstant.COOLINGPERIOD_FIRSTLOGIN_KEY, closeFollowRequest.getLineId());
            redisUtilPool.setString(coolingPeriodFirstLoginCacheKey,JSONObject.toJSONString(closeFollowRequest));
            hyPartnerLineInfoDO.setDeadline(CoolDateUtils.getDateBefore(new Date(),15));
            hyPartnerLineInfoDO.setRejectPublicReason(closeFollowRequest.getRejectPublicReason());
            hyPartnerLineInfoDO.setRejectRealReason(closeFollowRequest.getRejectRealReason());
            if (CollectionUtils.isNotEmpty(closeFollowRequest.getCertifyFile())){
                hyPartnerLineInfoDO.setCertifyFile(JSONObject.toJSONString(closeFollowRequest.getCertifyFile()));
            }
            hyPartnerLineInfoDO.setLineStatus(LineStatusEnum.PUBLIC_SEAS.getCode());
            hyPartnerLineInfoDO.setCloseTime(new Date());
            hyPartnerLineInfoDO.setCloseUserId(user.getUserId());
            //各阶段单独的逻辑
            workFlowService.endProcess(WorkflowStageEnum.getWorkflowStageByCode(hyPartnerLineInfoDO.getWorkflowStage()),closeFollowRequest);
        }

        //面试超时
        if ("overtime_interview".equals(closeFollowRequest.getType())){
            //面试超时未预约
            hyPartnerLineInfoDO.setWorkflowStatus(WorkflowStatusEnum.RESERVATION_8.getCode());
            //15天 冷静期
            String coolingPeriodFirstLoginCacheKey = MessageFormat.format(RedisConstant.COOLINGPERIOD_FIRSTLOGIN_KEY, closeFollowRequest.getLineId());
            redisUtilPool.setString(coolingPeriodFirstLoginCacheKey,JSONObject.toJSONString(closeFollowRequest));
            hyPartnerLineInfoDO.setDeadline(CoolDateUtils.getDateBefore(new Date(),15));
            hyPartnerLineInfoDO.setRejectPublicReason(closeFollowRequest.getRejectPublicReason());
            hyPartnerLineInfoDO.setRejectRealReason(closeFollowRequest.getRejectRealReason());
            hyPartnerLineInfoDO.setLineStatus(LineStatusEnum.PUBLIC_SEAS.getCode());
            hyPartnerLineInfoDO.setCloseTime(new Date());
        }
        hyPartnerLineInfoDAO.updateByPrimaryKeySelective(hyPartnerLineInfoDO);


        //通过 拒绝添加日志
        if ("pass".equals(closeFollowRequest.getType())||"reject".equals(closeFollowRequest.getType())){
            LineLogInfo lineLogInfo = new LineLogInfo(hyPartnerLineInfoDO.getPartnerId(), hyPartnerLineInfoDO.getId(), user.getUserId(),
                    user.getName(), OperateTypeEnum.REMOVE_BLACKLIST,
                    WorkflowStageEnum.getWorkflowStageByCode(oldWorkflowStage),
                    oldWorkflowStatus, "");
            CloseOrPassFollowLogDTO log = CloseOrPassFollowLogDTO.builder().operateUserId(user.getUserId()).passReason(closeFollowRequest.getPassReason()).rejectRealReason(closeFollowRequest.getRejectRealReason())
                    .operateUsername(user.getName()).rejectPublicReason(closeFollowRequest.getRejectPublicReason()).certifyFile(JSONObject.toJSONString(closeFollowRequest.getCertifyFile()))
                    .mobile(user.getMobile()).operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC_2)).build();
            lineLogInfo.setData(log);
            hyPartnerTaskInfoLogDAO.addOperateLog(lineLogInfo);
        }
        return Boolean.TRUE;
    }



    @Override
    public PageInfo<PublicSeaLineListVo> publicSeaLineList(String userId, LineRequest lineRequest) {
        //确认是招商经理还是部门负责人
//        EnterpriseUserDO userInfo = enterpriseUserDAO.getUserInfoById(userId);
//        List<String> userIds = new ArrayList<>();
//        if (userInfo.getIsLeader()){
//            if (StringUtil.isNotEmpty(userInfo.getLeaderDeptIds())){
//                List<String> regionIds = JSONObject.parseArray(userInfo.getLeaderDeptIds(), String.class);
//                List<EnterpriseUserDO> enterpriseUserDOS = enterpriseUserDAO.searchUserByRegionIdsAndKeyword(regionIds, null, true);
//                userIds =enterpriseUserDOS.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList());
//            }
//        }else {
//            userIds = Arrays.asList(userId);
//        }
        String intentAreaName = getIntentAreaName(lineRequest.getIntentArea());
        PageHelper.startPage(lineRequest.getPageNum(),lineRequest.getPageSize());
        PageInfo publicSeaLineList = new PageInfo(hyPartnerLineInfoDAO.getPublicSeaLineList(lineRequest.getUserNameKeyword(), lineRequest.getPhoneKeyword(),
                intentAreaName, lineRequest.getAcceptAdjustType(), lineRequest.getUpdateStartTime(), lineRequest.getUpdateEndTime(), null));

        List<PublicSeaLineDTO> list = publicSeaLineList.getList();
        if (CollectionUtils.isEmpty(list)){
            return new PageInfo<>();
        }
        //上一次结束的线索
        List<String> partnerIdList = list.stream().map(PublicSeaLineDTO::getPartnerId).collect(Collectors.toList());
        List<HyPartnerLineInfoDO> partnerLastLine = hyPartnerLineInfoDAO.getPartnerLastLine(partnerIdList);
        List<String> investmentManagerIds = partnerLastLine.stream().map(HyPartnerLineInfoDO::getInvestmentManager).collect(Collectors.toList());
        List<EnterpriseUserDO> userInfoList = enterpriseUserDAO.getUserInfoByUserIds(investmentManagerIds);
        Map<String, String> nameMobileMap = userInfoList.stream().filter(x ->
            StringUtil.isNotEmpty(x.getMobile())).collect(Collectors.toMap(EnterpriseUserDO::getUserId, v-> v.getName() + " "+ v.getMobile()));
        Map<String, HyPartnerLineInfoDO> hyPartnerLineInfoDOMap = partnerLastLine.stream().collect(Collectors.toMap(HyPartnerLineInfoDO::getPartnerId, data -> data));

        List<LineCountDTO> followCountList = hyPartnerLineInfoDAO.getFollowCountList(partnerIdList);
        Map<String, Integer> countMap = followCountList.stream().collect(Collectors.toMap(LineCountDTO::getPartnerId, LineCountDTO::getFollowCount));

        List<Long> wantShopAreaList = list.stream().map(PublicSeaLineDTO::getWantShopArea).filter(Objects::nonNull).map(Long::parseLong).distinct().collect(Collectors.toList());
        Map<String, String> wantShopAreaNameMap = hyOpenAreaInfoDAO.selectNameMapByIds(wantShopAreaList);
        List<PublicSeaLineListVo> result = new ArrayList<>();
        list.forEach(x->{
            PublicSeaLineListVo publicSeaLineListVo = new PublicSeaLineListVo();
            publicSeaLineListVo.setPartnerId(x.getPartnerId());
            publicSeaLineListVo.setCreateTime(DateUtil.format(x.getCreateTime(),CoolDateUtils.DATE_FORMAT_SEC_2));
            publicSeaLineListVo.setPartnerUserName(x.getUserName());
            publicSeaLineListVo.setPartnerUserPhone(x.getMobile());
            String phoneAddress = x.getPhoneAddress();
            if (StringUtils.isEmpty(phoneAddress)){
                phoneAddress = hyPhoneLocationService.handleHyPhoneAddress(x.getMobile());
            }
            publicSeaLineListVo.setPhoneAddress(phoneAddress);
            publicSeaLineListVo.setWantShopArea(x.getWantShopArea());
            publicSeaLineListVo.setUpdateTime(DateUtil.format(x.getUpdateTime(),CoolDateUtils.DATE_FORMAT_SEC_2));
            publicSeaLineListVo.setId(x.getLineId());
            publicSeaLineListVo.setAcceptAdjustType(x.getAcceptAdjustType());
            publicSeaLineListVo.setFollowCount(countMap.getOrDefault(x.getPartnerId(),0));
            HyPartnerLineInfoDO hy = hyPartnerLineInfoDOMap.getOrDefault(x.getPartnerId(), new HyPartnerLineInfoDO());
            publicSeaLineListVo.setRejectPublicReason(hy.getRejectPublicReason());
            publicSeaLineListVo.setRejectRealReason(hy.getRejectRealReason());
            publicSeaLineListVo.setWantShopAreaName(wantShopAreaNameMap.get(x.getWantShopArea()));
            String closeTime = DateUtil.format(hy.getCloseTime(), CoolDateUtils.DATE_FORMAT_SEC_2);
            publicSeaLineListVo.setLastCloseDate(closeTime);
            publicSeaLineListVo.setLastInvestmentManager(nameMobileMap.get(hy.getInvestmentManager()));
            result.add(publicSeaLineListVo);
        });
        publicSeaLineList.setList(result);
        return publicSeaLineList;
    }




    @Override
    public PageInfo<PrivateSeaLineListVo> privateSeaLineList(String userId, PrivateSeaLineListRequest request) {
        UserPositionAndUserScopeDTO userIdsByScope = enterpriseUserService.getUserIdsByScope(userId);
        String intentAreaName = getIntentAreaName(request.getIntentArea());
        PageHelper.startPage(request.getPageNum(),request.getPageSize());
        PageInfo privateLineList = new PageInfo(hyPartnerLineInfoDAO.getPrivateSeaLineList(request.getKeyword(),  request.getKeywordType(),  request.getWorkflowStage(),
                request.getWorkflowStatus(),  request.getDeadlineStart(),  request.getDeadlineEnd(),
                intentAreaName,  request.getAcceptAdjustType(),  request.getStoreKeyword(),
                request.getStoreKeywordType(), userIdsByScope.getInvestmentUserIds(),userIdsByScope.getDevelopmentUserIds()));
        List<PrivateSeaLineDTO> list = privateLineList.getList();
        if (CollectionUtils.isEmpty(list)){
            return new PageInfo<>();
        }
        List<Long> lindIds = list.stream().map(PrivateSeaLineDTO::getLineId).collect(Collectors.toList());
        List<HyPartnerInterviewPlanDO> hyPartnerInterviewPlanDOS = hyPartnerInterviewPlanDAO.getHyPartnerInterviewPlanByLineIds(lindIds);
        Map<Long, HyPartnerInterviewPlanDO> hyPartnerInterviewPlanDOMap = hyPartnerInterviewPlanDOS.stream().collect(Collectors.toMap(HyPartnerInterviewPlanDO::getPartnerLineId, data -> data));

        Map<String, String> devManagerMap = new HashMap<>();
        List<String> devManagerIdList = list.stream().filter(x -> StringUtils.isNotEmpty(x.getDevelopmentManager())).map(PrivateSeaLineDTO::getDevelopmentManager).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(devManagerIdList)){
            List<EnterpriseUserDO> devManagerList = enterpriseUserDAO.getUserInfoByUserIds(devManagerIdList);
            devManagerMap = devManagerList.stream().collect(Collectors.toMap(EnterpriseUserDO::getUserId, EnterpriseUserDO::getName));
        }
        List<Long> wantShopAreaList = list.stream().filter(x->StringUtils.isNotEmpty(x.getWantShopArea())).map(PrivateSeaLineDTO::getWantShopArea).map(Long::parseLong).distinct().collect(Collectors.toList());
        Map<String, String> wantShopAreaNameMap = hyOpenAreaInfoDAO.selectNameMapByIds(wantShopAreaList);
        List<PrivateSeaLineListVo> result = PrivateSeaLineListVo.convertList(list, devManagerMap, wantShopAreaNameMap,hyPartnerInterviewPlanDOMap);
        privateLineList.setList(result);
        return privateLineList;
    }

    @Override
    public PartnerLineBaseInfoVO getPartnerLinBaseInfo(String partnerId) {
        PartnerLineBaseInfoVO lineBaseInfoVO = new PartnerLineBaseInfoVO();
        // todo wxp 需要加条件
        HyPartnerLineInfoDO lineInfoDO = hyPartnerLineInfoDAO.getByPartnerId(partnerId);
        BeanUtil.copyProperties(lineInfoDO, lineBaseInfoVO);
        String coolingPeriodFirstLoginCacheKey = MessageFormat.format(RedisConstant.COOLINGPERIOD_FIRSTLOGIN_KEY, lineInfoDO.getId());
        String value = redisUtilPool.getString(coolingPeriodFirstLoginCacheKey);
        lineBaseInfoVO.setCoolDownFirstLoginFlag(StringUtils.isNotBlank(value));
        lineBaseInfoVO.setPartnerLineId(lineInfoDO.getId());
        lineBaseInfoVO.setCause(lineInfoDO.getRejectPublicReason());

        return lineBaseInfoVO;
    }

    @Override
    public List<LineFollowHistoryVO> getLineFollowHistory(String partnerId) {
        List<HyPartnerLineInfoDO> lineFollowHistoryList = hyPartnerLineInfoDAO.getLineFollowHistoryList(partnerId);
        if (CollectionUtils.isEmpty(lineFollowHistoryList)){
            return new ArrayList<>();
        }
        List<LineFollowHistoryVO> result = new ArrayList<>();
        lineFollowHistoryList.forEach(x->{
            LineFollowHistoryVO lineFollowHistoryVO = new LineFollowHistoryVO();
            lineFollowHistoryVO.setCloseCause(x.getRejectRealReason());
            lineFollowHistoryVO.setCloseTime( DateUtil.format(x.getCloseTime(), CoolDateUtils.DATE_FORMAT_SEC_2));
            lineFollowHistoryVO.setStartTime(DateUtil.format(x.getCreateTime(), CoolDateUtils.DATE_FORMAT_SEC_2));
            result.add(lineFollowHistoryVO);
        });
        return result;
    }

    @Override
    public Boolean assignFollowUser(String partnerId, String wantShopArea, Integer acceptAdjustType,Boolean flag) {
        log.info("assignFollowUser partnerId:{}，wantShopArea：{}，acceptAdjustType：{}",partnerId,wantShopArea,acceptAdjustType);

        if (!flag){
            return Boolean.FALSE;
        }
        List<HyPartnerLineInfoDO> lineFollowHistoryList = hyPartnerLineInfoDAO.getLineFollowHistoryList(partnerId);
        //如果跟进次数大于1 直接使用上一次的招商经理
        if (CollectionUtils.isNotEmpty(lineFollowHistoryList)){
            return Boolean.TRUE;
        }
        //当前加盟商线索
        HyPartnerLineInfoDO HyPartnerLineInfo = hyPartnerLineInfoDAO.getByPartnerId(partnerId);
        //如果意向区域没有绑定战区 不分配招商经理
        HyIntendDevelopementMappingDO hyIntendDevelopementMappingDO = hyIntendDevMappingDAO.selectByOpenAreaMappingId(Long.valueOf(wantShopArea), "intent");
        if (hyIntendDevelopementMappingDO==null){
            log.info("如果意向区域没有绑定战区 不分配招商经理");
            return Boolean.FALSE;
        }
        List<String> result  = new ArrayList<>();
        if (hyIntendDevelopementMappingDO!=null){
            HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO = hyIntendDevZoneInfoDAO.selectById(hyIntendDevelopementMappingDO.getMappingId());
            if (hyIntendDevZoneInfoDO!=null && StringUtil.isNotEmpty(hyIntendDevZoneInfoDO.getAssociatedRegionId())) {
                List<String> list = JSONObject.parseArray(hyIntendDevZoneInfoDO.getAssociatedRegionId(), String.class);
                result.addAll(list);
            }
        }
        List<EnterpriseUserDO> userListByRegionIds = enterpriseUserDAO.getUserListByRegionIds(result);
        if (CollectionUtils.isEmpty(userListByRegionIds)){
            log.info("意向区域绑定战区 但是战区绑定的组织机构下没人 不分配");
            return Boolean.FALSE;
        }

        //如果是私海线索 不需要重新分配招商经理
        if ((HyPartnerLineInfo != null && HyPartnerLineInfo.getLineStatus()==1)){
            log.info("如果是私海线索 不需要重新分配招商经理  或者跟进次数大于等于1 lineStatus:{}",HyPartnerLineInfo.getLineStatus());
            return Boolean.FALSE;
        }

        if(HyPartnerLineInfo == null){
            Boolean lineStatus = getLineStatus(Long.valueOf(wantShopArea), acceptAdjustType);
            return lineStatus;
        }
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
        Boolean lineStatus = getLineStatus(Long.valueOf(hyPartnerUserInfoDO.getWantShopArea()), hyPartnerUserInfoDO.getAcceptAdjustType());
        log.info("lineStatus:{}",lineStatus);
        return lineStatus;
    }

    /**
     * 线索状态
     * @param wantShopAreaId
     * @param acceptAdjustType
     * @return
     */
    @Override
    public Boolean getLineStatus(Long wantShopAreaId,Integer acceptAdjustType){
        HyOpenAreaInfoDO hyOpenAreaInfoDO = hyOpenAreaInfoDAO.selectById(wantShopAreaId);

        if (AreaStatusEnum.OPEN.getCode().equals(hyOpenAreaInfoDO.getAreaStatus()) || AreaStatusEnum.KEY_OPEN.getCode().equals(hyOpenAreaInfoDO.getAreaStatus())){
            return Boolean.TRUE;
        }
        if (AreaStatusEnum.NOT_OPEN.getCode().equals(hyOpenAreaInfoDO.getAreaStatus()) || AreaStatusEnum.SATURATED.getCode().equals(hyOpenAreaInfoDO.getAreaStatus())){
            if (AcceptAdjustTypeEnum.NOT_ACCEPT.getCode().equals(acceptAdjustType)){
                return Boolean.FALSE;
            }
            //全国调剂 默认分配呗 有啥好说的
            if (AcceptAdjustTypeEnum.NATIONAL_ADJUSTMENT.getCode().equals(acceptAdjustType)){
                return Boolean.TRUE;
            }
            //省内调剂 有重点或者开放的 分配
            if (AcceptAdjustTypeEnum.PROVINCIAL_ADJUSTMENT.getCode().equals(acceptAdjustType)){

                List<HyOpenAreaInfoDO> hyOpenAreaInfoDOList= new ArrayList<>();
                if(hyOpenAreaInfoDO != null){
                    String areaPath = hyOpenAreaInfoDO.getAreaPath();
                    String province = areaPath.substring(0, areaPath.indexOf("/", areaPath.indexOf("/") + 1));
                    hyOpenAreaInfoDOList = hyOpenAreaInfoDAO.queryByKeyword(province, true, null, true);
                }
                if (hyOpenAreaInfoDOList.size()>CommonConstants.ZERO){
                    return Boolean.TRUE;
                }
                return Boolean.FALSE;
            }
            //市内调剂 不分配
            if (AcceptAdjustTypeEnum.LOCAL_ADJUSTMENT.getCode().equals(acceptAdjustType)){
                return Boolean.FALSE;
            }
        }
        return Boolean.FALSE;
    }


    @Override
    public  String getAssignFollowUser(String partnerId,String type) {
        //查询意向区域
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
        List<HyPartnerLineInfoDO> lineFollowHistoryList = hyPartnerLineInfoDAO.getLineFollowHistoryList(partnerId);
        //如果跟进次数大于1 直接使用上一次的招商经理
        if (CollectionUtils.isNotEmpty(lineFollowHistoryList)){
            return lineFollowHistoryList.get(0).getInvestmentManager();
        }
        //意向区域
        String wantShopArea = hyPartnerUserInfoDO.getWantShopArea();
        //查询意向区域绑定的组织架构 没有绑定战区 分配空
        HyIntendDevelopementMappingDO hyIntendDevelopementMappingDO = hyIntendDevMappingDAO.selectByOpenAreaMappingId(Long.valueOf(wantShopArea),type);
        List<String> result  = new ArrayList<>();
        if (hyIntendDevelopementMappingDO!=null){
            HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO = hyIntendDevZoneInfoDAO.selectById(hyIntendDevelopementMappingDO.getMappingId());
            if (hyIntendDevZoneInfoDO!=null && StringUtil.isNotEmpty(hyIntendDevZoneInfoDO.getAssociatedRegionId())) {
                List<String> list = JSONObject.parseArray(hyIntendDevZoneInfoDO.getAssociatedRegionId(), String.class);
                result.addAll(list);
            }
        }
        String userId = "";
        List<EnterpriseUserDO> userListByRegionIds = enterpriseUserDAO.getUserListByRegionIds(result);
        HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO = hyIntendDevZoneInfoDAO.selectById(hyIntendDevelopementMappingDO.getMappingId());
        if (CollectionUtils.isNotEmpty(userListByRegionIds)){
            List<String> userIdList = userListByRegionIds.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList());
            int i = userIdList.indexOf(hyIntendDevZoneInfoDO.getLastAllotUserId());
            if (i==(userListByRegionIds.size()-1)){
                 i = -1;
            }
              userId = userIdList.get(++i);
        }
        //上次分配的招商经理 记录
        if ("intent".equals(type)){
            hyIntendDevZoneInfoDO.setLastAllotUserId(userId);
            hyIntendDevZoneInfoDAO.updateByPrimaryKeySelective(hyIntendDevZoneInfoDO);
        }
        return userId;
    }

    @Override
    public InterviewVO getInterviewInfo(Long lineId,Boolean needDevelopmentDirector) throws ApiException {
        Long interviewId = hyPartnerInterviewPlanDAO.selectInterviewIdByLineId(lineId);
        QueryByInterviewPlanIdReq queryByInterviewPlanIdReq = new QueryByInterviewPlanIdReq();
        if (interviewId!=null){
            queryByInterviewPlanIdReq.setInterviewPlanId(String.valueOf(interviewId));
            queryByInterviewPlanIdReq.setNeedDevelopmentDirector(needDevelopmentDirector);
            return interviewService.getInterviewInfo(queryByInterviewPlanIdReq);
        }
        return null;
    }
    @Override
    public HyPartnerLineInfoDO generateDefaultLineInfo(String partnerId, String wantShopArea, Integer acceptAdjustType,Boolean assignFlag) {
        // 生成一条线索
        HyPartnerLineInfoDO hyPartnerLineInfoDO = hyPartnerLineInfoDAO.getByPartnerId(partnerId);
        Boolean flag = this.assignFollowUser(partnerId, wantShopArea, acceptAdjustType,assignFlag);
        String investmentManager = null;
        if (flag){
            investmentManager = getAssignFollowUser(partnerId, "intent");
        }
        if(hyPartnerLineInfoDO == null){
            hyPartnerLineInfoDO = new HyPartnerLineInfoDO();
            hyPartnerLineInfoDO.setPartnerId(partnerId);
            hyPartnerLineInfoDO.setWorkflowStage(WorkflowStageEnum.INTENT.getCode());
            hyPartnerLineInfoDO.setWorkflowStatus(WorkflowStatusEnum.INTENT_0.getCode());
            hyPartnerLineInfoDO.setLineStatus(flag ? LineStatusEnum.PRIVATE_SEAS.getCode() : LineStatusEnum.PUBLIC_SEAS.getCode());
            hyPartnerLineInfoDO.setInvestmentManager(investmentManager);
            hyPartnerLineInfoDAO.insertSelective(hyPartnerLineInfoDO);
        }else {
            if (LineStatusEnum.PUBLIC_SEAS.getCode().equals(hyPartnerLineInfoDO.getLineStatus())){
                hyPartnerLineInfoDO.setLineStatus(flag ? LineStatusEnum.PRIVATE_SEAS.getCode() : LineStatusEnum.PUBLIC_SEAS.getCode());
                hyPartnerLineInfoDO.setInvestmentManager(investmentManager);
                hyPartnerLineInfoDAO.updateByPrimaryKeySelective(hyPartnerLineInfoDO);
            }
        }
        //发送飞书工作通知
        if(flag){
            List<String> userIdList = new ArrayList<>();
            userIdList.add(investmentManager);
            HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
            noticeService.sendFeiShuNotice(FeiShuNoticeMsgEnum.ALLOCATION_INVESTMENT_MANAGER,userIdList,DateUtil.formatDateTime(new Date()),hyPartnerUserInfoDO.getUsername(),hyPartnerUserInfoDO.getMobile());
        }
        return hyPartnerLineInfoDO;
    }

    @Override
    public Long checkGenerateNewLineId(Long lineId) {
        HyPartnerLineInfoDO hyPartnerLineInfoDO = hyPartnerLineInfoDAO.selectByPrimaryKeySelective(lineId);
        // 15天之后可以继续填写意向信息，把之前的线索删除
        if(hyPartnerLineInfoDO != null && hyPartnerLineInfoDO.getDeadline() != null &&
                DateUtil.offsetSecond(hyPartnerLineInfoDO.getDeadline(), -2).before(new Date())){
            //将老的线索置为删除状态
            hyPartnerLineInfoDAO.batchDeleted(Collections.singletonList(hyPartnerLineInfoDO.getId()));
            HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(hyPartnerLineInfoDO.getPartnerId());
            // 生成一条新线索 生成新线索的时候不需要公海到私海
            HyPartnerLineInfoDO newLineInfoDO =  this.generateDefaultLineInfo(hyPartnerLineInfoDO.getPartnerId(), hyPartnerUserInfoDO.getWantShopArea(), hyPartnerUserInfoDO.getAcceptAdjustType(),Boolean.FALSE);
            // 生成一条意向基本信息
            HyPartnerBaseInfoDO oldBaseInfoDO = hyPartnerBaseInfoDAO.getByPartnerIdAndLineId(hyPartnerUserInfoDO.getPartnerId(), lineId);
            hyPartnerBaseInfoService.generateBaseInfo(hyPartnerUserInfoDO, newLineInfoDO.getId(), oldBaseInfoDO.getUserPortrait());
            return newLineInfoDO.getId();
        }
        return hyPartnerLineInfoDO.getId();
    }


    /**
     * convertPartnerBlackListDTOToVo
     * @param partnerBlackListDTO
     * @return
     */
    public BlackListVO convertPartnerBlackListDTOToVo(PartnerBlackListDTO partnerBlackListDTO){
        BlackListVO blackListVO = new BlackListVO();
        blackListVO.setId(partnerBlackListDTO.getLineId());
        blackListVO.setPartnerId(partnerBlackListDTO.getPartnerId());
        blackListVO.setPartnerUserName(partnerBlackListDTO.getPartnerUserName());
        blackListVO.setPartnerUserPhone(partnerBlackListDTO.getMobile());
        String createTime = DateUtil.format(partnerBlackListDTO.getCreateTime(), CoolDateUtils.DATE_FORMAT_SEC_2);
        String closeTime = DateUtil.format(partnerBlackListDTO.getCloseTime(), CoolDateUtils.DATE_FORMAT_SEC_2);
        blackListVO.setCreateTime(createTime);
        blackListVO.setCloseTime(closeTime);
        blackListVO.setJoinBlackReason(partnerBlackListDTO.getJoinBlackReason());
        blackListVO.setCloseUserId(partnerBlackListDTO.getCloseUserId());
        String phoneAddress = partnerBlackListDTO.getPhoneAddress();
        if (StringUtils.isEmpty(phoneAddress)){
            phoneAddress = hyPhoneLocationService.handleHyPhoneAddress(partnerBlackListDTO.getMobile());
        }
        blackListVO.setPhoneAddress(phoneAddress);
        blackListVO.setPhoneAddress(partnerBlackListDTO.getPhoneAddress());
        blackListVO.setCloseUserPhone(partnerBlackListDTO.getCloseUserId());
        return blackListVO;
    }




    /**
     * convertPartnerLineInfoAndBaseInfoDTOToVo
     * @param partnerLineInfoAndBaseInfoDTO
     * @return
     */
    private PartnerLineInfoAndBaseInfoVO convertPartnerLineInfoAndBaseInfoDTOToVo(PartnerLineInfoAndBaseInfoDTO partnerLineInfoAndBaseInfoDTO){
        PartnerLineInfoAndBaseInfoVO partnerLineInfoAndBaseInfoVO = new PartnerLineInfoAndBaseInfoVO();
        partnerLineInfoAndBaseInfoVO.setId(partnerLineInfoAndBaseInfoDTO.getId());
        partnerLineInfoAndBaseInfoVO.setPartnerUserId(partnerLineInfoAndBaseInfoDTO.getPartnerId());
        partnerLineInfoAndBaseInfoVO.setInvestmentManager(partnerLineInfoAndBaseInfoDTO.getInvestmentManager());
        if (StringUtils.isNotEmpty(partnerLineInfoAndBaseInfoDTO.getUserPortrait())){
            partnerLineInfoAndBaseInfoVO.setUserPortrait(JSONObject.parseArray(partnerLineInfoAndBaseInfoDTO.getUserPortrait(),String.class));
        }
        partnerLineInfoAndBaseInfoVO.setPartnerBaseInfoId(partnerLineInfoAndBaseInfoDTO.getPartnerBaseInfoId());
        partnerLineInfoAndBaseInfoVO.setWorkflowStage(partnerLineInfoAndBaseInfoDTO.getWorkflowStage());
        partnerLineInfoAndBaseInfoVO.setWorkflowStatus(partnerLineInfoAndBaseInfoDTO.getWorkflowStatus());
        partnerLineInfoAndBaseInfoVO.setPassCause(partnerLineInfoAndBaseInfoDTO.getPassCause());
        String phoneAddress = partnerLineInfoAndBaseInfoDTO.getPhoneAddress();
        if (StringUtils.isEmpty(phoneAddress)){
            phoneAddress = hyPhoneLocationService.handleHyPhoneAddress(partnerLineInfoAndBaseInfoDTO.getPartnerUserPhone());
        }
        partnerLineInfoAndBaseInfoVO.setPhoneAddress(phoneAddress);
        partnerLineInfoAndBaseInfoVO.setLineStatus(partnerLineInfoAndBaseInfoDTO.getLineStatus());
        partnerLineInfoAndBaseInfoVO.setInvestmentManagerPhone(partnerLineInfoAndBaseInfoDTO.getInvestmentManagerPhone());
        partnerLineInfoAndBaseInfoVO.setPartnerUserPhone(partnerLineInfoAndBaseInfoDTO.getPartnerUserPhone());
        partnerLineInfoAndBaseInfoVO.setPartnerUserName(partnerLineInfoAndBaseInfoDTO.getPartnerUserName());
        partnerLineInfoAndBaseInfoVO.setAcceptAdjustType(partnerLineInfoAndBaseInfoDTO.getAcceptAdjustType());
        partnerLineInfoAndBaseInfoVO.setWantShopArea(partnerLineInfoAndBaseInfoDTO.getWantShopArea());
        partnerLineInfoAndBaseInfoVO.setLiveArea(partnerLineInfoAndBaseInfoDTO.getLiveArea());
        partnerLineInfoAndBaseInfoVO.setIdCard(partnerLineInfoAndBaseInfoDTO.getIdCard());
        partnerLineInfoAndBaseInfoVO.setChannelName(partnerLineInfoAndBaseInfoDTO.getChannelName());
        partnerLineInfoAndBaseInfoVO.setDevelopmentDirector(partnerLineInfoAndBaseInfoDTO.getDevelopmentDirector());
        if (StringUtil.isNotEmpty(partnerLineInfoAndBaseInfoDTO.getCertifyFile())){
            partnerLineInfoAndBaseInfoVO.setPassCertifyFile(JSONObject.parseArray(partnerLineInfoAndBaseInfoDTO.getCertifyFile(), String.class));
        }
        partnerLineInfoAndBaseInfoVO.setPassUserId(partnerLineInfoAndBaseInfoDTO.getPassUserId());
        partnerLineInfoAndBaseInfoVO.setEducation(partnerLineInfoAndBaseInfoDTO.getEducation());
        partnerLineInfoAndBaseInfoVO.setPassTime(DateUtil.format(partnerLineInfoAndBaseInfoDTO.getPassTime(),CoolDateUtils.DATE_FORMAT_SEC_2));
        return partnerLineInfoAndBaseInfoVO;
    }



    /**
     * stageCountDTOToVo
     * @param stageCountDTO
     * @return
     */
    private StageCountVO stageCountDTOToVo(StageCountDTO stageCountDTO){
        StageCountVO stageCountVO = new StageCountVO();
        stageCountVO.setQualifiedInterviewCount(stageCountDTO.getQualifiedInterviewCount());
        stageCountVO.setIntentApplyApproveCount(stageCountDTO.getIntentApplyApproveCount());
        stageCountVO.setReservationInterviewCount(stageCountDTO.getReservationInterviewCount());
        return stageCountVO;
    }

    /**
     * getIntentAreaName
     * @param intentArea
     * @return
     */
    private String getIntentAreaName(String intentArea){
        String intentAreaName = null;
        if (StringUtils.isNotEmpty(intentArea)){
            HyOpenAreaInfoDO hyOpenAreaInfoDO = hyOpenAreaInfoDAO.selectById(Long.valueOf(intentArea));
            intentAreaName = hyOpenAreaInfoDO.getAreaName();
        }
        return intentAreaName;
    }

}
