package com.ningdatech.carapi.qrcode.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.exception.code.ExceptionCode;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.carapi.car.vehicle.model.dto.VehicleArchivesQueryDTO;
import com.ningdatech.carapi.car.vehicle.manage.VehicleManage;
import com.ningdatech.carapi.common.constant.VehicleTypeEnum;
import com.ningdatech.carapi.driver.entity.DriverInfo;
import com.ningdatech.carapi.driver.helper.DriverInfoHelper;
import com.ningdatech.carapi.driver.manage.DriverArchivesManage;
import com.ningdatech.carapi.driver.model.po.ReqGetArchivalInfoReviewDetailPO;
import com.ningdatech.carapi.driver.model.vo.ResArchivalInfoDetailVO;
import com.ningdatech.carapi.driver.model.vo.ResArchivalInfoSearchListVO;
import com.ningdatech.carapi.driver.service.IDriverInfoService;
import com.ningdatech.carapi.qrcode.entity.NdVehicleGetOn;
import com.ningdatech.carapi.qrcode.model.dto.GetOnVehicleDTO;
import com.ningdatech.carapi.qrcode.model.dto.VehicleGetOnPageQuery;
import com.ningdatech.carapi.qrcode.model.vo.GetOnVehicleVO;
import com.ningdatech.carapi.qrcode.service.VehicleGetOnService;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.user.util.LoginUserUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @Classname OrcodeManage
 * @Description
 * @Date 2022/10/18 14:39
 * @Created by PoffyZhang
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class QrcodeManage {

    private final IDriverInfoService driverInfoService;
    private final VehicleGetOnService vehicleGetOnService;
    private final VehicleManage vehicleManage;
    private final DriverArchivesManage driverArchivesManage;
    private final RegionsCacheHelper regionsCacheHelper;
    private final DriverInfoHelper driverInfoHelper;

    /**
     * 获取当前登录驾驶员信息
     *
     * @return
     */
    public ResArchivalInfoSearchListVO queryLoginedDriver() {
        Long userId = LoginUserUtil.getUserId();
        if (Objects.isNull(userId)) {
            throw new BizException(ExceptionCode.JWT_NOT_LOGIN.getCode(), "请确认当前驾驶员已登录");
        }

        LambdaQueryWrapper<DriverInfo> driverInfoLambdaQueryWrappery = Wrappers.lambdaQuery(DriverInfo.class)
                .eq(DriverInfo::getUserId, userId)
                .orderByDesc(DriverInfo::getUpdateOn);
        DriverInfo driveInfo = driverInfoService.getOne(driverInfoLambdaQueryWrappery);
        if (Objects.isNull(driveInfo)) {
            throw new BizException("驾驶员信息不存在!");
        }
        ResArchivalInfoSearchListVO res = BeanUtil.copyProperties(driveInfo, ResArchivalInfoSearchListVO.class);
        res.setDriverId(driveInfo.getId());
        return res;
    }

    public PageVo<GetOnVehicleVO> getOnList(VehicleGetOnPageQuery vehicleArchivesPageQuery) {
        Page<NdVehicleGetOn> page = vehicleArchivesPageQuery.page();
        LambdaQueryWrapper<NdVehicleGetOn> wrapper = Wrappers.lambdaQuery(NdVehicleGetOn.class);
        buildWrapper(wrapper, vehicleArchivesPageQuery);
        vehicleGetOnService.page(page, wrapper);
        List<GetOnVehicleVO> data = CollUtils.convert(page.getRecords(), e -> BeanUtil.copyProperties(e, GetOnVehicleVO.class));
        return PageVo.of(data, page.getTotal());
    }

    private void buildWrapper(LambdaQueryWrapper<NdVehicleGetOn> wrapper, VehicleGetOnPageQuery vehicleArchivesPageQuery) {
        if (Objects.nonNull(vehicleArchivesPageQuery.getRegionId())) {
            List<Long> regionIds = regionsCacheHelper.listChildRegionId(vehicleArchivesPageQuery.getRegionId());
            wrapper.in(CollUtil.isNotEmpty(regionIds), NdVehicleGetOn::getRegionId, regionIds);
        }
        wrapper.like(StringUtils.isNotBlank(vehicleArchivesPageQuery.getCarPlate()), NdVehicleGetOn::getCarPlate, vehicleArchivesPageQuery.getCarPlate())
                .like(StringUtils.isNotBlank(vehicleArchivesPageQuery.getCompanyName()), NdVehicleGetOn::getCompanyName, vehicleArchivesPageQuery.getCompanyName())
                .eq(Objects.nonNull(vehicleArchivesPageQuery.getVehicleType()), NdVehicleGetOn::getVehicleType, vehicleArchivesPageQuery.getVehicleType())
                .like(StringUtils.isNotBlank(vehicleArchivesPageQuery.getDriverName()), NdVehicleGetOn::getDriverName, vehicleArchivesPageQuery.getDriverName())
                .like(StringUtils.isNotBlank(vehicleArchivesPageQuery.getOperatorName()), NdVehicleGetOn::getOperatorName, vehicleArchivesPageQuery.getOperatorName())
                .ge(Objects.nonNull(vehicleArchivesPageQuery.getStartTime()), NdVehicleGetOn::getCreateOn, vehicleArchivesPageQuery.getStartTime())
                .le(Objects.nonNull(vehicleArchivesPageQuery.getEndTime()), NdVehicleGetOn::getCreateOn, vehicleArchivesPageQuery.getEndTime())
                .orderBy(Boolean.TRUE, Boolean.FALSE, NdVehicleGetOn::getCreateOn);
    }

    /**
     * 扫码上车
     *
     * @param data
     * @return
     */
    public GetOnVehicleVO getOnVehicle(GetOnVehicleDTO data, Long userId) {
        driverInfoHelper.driverCertificateValidCheck(userId);

        NdVehicleGetOn vehicleGetOn = BeanUtil.toBean(data, NdVehicleGetOn.class);
        //进行业务处理
        //1.查询车辆信息
        VehicleArchivesQueryDTO vehicleDetails = vehicleManage.getDetails(data.getVehicleId());
        if (Objects.isNull(vehicleDetails)) {
            throw new BizException(ExceptionCode.NOT_FOUND.getCode(), "找不到目标车辆 {}", data.getVehicleId());
        }
        //2.查询驾驶员信息
        ReqGetArchivalInfoReviewDetailPO po = new ReqGetArchivalInfoReviewDetailPO();
        po.setDriverId(data.getDriverId());
        ResArchivalInfoDetailVO archivalInfoDetail = driverArchivesManage.getDriverDetail(po);
        if (Objects.isNull(archivalInfoDetail)) {
            throw new BizException(ExceptionCode.NOT_FOUND.getCode(), "找不到目标驾驶员 {}", data.getVehicleId());
        }
        //3.拼接信息存入上车表
        vehicleGetOn.setCarPlate(vehicleDetails.getCarPlate());
        vehicleGetOn.setPlateColor(vehicleDetails.getPlateColor());
        vehicleGetOn.setCompanyId(vehicleDetails.getCompanyId());
        vehicleGetOn.setCompanyName(vehicleDetails.getCompanyName());
        vehicleGetOn.setDriverName(archivalInfoDetail.getDriverName());
        vehicleGetOn.setOperatorName(vehicleDetails.getOperatorName());
        vehicleGetOn.setRegionId(vehicleDetails.getRegionId());
        vehicleGetOn.setRegionName(vehicleDetails.getRegionName());
        if (Objects.nonNull(vehicleDetails.getVehicleType())) {
            vehicleGetOn.setVehicleType(vehicleDetails.getVehicleType());
            vehicleGetOn.setVehicleTypeName(VehicleTypeEnum.getDescByCode(vehicleDetails.getVehicleType()));
        }
        //创建人 最后修改人
        vehicleGetOn.setCreateBy(userId);
        vehicleGetOn.setUpdateBy(userId);
        vehicleGetOnService.save(vehicleGetOn);
        return BeanUtil.toBean(vehicleGetOn, GetOnVehicleVO.class);
    }
}
