CommonService.java 10.3 KB
package cn.fw.valhalla.service.bus;

import cn.fw.common.util.ValidationUtils;
import cn.fw.valhalla.common.constant.RoleCode;
import cn.fw.valhalla.common.utils.DateUtil;
import cn.fw.valhalla.domain.db.OriginalData;
import cn.fw.valhalla.domain.db.customer.AccidentPool;
import cn.fw.valhalla.domain.db.customer.Customer;
import cn.fw.valhalla.domain.db.customer.CustomerBaseInfo;
import cn.fw.valhalla.domain.db.follow.FollowClue;
import cn.fw.valhalla.domain.db.pool.StammkundePool;
import cn.fw.valhalla.domain.enums.ClueStatusEnum;
import cn.fw.valhalla.domain.enums.FollowTypeEnum;
import cn.fw.valhalla.domain.enums.SettingTypeEnum;
import cn.fw.valhalla.domain.enums.StammkundeStatusEnum;
import cn.fw.valhalla.domain.vo.PostUserVO;
import cn.fw.valhalla.domain.vo.setting.SettingVO;
import cn.fw.valhalla.rpc.ehr.EhrRpcService;
import cn.fw.valhalla.rpc.ehr.dto.StaffInfoDTO;
import cn.fw.valhalla.rpc.erp.UserService;
import cn.fw.valhalla.rpc.erp.dto.PostUserDTO;
import cn.fw.valhalla.rpc.pstn.PstnService;
import cn.fw.valhalla.sdk.enums.DataTypeEnum;
import cn.fw.valhalla.service.bus.cust.CustomerChangeBizService;
import cn.fw.valhalla.service.bus.follow.FollowBizService;
import cn.fw.valhalla.service.bus.setting.SettingBizService;
import cn.fw.valhalla.service.data.*;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static cn.fw.common.businessvalidator.Validator.BV;

/**
 * @author : kurisu
 * @className : CommonService
 * @description : 公共服务
 * @date: 2020-10-22 11:07
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CommonService {
    private final UserService userService;
    private final CustomerService customerService;
    private final CustomerBaseInfoService customerBaseInfoService;
    private final StammkundePoolService stammkundePoolService;
    private final PstnService pstnService;
    private final EhrRpcService ehrRpcService;
    private final AccidentPoolService accidentPoolService;
    private final CustomerChangeBizService customerChangeBizService;
    private final FollowClueService followClueService;
    private final FollowBizService followBizService;
    private final OriginalDataService originalDataService;
    private final SettingBizService settingBizService;
    Map<Long, List<Integer>> map = MapUtil.builder(new HashMap<Long, List<Integer>>())
            .put(-1L, ListUtil.toList(67, 65, 66))
            .put(28L, ListUtil.toList(67, 70, 79, 66, 65, 73, 69))
            .put(29L, ListUtil.toList(79, 69, 66, 70, 65, 73, 147, 67))
            .put(30L, ListUtil.toList(67))
            .put(59L, ListUtil.toList(161, 159, 66))
            .put(148L, ListUtil.toList(159))
            .put(175L, ListUtil.toList(67))
            .put(180L, ListUtil.toList(66, 67, 79, 65, 70, 69))
            .build();


    public List<PostUserVO> getUsers(final Long shopId) {
        List<PostUserVO> list = new ArrayList<>();
        List<PostUserDTO> userByRole = userService.getUserByRole(shopId, RoleCode.FWGW);
        if (CollectionUtils.isEmpty(userByRole)) {
            return list;
        }

        for (PostUserDTO userDTO : userByRole) {
            PostUserVO vo = new PostUserVO(userDTO.getUserId(), userDTO.getUserName(), 0);
            int count = stammkundePoolService.count(Wrappers.<StammkundePool>lambdaQuery()
                    .eq(StammkundePool::getAdviserId, userDTO.getUserId())
                    .eq(StammkundePool::getShopId, shopId)
                    .eq(StammkundePool::getPoolStatus, StammkundeStatusEnum.KUNDE)
                    .eq(StammkundePool::getAktiv, Boolean.TRUE)
                    .isNull(StammkundePool::getRejectTime)
            );
            vo.setCurQuantity(count);
            list.add(vo);
        }
        return list;
    }

    public void rollBack(String vin, Long groupId) {
        rollBack(vin);
        customerChangeBizService.rollBack(vin, groupId);
    }

    public void rollBack(String vin) {
    }

    /**
     * 通过智能通话系统获取所拨打的电话号码
     *
     * @param userId
     * @param cusId
     * @param accidentCar
     * @return
     */
    public String call(Long userId, Long cusId, Boolean accidentCar) {
        StaffInfoDTO staffInfo = ehrRpcService.queryStaffInfo(userId);
        BV.notNull(staffInfo, () -> "用户身份验证异常,请重试");
        String becallNo;
        if (Boolean.TRUE.equals(accidentCar)) {
            AccidentPool accidentPool = accidentPoolService.getById(cusId);
            BV.notNull(accidentPool, () -> "用户不存在");
            becallNo = accidentPool.getReportMobile();
            if (!ValidationUtils.checkMobile(becallNo)) {
                return becallNo;
            }
        } else {
            Customer customer = customerService.queryByIdWithInvalid(cusId);
            BV.notNull(customer, () -> "用户不存在");
            BV.isTrue(customer.getYn(), () -> "此档案已经作废,请主动放弃本次跟进");
            CustomerBaseInfo baseInfo = customerBaseInfoService.getById(customer.getBaseId());
            BV.notNull(baseInfo, () -> "用户不存在");
            becallNo = baseInfo.getMobile();
        }
        BV.isNotBlank(becallNo, () -> "客户电话号码不正确,无法拨打");
        assert staffInfo != null;
        BV.isNotBlank(staffInfo.getMobile(), () -> "用户电话号码不正确,无法拨打");
        String virtualNumber = pstnService.virtualNumber(staffInfo.getMobile(), becallNo, staffInfo.getGroupId());
        BV.isNotBlank(virtualNumber, () -> "号码不正确,无法拨号");
        return virtualNumber;
    }

    /**
     * 手动开始任务
     */
    public void startClue() {
        List<FollowClue> list = followClueService.list(Wrappers.<FollowClue>lambdaQuery()
                .eq(FollowClue::getClueState, ClueStatusEnum.WAITING)
                .le(FollowClue::getStartTime, DateUtil.localDateTime2Date(LocalDateTime.now()))
                .last("limit 0, 2000")
        );
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (FollowClue cluePool : list) {
            followBizService.startClue(cluePool);
        }
    }

    public void createClue(Long groupId) {
        int count = customerService.count(Wrappers.<Customer>lambdaQuery()
                .eq(Customer::getGroupId, groupId)
                .eq(Customer::getYn, Boolean.TRUE)
        );
        if (count <= 0) {
            return;
        }
        List<Customer> list = customerService.list(Wrappers.<Customer>lambdaQuery()
                .eq(Customer::getGroupId, groupId)
                .eq(Customer::getYn, Boolean.TRUE)
        );
        for (Customer customer : list) {
            try {
                createClue(customer);
            } catch (Exception e) {
                log.error("手动生成续保任务失败:", e);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void createClue(Customer customer) {
        String day = DateUtil.getStringDateShort(new Date());
        Long customerId = customer.getId();
        Long shopId = customer.getShopId();
        Long adviserId = customer.getAdviserId();

        String vin = customer.getFrameNo();
        ArrayList<ClueStatusEnum> statusEnums = ListUtil.toList(ClueStatusEnum.WAITING, ClueStatusEnum.ONGOING);
        int count = followClueService.count(Wrappers.<FollowClue>lambdaQuery()
                .eq(FollowClue::getClueType, FollowTypeEnum.IR)
                .eq(FollowClue::getVin, vin)
                .in(FollowClue::getClueState, statusEnums)
        );
        if (count > 0) {
            return;
        }

        OriginalData originalData = originalDataService.getOne(Wrappers.<OriginalData>lambdaQuery()
                .eq(OriginalData::getType, DataTypeEnum.BI)
                .eq(OriginalData::getCustomerId, customerId)
                .orderByDesc(OriginalData::getCreateTime)
                .last(" limit 1 ")
        );
        LocalDate generateTime = generateTime(originalData, customer);
        if (Objects.isNull(generateTime)) {
            return;
        }
        OriginalData data = new OriginalData();
        data.setType(DataTypeEnum.BI);
        data.setCustomerId(customerId);
        data.setPlateNo(customer.getPlateNo());
        data.setFrameNo(customer.getFrameNo());
        if (Objects.nonNull(shopId)) {
            data.setUserId(adviserId);
            data.setShopId(shopId);
        } else {
            Long brandId = Optional.ofNullable(customer.getBrandId()).orElse(-1L);
            List<Integer> list = map.get(brandId);
            int randomIndex = new Random().nextInt(list.size());
            data.setShopId(Long.valueOf(list.get(randomIndex)));
        }
        data.setGenerateTime(DateUtil.localDate2Date(generateTime));
        data.setDetailId(customer.getPlateNo() + "_" + day);
        data.setSolved(false);
        data.setGroupId(customer.getGroupId());
        originalDataService.save(data);
    }

    private LocalDate generateTime(OriginalData originalData, Customer customer) {
        LocalDate generateTime;
        if (Objects.nonNull(originalData)) {
            generateTime = DateUtil.date2LocalDate(originalData.getGenerateTime());
        } else {
            Date date = customer.getInsuranceExpires();
            if (Objects.isNull(date)) {
                date = Objects.isNull(customer.getBuyDate()) ? customer.getRegDate() : customer.getBuyDate();
            }
            if (Objects.isNull(date)) {
                return null;
            }
            generateTime = DateUtil.date2LocalDate(date);
        }
        Optional<SettingVO> settingVO = settingBizService.querySettingByType(FollowTypeEnum.IR, SettingTypeEnum.FIRST_TRIGGER_TIME, customer.getGroupId(), null);
        if (!settingVO.isPresent()) {
            return null;
        }
        int detailValue = Optional.ofNullable(settingVO.get().getDetailValue()).orElse(0);
        while (!generateTime.minusDays(detailValue).isAfter(LocalDate.now())) {
            generateTime = generateTime.plusYears(1L);
        }
        return generateTime;
    }
}