package com.sckw.contract.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.sckw.contract.api.model.dto.req.LogisticsScoreDetailFeignDto;
import com.sckw.contract.dao.KwcContractLogisticsScoreDetailMapper;
import com.sckw.contract.model.dto.req.LogisticsScoreApprovalDto;
import com.sckw.contract.model.dto.req.LogisticsScoreDetailQueryDto;
import com.sckw.contract.model.dto.req.LogisticsScoreQueryDto;
import com.sckw.contract.model.dto.req.LogisticsScoreDetailAddDto;
import com.sckw.contract.model.entity.KwcContractLogistics;
import com.sckw.contract.model.entity.KwcContractLogisticsScoreDetail;
import com.sckw.contract.model.entity.KwcContractLogisticsUnit;
import com.sckw.contract.model.vo.req.LogisticListReq;
import com.sckw.contract.model.vo.res.LogisticsScoreDetailResVo;
import com.sckw.contract.model.vo.res.LogisticsScoreResVo;
import com.sckw.contract.repository.KwcContractLogisticsRepository;
import com.sckw.contract.repository.KwcContractLogisticsUnitRepository;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.EntTypeEnum;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.PageUtils;
import com.sckw.core.web.config.CustomConfig;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.fleet.api.feign.DriverScoreFeignService;
import com.sckw.fleet.api.model.dto.DriverScoreQuery;
import com.sckw.fleet.api.model.dto.UpdateDriverScoreDto;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import com.sckw.system.api.model.dto.res.UserResDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sckw.contract.dao.KwcContractLogisticsScoreMapper;
import com.sckw.contract.model.entity.KwcContractLogisticsScore;
import com.sckw.contract.service.IKwcContractLogisticsScoreService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 物流企业评分Service业务层处理
 * 
 * @author tangyishan
 * @date 2025-12-05
 */
@Slf4j
@Service
public class KwcContractLogisticsScoreServiceImpl implements IKwcContractLogisticsScoreService 
{
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    @Autowired
    private KwcContractLogisticsScoreMapper kwcContractLogisticsScoreMapper;
    @Autowired
    private KwcContractLogisticsRepository kwcContractLogisticsRepository;
    @Autowired
    private KwcContractLogisticsUnitRepository kwcContractLogisticsUnitRepository;
    @Autowired
    private KwcContractLogisticsScoreDetailMapper kwcContractLogisticsScoreDetailMapper;
    @Autowired
    private DriverScoreFeignService driverScoreFeignService;
    @Autowired
    private CustomConfig customConfig;

    /**
     * 查询物流企业评分列表
     * providerEntId 供应商企业id
     * isPage 是否是分页查询
     * @return 物流企业评分
     */
    @Override
    public PageInfo<LogisticsScoreResVo> selectLogisticsScoreWithPendingSocreList(LogisticsScoreQueryDto query)
    {
        //查询评分列表
        PageInfo<LogisticsScoreResVo> pageInfo = new PageInfo<>(new ArrayList<>());
        List<KwcContractLogisticsScore> logisticsScores = selectLogisticsScoreList(query);
        List<Long> logisticsScoreIds = logisticsScores.stream().map(KwcContractLogisticsScore::getId).toList();
        if(CollectionUtils.isNotEmpty(logisticsScoreIds)){
            //查询待审评分
            LogisticsScoreDetailQueryDto detailReqDto = new LogisticsScoreDetailQueryDto();
            detailReqDto.setScoreIds(logisticsScoreIds);
            detailReqDto.setStatus(NumberConstant.ZERO);
            List<KwcContractLogisticsScoreDetail> logisticsScoreDetails = kwcContractLogisticsScoreDetailMapper.selectKwcContractLogisticsScoreDetailList(detailReqDto);
            if(CollectionUtils.isNotEmpty(logisticsScoreDetails)){
                Map<Long, BigDecimal> scoreChangeMap = logisticsScoreDetails.stream().collect(Collectors.toMap(KwcContractLogisticsScoreDetail::getScoreId, KwcContractLogisticsScoreDetail::getScoreChange, (v1, v2) -> v1));
                for (KwcContractLogisticsScore logisticsScore : logisticsScores) {
                    logisticsScore.setPendingScore(scoreChangeMap.getOrDefault(logisticsScore.getId(), null));
                }
            }
            Map<Long, EntCacheResDto> entCacheResDtoMap = remoteSystemService.queryEntCacheMapByIds(logisticsScores.stream().map(KwcContractLogisticsScore::getLogisticsEntId).toList());
            pageInfo = ((Page<KwcContractLogisticsScore>) logisticsScores).toPageInfo(e -> {
                LogisticsScoreResVo logisticsScoreResVo = new LogisticsScoreResVo();
                BeanUtils.copyProperties(e, logisticsScoreResVo);
                EntCacheResDto entCacheResDto = entCacheResDtoMap.get(e.getLogisticsEntId());
                if(entCacheResDto!=null){
                    logisticsScoreResVo.setLogisticsEntName(entCacheResDto.getFirmName());
                }
                if(e.getPendingScore()!=null && e.getPendingScore().compareTo(BigDecimal.ZERO) > 0){
                    logisticsScoreResVo.setPendingScore("+"+e.getPendingScore());
                }else if(e.getPendingScore()==null){
                    logisticsScoreResVo.setPendingScore("");
                }
                return logisticsScoreResVo;
            });
        }

        return pageInfo;
    }


    /**
     * 查询物流企业评分明细列表
     *
     * @param detailReqDto 物流企业评分明细
     * @return 物流企业评分明细
     */
    @Override
    public PageInfo<LogisticsScoreDetailResVo> selectKwcContractLogisticsScoreDetailList(LogisticsScoreDetailQueryDto detailReqDto)
    {
        //校验评分权限
        KwcContractLogisticsScore logisticsScore = checkLogisticsScoreAuth(detailReqDto.getProviderEntId(), detailReqDto.getScoreId());
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(logisticsScore.getLogisticsEntId());
        PageInfo<LogisticsScoreDetailResVo> pageInfo = new PageInfo<>(new ArrayList<>());
        PageUtils.startPage(detailReqDto);
        detailReqDto.setScoreIds(Collections.singletonList(detailReqDto.getScoreId()));
        List<KwcContractLogisticsScoreDetail> logisticsScoreDetails = kwcContractLogisticsScoreDetailMapper.selectKwcContractLogisticsScoreDetailList(detailReqDto);
        //根据影响人id列表查询影响人
        List<Long> influenceByIds = logisticsScoreDetails.stream().map(KwcContractLogisticsScoreDetail::getInfluenceBy).toList();
        Map<Long, UserCacheResDto> userCacheResDtoMap = remoteSystemService.queryUserCacheMapByIds(influenceByIds);
        if(CollectionUtils.isNotEmpty(logisticsScoreDetails)){
            pageInfo = ((Page<KwcContractLogisticsScoreDetail>) logisticsScoreDetails).toPageInfo(e -> {
                LogisticsScoreDetailResVo logisticsScoreDetailResVo = new LogisticsScoreDetailResVo();
                BeanUtils.copyProperties(e, logisticsScoreDetailResVo);
                if(e.getScoreChange()!=null && e.getScoreChange().compareTo(BigDecimal.ZERO) > 0){
                    logisticsScoreDetailResVo.setScoreChange("+"+e.getScoreChange());
                }else if(e.getScoreChange() == null){
                    logisticsScoreDetailResVo.setScoreChange("");
                }
                if(e.getScore() == null){
                    logisticsScoreDetailResVo.setScore("");
                }
                logisticsScoreDetailResVo.setLogisticsEntName(entCacheResDto.getFirmName());
                UserCacheResDto userCacheResDto = userCacheResDtoMap.get(e.getInfluenceBy());
                if(userCacheResDto != null){
                    logisticsScoreDetailResVo.setInfluenceByName(userCacheResDto.getName());
                }
                return logisticsScoreDetailResVo;
            });
        }
        return pageInfo;
    }

    /**
     * 查询物流企业待审评分
     *
     * @param scoreId 物流企业评分id
     * @param providerEntId 供应商企业id
     * @return 物流企业评分明细
     */
    @Override
    public LogisticsScoreDetailResVo selectLogisticsPendingScoreDetail(Long scoreId, Long providerEntId)
    {
        //校验评分权限
        KwcContractLogisticsScore logisticsScore = checkLogisticsScoreAuth(providerEntId,scoreId);
        KwcContractLogisticsScoreDetail logisticsScoreDetail = kwcContractLogisticsScoreDetailMapper.selectLogisticsPendingScoreDetail(scoreId);
        if(logisticsScoreDetail == null){
            return null;
        }
        EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(logisticsScore.getLogisticsEntId());
        UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(logisticsScoreDetail.getInfluenceBy());
        logisticsScoreDetail.setLogisticsEntName(entCacheResDto.getFirmName());
        LogisticsScoreDetailResVo logisticsScoreDetailResVo = new LogisticsScoreDetailResVo();
        BeanUtils.copyProperties(logisticsScoreDetail,logisticsScoreDetailResVo);
        logisticsScoreDetailResVo.setScore(logisticsScore.getScore().toString());
        logisticsScoreDetailResVo.setInfluenceByName(userCacheResDto.getName());
        return logisticsScoreDetailResVo;
    }


    /**
     * 查询物流企业评分列表
     * providerEntId 供应商企业id
     * isPage 是否是分页查询
     * @return 物流企业评分
     */
    private List<KwcContractLogisticsScore> selectLogisticsScoreList(LogisticsScoreQueryDto query)
    {
        //1.查询当前供应商企业有效的自动派车物流合同
        List<KwcContractLogistics> logisticsContracts = kwcContractLogisticsRepository.queryValidByEntId(query.getProviderEntId());
        List<Long> contractIds = logisticsContracts.stream().map(KwcContractLogistics::getId).toList();
        if(CollectionUtils.isNotEmpty(contractIds)){
            //2.根据物流合同id列表和托运商类型查询物流企业列表并得到物流企业id列表
            List<KwcContractLogisticsUnit> logisticsUnits = kwcContractLogisticsUnitRepository.queryByContractIds(contractIds, EntTypeEnum.LOGISTICS4.getCode());
            List<Long> logisticsEntIds = logisticsUnits.stream().map(KwcContractLogisticsUnit::getEntId).toList();
            if(CollectionUtils.isNotEmpty(logisticsEntIds)){
                //3.根据物流企业id列表和供应商企业id查询物流企业评分列表
                query.setLogisticsEntIds(logisticsEntIds);
                PageUtils.startPage(query);
                return kwcContractLogisticsScoreMapper.selectKwcContractLogisticsScoreList(query);
            }
        }
        return new Page<>(query.getPageNum(), query.getPageSize());
    }





    /**
     * 校验供应商企业评分权限
     * @param providerEntId 供应商企业id
     * @param scoreId 评分id
     * @return 评分id集合
     */
    private KwcContractLogisticsScore checkLogisticsScoreAuth(Long providerEntId,Long scoreId){
        KwcContractLogisticsScore logisticsScore = kwcContractLogisticsScoreMapper.selectLogisticsScoreByEntIdAndScoreId(providerEntId,scoreId);
        if(logisticsScore == null){
            throw new BusinessException("无当前评分记录权限");
        }
        return logisticsScore;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void initLogisticsScore(LogisticListReq.TradeBaseInfo baseInfo) {
        KwcContractLogisticsScore logisticsScore = new KwcContractLogisticsScore();

        long scoreId = new IdWorker(1L).nextId();
        logisticsScore.setId(scoreId);
        //自动派单合同的托运单位等于当前登陆企业
        logisticsScore.setProviderEntId(baseInfo.getProvideEntId());
        logisticsScore.setLogisticsEntId(baseInfo.getPurchaseEntId());
        logisticsScore.setScore(new BigDecimal(customConfig.getLogisticsInitScore()));
        logisticsScore.setCreateBy(LoginUserHolder.getUserId());
        Date date = new Date();
        logisticsScore.setCreateTime(date);
        logisticsScore.setUpdateBy(LoginUserHolder.getUserId());
        logisticsScore.setUpdateTime(date);
        //判断是否存在,存在则不创建
        String lockKey = String.format(RedisConstant.LOGISTICS_SCORE_RECORD_INIT_KEY,logisticsScore.getProviderEntId(),logisticsScore.getLogisticsEntId());
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            throw new BusinessException("业务繁忙，请稍后再试!");
        }
        try {
            if(kwcContractLogisticsScoreMapper.selectLogisticsScoreByEntId(baseInfo.getProvideEntId(),baseInfo.getPurchaseEntId())==null){
                //初始化物流企业评分记录
                kwcContractLogisticsScoreMapper.insertKwcContractLogisticsScore(logisticsScore);
                //初始化物流企业评分明细
                LogisticsScoreDetailAddDto detailDto  = new LogisticsScoreDetailAddDto();
                detailDto.setScoreId(scoreId);
                detailDto.setInfluenceBy(LoginUserHolder.getUserId());
                detailDto.setAction("物流企业评分初始化");
                detailDto.setScoreChange(logisticsScore.getScore());
                detailDto.setScore(logisticsScore.getScore());
                detailDto.setStatus(NumberConstant.ONE);
                KwcContractLogisticsScoreDetail logisticsScoreDetail = initLogisticsScoreDetail(detailDto);

                //初始化司机评分
                updateDriverScore(logisticsScore,logisticsScoreDetail,1);
            }
        } finally {
            RedissonUtils.unlock(lockKey);
        }
    }


    @Override
    public KwcContractLogisticsScoreDetail initLogisticsScoreDetail(LogisticsScoreDetailAddDto detailDto) {
        KwcContractLogisticsScoreDetail logisticsScoreDetail = buildLogisticsScoreDetail(detailDto);
        logisticsScoreDetail.setScore(logisticsScoreDetail.getScoreChange());
        kwcContractLogisticsScoreDetailMapper.insertKwcContractLogisticsScoreDetail(logisticsScoreDetail);
        return logisticsScoreDetail;
    }


    /**
     * 审批物流企业评分明细
     *
     * @param approvalDto 审批参数
     * @param providerEntId 供应商企业id
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approvalLogisticsScoreDetail(LogisticsScoreApprovalDto approvalDto, Long providerEntId)
    {
        String lockKey = String.format(RedisConstant.LOGISTICS_SCORE_RECORD_APPROVAL_KEY,approvalDto.getScoreId());
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            throw new BusinessException("业务繁忙，请稍后再试!");
        }
        try {
            //校验评分权限
            KwcContractLogisticsScore logisticsScore = checkLogisticsScoreAuth(providerEntId,approvalDto.getScoreId());
            KwcContractLogisticsScoreDetail logisticsScoreDetail = kwcContractLogisticsScoreDetailMapper.selectLogisticsPendingScoreDetail(approvalDto.getScoreId());
            if(logisticsScoreDetail != null && Objects.equals(logisticsScoreDetail.getStatus(),NumberConstant.ZERO)){
                if(approvalDto.getApproval()==0){
                    //驳回,清除待审核评分
                    kwcContractLogisticsScoreDetailMapper.deleteKwcContractLogisticsScoreDetailById(logisticsScoreDetail.getId(),NumberConstant.ZERO);
                }else{
                    //通过
                    //校验分数扣减是否会超过上下限
                    BigDecimal score = logisticsScore.getScore();
                    BigDecimal resultScore = score.add(logisticsScoreDetail.getScoreChange());
                    double scoreDouble = resultScore.doubleValue();
                    if (scoreDouble < 0 || scoreDouble > 100) {
                        throw new BusinessException("通过后企业评分将超过100或小于0，请驳回");
                    }
                    //1、更新企业评分
                    logisticsScore.setScore(resultScore);
                    logisticsScore.setUpdateBy(LoginUserHolder.getUserId());
                    logisticsScore.setUpdateTime(new Date());
                    kwcContractLogisticsScoreMapper.updateKwcContractLogisticsScore(logisticsScore);
                    //2、修改待审评分状态
                    logisticsScoreDetail.setStatus(NumberConstant.ONE);
                    logisticsScoreDetail.setScore(resultScore);
                    logisticsScoreDetail.setUpdateBy(LoginUserHolder.getUserId());
                    logisticsScoreDetail.setUpdateTime(new Date());
                    kwcContractLogisticsScoreDetailMapper.updateKwcContractLogisticsScoreDetail(logisticsScoreDetail);
                    //修改司机评分
                    updateDriverScore(logisticsScore,logisticsScoreDetail,2);
                }
            }else{
                throw new BusinessException("该评分已审批完成");
            }
        } finally {
            RedissonUtils.unlock(lockKey);
        }
    }


    /**
     * 用户修改物流企业评分
     *
     * @param detailDto 物流企业评分
     * @return 结果
     */
    @Override
    public boolean insertLogisticsScoreDetailByUser(LogisticsScoreDetailAddDto detailDto,Long providerEntId)
    {
        //校验评分权限
        KwcContractLogisticsScore logisticsScore = checkLogisticsScoreAuth(providerEntId, detailDto.getScoreId());
        String lockKey = String.format(RedisConstant.LOGISTICS_SCORE_RECORD_UPDATE_KEY,detailDto.getScoreId());
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            throw new BusinessException("业务繁忙，请稍后再试!");
        }
        try {
            //校验是否已存在待审核评分
            KwcContractLogisticsScoreDetail dbScoreDetail = kwcContractLogisticsScoreDetailMapper.selectLogisticsPendingScoreDetail(detailDto.getScoreId());
            if(dbScoreDetail != null){
                throw new BusinessException("修改评分失败，存在待审核评分未处理");
            }
            //校验分数扣减是否会超过上下限
            BigDecimal score = logisticsScore.getScore();
            double scoreDouble = score.add(detailDto.getScoreChange()).doubleValue();
            if (scoreDouble < 0 || scoreDouble > 100) {
                throw new BusinessException("修改评分失败，评分不能低于0分或超过100分");
            }
            //用户修改评分
            detailDto.setInfluenceBy(LoginUserHolder.getUserId());
            detailDto.setStatus(NumberConstant.ZERO);
            detailDto.setAction("修改企业评分，原因："+detailDto.getAction());
            KwcContractLogisticsScoreDetail logisticsScoreDetail = buildLogisticsScoreDetail(detailDto);
            return SqlHelper.retBool(kwcContractLogisticsScoreDetailMapper.insertKwcContractLogisticsScoreDetail(logisticsScoreDetail));
        } finally {
            RedissonUtils.unlock(lockKey);
        }
    }


    /**
     * 系统修改物流企业评分
     *
     * @param detailDto 物流企业评分
     * @return 结果
     */
    @Override
    public boolean updateLogisticsScoreBySystem(LogisticsScoreDetailFeignDto detailDto)
    {
        //1.根据供应商企业id和物流企业查询物流企业评分
        KwcContractLogisticsScore logisticsScore = kwcContractLogisticsScoreMapper.selectLogisticsScoreByEntId(detailDto.getProviderEntId(),detailDto.getLogisticsEntId());
        //1、更新企业评分
        BigDecimal score = logisticsScore.getScore();
        //查询物流企业下所有的司机
        HttpResult driverCountRes = driverScoreFeignService.countDriver(detailDto.getLogisticsEntId());
        if(driverCountRes.getCode() == HttpStatus.SUCCESS_CODE  && (Integer)driverCountRes.getData()>0){
            //查询物流企业下的所有司机的总分
            HttpResult scoreCountRes = driverScoreFeignService.countDriverScore(new DriverScoreQuery(detailDto.getProviderEntId(),detailDto.getLogisticsEntId()));
            if(scoreCountRes.getCode() != HttpStatus.SUCCESS_CODE){
                log.error("查询物流企业下的所有司机的总分失败,响应信息如下：{}", JSON.toJSONString(scoreCountRes));
                throw new BusinessException("系统修改评分失败，请稍后再试");
            }
            BigDecimal driverScoreCount = (BigDecimal)scoreCountRes.getData();
            Integer driverCount =(Integer)driverCountRes.getData();
            //计算物流企业最新评分
            BigDecimal resultScore = driverScoreCount.divide(new BigDecimal(driverCount),2, RoundingMode.HALF_UP);
            //企业变动评分
            BigDecimal entScoreChange = resultScore.subtract(score);
            logisticsScore.setScore(resultScore);
            logisticsScore.setUpdateBy(LoginUserHolder.getUserId());
            logisticsScore.setUpdateTime(new Date());
            kwcContractLogisticsScoreMapper.updateKwcContractLogisticsScore(logisticsScore);
            //2.插入评分明细记录
            LogisticsScoreDetailAddDto detailAddDto = new LogisticsScoreDetailAddDto();
            detailAddDto.setScoreId(logisticsScore.getId());
            //根据影响人手机号查询影响人userId
            UserResDto userResDto = remoteSystemService.queryUserByPhone(detailDto.getPhone());
            if(userResDto != null){
                detailAddDto.setInfluenceBy(userResDto.getId());
            }
            StringBuilder actionBuilder = new StringBuilder(detailDto.getAction());
            if(detailDto.getScoreChange().compareTo(BigDecimal.ZERO)>0){
                actionBuilder.append("+");
            }
            detailAddDto.setAction(actionBuilder.append(detailDto.getScoreChange()).append("分").toString());
            detailAddDto.setScoreChange(entScoreChange);
            detailAddDto.setScore(resultScore);
            //2.设置评分状态为通过
            detailAddDto.setStatus(NumberConstant.ONE);
            //3.构建评分明细记录
            KwcContractLogisticsScoreDetail logisticsScoreDetail = buildLogisticsScoreDetail(detailAddDto);
            //4.插入数据
            return SqlHelper.retBool(kwcContractLogisticsScoreDetailMapper.insertKwcContractLogisticsScoreDetail(logisticsScoreDetail));
        }else{
            throw new BusinessException("查询物流企业司机数量失败");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void resetLogisticsScore(Long scoreId, Long providerEntId)
    {
        //1.校验供应商企业评分权限
        KwcContractLogisticsScore logisticsScore = checkLogisticsScoreAuth(providerEntId, scoreId);
        BigDecimal originScore = logisticsScore.getScore();
        String lockKey = String.format(RedisConstant.LOGISTICS_SCORE_RECORD_RESET_KEY,scoreId);
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            throw new BusinessException("业务繁忙，请稍后再试!");
        }
        try {
            //2.修改企业评分为初始化分
            logisticsScore.setScore(new BigDecimal(customConfig.getLogisticsInitScore()));
            logisticsScore.setUpdateBy(LoginUserHolder.getUserId());
            logisticsScore.setUpdateTime(new Date());
            kwcContractLogisticsScoreMapper.updateKwcContractLogisticsScore(logisticsScore);
            //3.评分明细中插入重置记录
            KwcContractLogisticsScoreDetail resetLogisticsScoreDetail = buildResetLogisticsScoreDetail(scoreId,originScore);
            kwcContractLogisticsScoreDetailMapper.insertKwcContractLogisticsScoreDetail(resetLogisticsScoreDetail);
            //4.清除待审核评分
            kwcContractLogisticsScoreDetailMapper.deleteKwcContractLogisticsScoreDetailByScoreId(logisticsScore.getId(),NumberConstant.ZERO);
            //重置司机评分
            updateDriverScore(logisticsScore,resetLogisticsScoreDetail,3);

        } finally {
            RedissonUtils.unlock(lockKey);
        }
    }


    private void updateDriverScore(KwcContractLogisticsScore logisticsScore,KwcContractLogisticsScoreDetail logisticsScoreDetail,Integer operatorType){
        UpdateDriverScoreDto updateDriverScoreDto = new UpdateDriverScoreDto();
        updateDriverScoreDto.setProviderEntId(logisticsScore.getProviderEntId());
        updateDriverScoreDto.setLogisticsEntId(logisticsScore.getLogisticsEntId());
        updateDriverScoreDto.setScoreChange(logisticsScoreDetail.getScoreChange());
        updateDriverScoreDto.setAfterUpdateLogisticsEntScore(logisticsScore.getScore());
        updateDriverScoreDto.setAction(logisticsScoreDetail.getAction());
        updateDriverScoreDto.setOperatorType(operatorType);
        HttpResult result = driverScoreFeignService.update(updateDriverScoreDto);
        if(result.getCode()!= HttpStatus.SUCCESS_CODE){
            log.error("更新司机评分失败,原因：{}",result.getMsg());
            throw new BusinessException("更新司机评分失败,原因："+result.getMsg());
        }
    }

    /**
     * 构建重置评分记录明细
     *
     * @param scoreId 评分id
     * @return 评分记录
     */
    private KwcContractLogisticsScoreDetail buildResetLogisticsScoreDetail(Long scoreId,BigDecimal originScore) {
        KwcContractLogisticsScoreDetail logisticsScoreDetail = new KwcContractLogisticsScoreDetail();
        long scoreDetailId = new IdWorker(1L).nextId();
        logisticsScoreDetail.setId(scoreDetailId);
        logisticsScoreDetail.setScoreId(scoreId);
        logisticsScoreDetail.setInfluenceBy(LoginUserHolder.getUserId());
        logisticsScoreDetail.setAction("重置企业评分");
        BigDecimal score = new BigDecimal(customConfig.getLogisticsInitScore());
        BigDecimal scoreChange = score.subtract(originScore);
        logisticsScoreDetail.setScore(score);
        logisticsScoreDetail.setScoreChange(scoreChange);
        logisticsScoreDetail.setStatus(NumberConstant.ONE);
        logisticsScoreDetail.setCreateBy(LoginUserHolder.getUserId());
        logisticsScoreDetail.setCreateTime(new Date());
        logisticsScoreDetail.setUpdateBy(LoginUserHolder.getUserId());
        logisticsScoreDetail.setUpdateTime(new Date());
        return logisticsScoreDetail;
    }


    private KwcContractLogisticsScoreDetail buildLogisticsScoreDetail(LogisticsScoreDetailAddDto detailDto) {
        KwcContractLogisticsScoreDetail logisticsScoreDetail = new KwcContractLogisticsScoreDetail();
        long scoreDetailId = new IdWorker(1L).nextId();
        logisticsScoreDetail.setId(scoreDetailId);
        logisticsScoreDetail.setScoreId(detailDto.getScoreId());
        logisticsScoreDetail.setInfluenceBy(detailDto.getInfluenceBy());
        logisticsScoreDetail.setAction(detailDto.getAction());
        logisticsScoreDetail.setScoreChange(detailDto.getScoreChange());
        logisticsScoreDetail.setScore(detailDto.getScore());
        logisticsScoreDetail.setStatus(detailDto.getStatus());
        logisticsScoreDetail.setCreateBy(LoginUserHolder.getUserId());
        logisticsScoreDetail.setCreateTime(new Date());
        logisticsScoreDetail.setUpdateBy(LoginUserHolder.getUserId());
        logisticsScoreDetail.setUpdateTime(new Date());
        return logisticsScoreDetail;
    }
}
