package com.clx.performance.service.impl.collect;

import com.clx.performance.dao.collect.CollectDriverTransportIntentionDao;
import com.clx.performance.dao.collect.CollectDriverTransportIntentionRecordDao;
import com.clx.performance.dao.collect.DriverTransportIntentionInfoDao;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.model.collect.CollectDriverTransportIntention;
import com.clx.performance.model.collect.CollectDriverTransportIntentionRecord;
import com.clx.performance.model.collect.DriverTransportIntentionInfo;
import com.clx.performance.param.app.collect.AppCarrierDriverCollectChildParam;
import com.clx.performance.param.app.collect.AppCarrierDriverCollectMainParam;
import com.clx.performance.param.app.collect.AppCarrierDriverCollectSaveParam;
import com.clx.performance.service.collect.DriverTransportIntentionInfoService;
import com.clx.performance.struct.collect.CollectDriverTransportIntentionDaoStruct;
import com.clx.performance.struct.collect.CollectDriverTransportIntentionRecordDaoStruct;
import com.clx.performance.vo.pc.collect.CarrierDriverCollectTransportIntentionRecordVO;
import com.clx.performance.vo.pc.collect.CarrierDriverCollectTransportIntentionVO;
import com.msl.common.exception.ServiceSystemException;
import com.msl.user.utils.TokenUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kavin
 * Date 2024-10-18
 * Time 18:03
 */
@Service
@Slf4j
@AllArgsConstructor
public class DriverTransportIntentionInfoServiceImpl implements DriverTransportIntentionInfoService {

    private final DriverTransportIntentionInfoDao driverTransportIntentionInfoDao;
    private final CollectDriverTransportIntentionDao collectDriverTransportIntentionDao;
    private final CollectDriverTransportIntentionRecordDao collectDriverTransportIntentionRecordDao;
    private final CollectDriverTransportIntentionDaoStruct collectDriverTransportIntentionDaoStruct;
    private final CollectDriverTransportIntentionRecordDaoStruct collectDriverTransportIntentionRecordDaoStruct;

    @Override
    public void saveCheckedList(AppCarrierDriverCollectSaveParam param) {
        if (Objects.isNull(param) || CollectionUtils.isEmpty(param.getParamList())) {
            log.info("driverTransportIntentionInfoServiceImpl saveCheckedList param is null");
            throw new ServiceSystemException(PerformanceResultEnum.DATA_NOT_FIND);
        }

        if (this.existUpdateChange(param.getCurrentTime())) {
            log.info("driverTransportIntentionInfoServiceImpl saveCheckedList existUpdateChange");
            // 返回异常错误码
            throw new ServiceSystemException(PerformanceResultEnum.DRIVER_TRANSPORT_INTENTION_HAPPEN_CHANGE_ERROR_MSG);
        }

        List<DriverTransportIntentionInfo> driverTransportIntentionInfoList = new ArrayList<>();
        for (AppCarrierDriverCollectMainParam saveParam : param.getParamList()) {
            if (CollectionUtils.isEmpty(saveParam.getRecordList())) {
                log.info("driverTransportIntentionInfoServiceImpl saveCheckedList saveParam is null");
                throw new ServiceSystemException(PerformanceResultEnum.DATA_NOT_FIND);
            }
            // 遍历已勾选的选项
            for (AppCarrierDriverCollectChildParam collectChildParam : saveParam.getRecordList()) {
                DriverTransportIntentionInfo driverTransportIntentionInfo = new DriverTransportIntentionInfo();
                driverTransportIntentionInfo.setCollectTransportIntentionId(saveParam.getId());
                driverTransportIntentionInfo.setCollectTransportIntentionName(saveParam.getCollectName());
                driverTransportIntentionInfo.setCollectTransportIntentionRecordId(collectChildParam.getCollectRecordId());
                driverTransportIntentionInfo.setCollectTransportIntentionRecordName(collectChildParam.getCollectRecordName());
                driverTransportIntentionInfo.setCreateUserNo(TokenUtil.getLoginUserInfo().getUserNo());
                driverTransportIntentionInfo.setCreateUserName(TokenUtil.getLoginUserInfo().getUserName());
                driverTransportIntentionInfo.setCreateTime(LocalDateTime.now());
                driverTransportIntentionInfo.setModifiedTime(LocalDateTime.now());
                driverTransportIntentionInfoList.add(driverTransportIntentionInfo);
            }
        }
        driverTransportIntentionInfoDao.saveBatchList(driverTransportIntentionInfoList);
    }

    @Override
    public List<CarrierDriverCollectTransportIntentionVO> getCurrentUserCheckInfo() {
        // 1.根据当前用户查询所有记录
        List<DriverTransportIntentionInfo> driverTransportIntentionInfoList =
                driverTransportIntentionInfoDao.listByField(DriverTransportIntentionInfo::getCreateUserNo,
                        TokenUtil.getLoginUserInfo().getUserNo());
        if (CollectionUtils.isEmpty(driverTransportIntentionInfoList)) {
            log.info("driverTransportIntentionInfoServiceImpl getCurrentUserCheckInfo driverTransportIntentionInfoList is null");
            return null;
        }

        // 2.组装主子表
        // 主表id
        Set<Integer> idList = driverTransportIntentionInfoList.stream()
                .map(DriverTransportIntentionInfo::getCollectTransportIntentionId).collect(Collectors.toSet());
        // 子表id
        Set<Integer> idRecordList = driverTransportIntentionInfoList.stream()
                .map(DriverTransportIntentionInfo::getCollectTransportIntentionRecordId).collect(Collectors.toSet());

        List<CollectDriverTransportIntention> intentionList
                = collectDriverTransportIntentionDao.listInField(CollectDriverTransportIntention::getId, idList);
        List<CarrierDriverCollectTransportIntentionVO> intentionVOList
                = collectDriverTransportIntentionDaoStruct.covertList(intentionList);

        List<CollectDriverTransportIntentionRecord> intentionRecordList
                = collectDriverTransportIntentionRecordDao.listInField(CollectDriverTransportIntentionRecord::getId, idRecordList);
        List<CarrierDriverCollectTransportIntentionRecordVO> intentionRecordVOList
                = collectDriverTransportIntentionRecordDaoStruct.covertList(intentionRecordList);
        // 构建map
        Map<Integer, List<CarrierDriverCollectTransportIntentionRecordVO>> recordMap
                = intentionRecordVOList.stream().collect(Collectors
                .groupingBy(CarrierDriverCollectTransportIntentionRecordVO::getCollectDriverTransportIntentionId));

        for (CarrierDriverCollectTransportIntentionVO vo : intentionVOList) {
            if (recordMap.containsKey(vo.getId())) {
                vo.setCollectIntentionRecordList(recordMap.get(vo.getId()));
            }
        }
        // 3.返回数据
        return intentionVOList;
    }

    public boolean existUpdateChange(String currentTime) {
        // 获取当前时间
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.parse(currentTime, ftf);
        // 获取主表最新一次更新时间
        LocalDateTime intentionLastUpdateTime =collectDriverTransportIntentionDao.getLastUpdateTime();
        // 获取子表最新一次更新时间
        LocalDateTime intentionRecordLastUpdateTime = collectDriverTransportIntentionRecordDao.getLastUpdateTime();
        // 当前时间在主表和子表更新时间之前，说明有更新
        return now.isBefore(intentionLastUpdateTime) || now.isBefore(intentionRecordLastUpdateTime);
    }
}
