package com.ningdatech.carapi.driver.manage;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Component;

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.model.PageVo;
import com.ningdatech.carapi.common.aop.BuildChildrenRegionWrapper;
import com.ningdatech.carapi.common.constant.UserRoleTypeEnum;
import com.ningdatech.carapi.common.util.CodeUtil;
import com.ningdatech.carapi.datascope.aop.LambdaDataScope;
import com.ningdatech.carapi.driver.constant.ExamQualifiedEnum;
import com.ningdatech.carapi.driver.entity.Certificate;
import com.ningdatech.carapi.driver.entity.ExamRecordDetail;
import com.ningdatech.carapi.driver.model.po.ReqListExamRecordPO;
import com.ningdatech.carapi.driver.model.vo.ResListExamRecordVO;
import com.ningdatech.carapi.driver.service.ICertificateService;
import com.ningdatech.carapi.driver.service.IExamRecordDetailService;
import com.ningdatech.carapi.user.security.auth.model.UserInfoDetails;
import com.ningdatech.carapi.user.util.LoginUserUtil;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;

/**
 * @author liuxinxin
 * @date 2022/10/26 下午5:13
 */
@Component
@RequiredArgsConstructor
public class ExamRecordManage {

    private final IExamRecordDetailService iExamRecordDetailService;
    private final ICertificateService iCertificateService;


    public PageVo<ResListExamRecordVO> listExamRecord(ReqListExamRecordPO request) {

        // 按照登录用户，如果是驾驶员登录，只展示该驾驶员信息
        UserInfoDetails userDetail = LoginUserUtil.loginUserDetail();
        Long roleId = userDetail.getRoleId();

        Integer pageNumber = request.getPageNumber();
        Integer pageSize = request.getPageSize();

        LambdaQueryWrapper<ExamRecordDetail> wrapper = Wrappers.lambdaQuery(ExamRecordDetail.class);
        ExamRecordManage context = (ExamRecordManage) AopContext.currentProxy();
        context.buildExamRecordQuery(wrapper, request);

        if (UserRoleTypeEnum.DRIVER_ROLE_ID.getId().equals(roleId)) {
            Long userId = userDetail.getUserId();
            wrapper.eq(ExamRecordDetail::getDriverUserId,userId);
        }
        Page<ExamRecordDetail> page = iExamRecordDetailService.page(new Page<>(pageNumber, pageSize),wrapper);
        if (0L == page.getTotal()) {
            return PageVo.empty();
        }
        List<ExamRecordDetail> records = page.getRecords();
        List<Long> driverUserIdList = records.stream().map(ExamRecordDetail::getDriverUserId).collect(Collectors.toList());
        List<Certificate> certificateList = iCertificateService.list(Wrappers.lambdaQuery(Certificate.class)
                .in(Certificate::getUserId, driverUserIdList));
        Map<Long, String> userIdCertificateNoMap = certificateList.stream().collect(Collectors.toMap(Certificate::getDriverId, Certificate::getCertificateNo));

        List<ResListExamRecordVO> resVoList = records.stream().map(r -> {
            ResListExamRecordVO resVO = BeanUtil.copyProperties(r,ResListExamRecordVO.class);
            resVO.setIsQualified(ExamQualifiedEnum.valueOf(r.getExamResult()));
            resVO.setCertificateNo(userIdCertificateNoMap.get(r.getDriverId()));
            resVO.setExamType(r.getExamType());
            CodeUtil.searchCompanyNameAndRegionName(resVO);
            return resVO;
        }).collect(Collectors.toList());
        return PageVo.of(resVoList,page.getTotal());
    }

    @LambdaDataScope
    @BuildChildrenRegionWrapper
    public void buildExamRecordQuery(LambdaQueryWrapper<ExamRecordDetail> wrapper, ReqListExamRecordPO request) {
        String companyName = request.getCompanyName();
        String driverName = request.getDriverName();
        ExamQualifiedEnum isQualified = request.getIsQualified();
        LocalDateTime startTime = request.getStartTime();
        LocalDateTime endTime = request.getEndTime();
        String isQualifiedStr = Objects.nonNull(isQualified) ? isQualified.name() : null;

        wrapper .like(StringUtils.isNotBlank(companyName), ExamRecordDetail::getCompanyName, companyName)
                .like(StringUtils.isNotBlank(driverName), ExamRecordDetail::getDriverName, driverName)
                .eq(StringUtils.isNotBlank(isQualifiedStr), ExamRecordDetail::getExamResult, isQualifiedStr)
                .gt(Objects.nonNull(startTime), ExamRecordDetail::getExamTime, startTime)
                .lt(Objects.nonNull(endTime), ExamRecordDetail::getExamTime, endTime)
                .orderByDesc(ExamRecordDetail::getExamTime);
    }
}
