package com.njzscloud.supervisory.sys.stationletter.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njzscloud.common.security.support.UserDetail;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.biz.constant.AuditStatus;
import com.njzscloud.supervisory.biz.constant.BizObj;
import com.njzscloud.supervisory.biz.pojo.entity.BizAuditConfigEntity;
import com.njzscloud.supervisory.biz.service.BizAuditConfigService;
import com.njzscloud.supervisory.order.contant.CheckStatus;
import com.njzscloud.supervisory.order.contant.OrderCategory;
import com.njzscloud.supervisory.order.contant.OrderStatus;
import com.njzscloud.supervisory.order.pojo.result.OrderPagingResult;
import com.njzscloud.supervisory.station.pojo.entity.StationManageEntity;
import com.njzscloud.supervisory.station.service.StationManageService;
import com.njzscloud.supervisory.sys.auth.pojo.result.MyResult;
import com.njzscloud.supervisory.sys.stationletter.constant.WarnCategory;
import com.njzscloud.supervisory.sys.stationletter.mapper.StationLetterMapper;
import com.njzscloud.supervisory.sys.stationletter.pojo.AuditResult;
import com.njzscloud.supervisory.sys.stationletter.pojo.StationLetterEntity;
import com.njzscloud.supervisory.sys.stationletter.pojo.StationLetterResult;
import com.njzscloud.supervisory.sys.stationletter.service.StationLetterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.njzscloud.supervisory.constant.Constant.ROLE_JG;

/**
 * 站内信服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StationLetterServiceImpl implements StationLetterService {

    private final StationLetterMapper stationLetterMapper;
    private final BizAuditConfigService bizAuditConfigService;
    private final StationManageService stationManageService;

    @Override
    public StationLetterResult getPendingWarnList() {
        StationLetterResult result = new StationLetterResult();
        List<StationLetterEntity> entities = stationLetterMapper.selectPendingWarnList();
        for (StationLetterEntity entity : entities) {
            // 通过枚举类设置预警类型中文名称
            String warnCategoryName = getWarnCategoryName(entity.getWarnCategory());
            entity.setWarnCategoryName(warnCategoryName);
        }
        result.setWarnList(entities);

        List<AuditResult> auditResults = Lists.newArrayList();

        // 1.查询未删除并且待审核的公司数量，表为biz_company
        int companyCount = stationLetterMapper.selectPendingCompanyCount();
        AuditResult companyAudit = new AuditResult();
        companyAudit.setModuleType("company");
        companyAudit.setAuditName("待审核公司");
        companyAudit.setCount(companyCount);
        auditResults.add(companyAudit);

        // 2.查询未删除并且待审核的车辆数量，表为biz_truck
        int truckCount = stationLetterMapper.selectPendingTruckCount();
        AuditResult truckAudit = new AuditResult();
        truckAudit.setModuleType("truck");
        truckAudit.setAuditName("待审核车辆");
        truckAudit.setCount(truckCount);
        auditResults.add(truckAudit);

        // 3.查询未删除并且待审核的项目数量，表为biz_project
        int projectCount = stationLetterMapper.selectPendingProjectCount();
        AuditResult projectAudit = new AuditResult();
        projectAudit.setModuleType("project");
        projectAudit.setAuditName("待审核项目");
        projectAudit.setCount(projectCount);
        auditResults.add(projectAudit);

        // 4.查询未删除并且待审核的司机数量，表为biz_driver
        int driverCount = stationLetterMapper.selectPendingDriverCount();
        AuditResult driverAudit = new AuditResult();
        driverAudit.setModuleType("driver");
        driverAudit.setAuditName("待审核司机");
        driverAudit.setCount(driverCount);
        auditResults.add(driverAudit);

        // 5.查询未删除并且待审核的订单数量，表为order_info
        AuditResult orderAudit = buildOrderAuditResult();
        auditResults.add(orderAudit);

        // 6.查询司机端：待接单订单数量
        MyResult userDetail = SecurityUtil.loginUser();
        Long userId = SecurityUtil.currentUserId();
        BizObj bizObj = userDetail.getBizObj();
        AuditResult sjAudit = new AuditResult();
        sjAudit.setModuleType("sjOrder");
        sjAudit.setAuditName("司机待接单");
        if (BizObj.isDriver(bizObj)) {
            QueryWrapper<OrderPagingResult> queryWrapper = Wrappers.query();
            queryWrapper.eq("a.order_status", OrderStatus.DaiJieDan)
                    .in("a.order_category", OrderCategory.DuanBoRu, OrderCategory.PuTong)
                    .eq("f.user_id", userId);
            int sjOrderCount = stationLetterMapper.selectPendingOrderCount(queryWrapper);
            sjAudit.setCount(sjOrderCount);
        } else {
            sjAudit.setCount(0);
        }
        auditResults.add(sjAudit);

        // 7.查询清运公司端：待派单订单数量
        AuditResult transAudit = new AuditResult();
        transAudit.setModuleType("transOrder");
        transAudit.setAuditName("清运公司待派单");
        if (BizObj.isTrans(bizObj)) {
            QueryWrapper<OrderPagingResult> queryWrapper = Wrappers.query();
            queryWrapper.in("a.order_status", OrderStatus.DaiPaiDan, OrderStatus.DaiJieDan)
                    .in("a.order_category", OrderCategory.DuanBoRu, OrderCategory.PuTong)
                    .eq("g.user_id", userId);
            int transOrderCount = stationLetterMapper.selectPendingOrderCount(queryWrapper);
            transAudit.setCount(transOrderCount);
        } else {
            transAudit.setCount(0);
        }
        auditResults.add(transAudit);

        // 8.查询勘料员端：待勘料订单数量
        AuditResult klyAudit = new AuditResult();
        klyAudit.setModuleType("klyOrder");
        klyAudit.setAuditName("勘料员待勘料");
        List<StationManageEntity> stationManageEntityList = stationManageService.list(Wrappers.lambdaQuery(StationManageEntity.class)
                .eq(StationManageEntity::getUserId, userDetail.getUserId()));
        if (null != stationManageEntityList && stationManageEntityList.size() > 0) {
            List<Long> collect = stationManageEntityList.stream().map(StationManageEntity::getStationId).collect(Collectors.toList());
            QueryWrapper<OrderPagingResult> queryWrapper = Wrappers.query();
            queryWrapper.eq("check_status", CheckStatus.WeiKanLiao)
                    .eq("order_status", OrderStatus.YiJinChang)
                    .in("station_id", collect);
            int klyOrderCount = stationLetterMapper.selectPendingKlyOrderCount(queryWrapper);
            klyAudit.setCount(klyOrderCount);
        } else {
            klyAudit.setCount(0);
        }
        auditResults.add(klyAudit);
        result.setAuditResultList(auditResults);
        return result;
    }

    /**
     * 构建订单审核结果
     */
    private AuditResult buildOrderAuditResult() {
        AuditResult orderAudit = new AuditResult();
        orderAudit.setModuleType("order");
        orderAudit.setAuditName("待审核订单");

        try {
            UserDetail userDetail = SecurityUtil.loginUser();
            if (userDetail == null || CollUtil.isEmpty(userDetail.getRoles())) {
                orderAudit.setCount(0);
                return orderAudit;
            }

            Set<String> roles = userDetail.getRoles();
            if (!roles.contains(ROLE_JG)) {
                orderAudit.setCount(0);
                return orderAudit;
            }

            // 获取审核配置区域信息
            AuditAreaInfo auditAreaInfo = getAuditAreaInfoByRoles(roles);
            if (CollUtil.isEmpty(auditAreaInfo.getAreaList()) &&
                    CollUtil.isEmpty(auditAreaInfo.getCityList()) &&
                    CollUtil.isEmpty(auditAreaInfo.getCityAreaList())) {
                orderAudit.setCount(0);
                return orderAudit;
            }

            // 构建查询条件
            QueryWrapper<OrderPagingResult> queryWrapper = buildOrderQueryWrapper(auditAreaInfo)
                    .in("a.order_category", OrderCategory.DuanBoRu, OrderCategory.PuTong);
            int orderCount = stationLetterMapper.selectPendingOrderCount(queryWrapper);
            orderAudit.setCount(orderCount);

        } catch (Exception e) {
            log.error("查询待审核订单数量失败", e);
            orderAudit.setCount(0);
        }

        return orderAudit;
    }

    /**
     * 根据角色获取审核配置区域信息
     */
    private AuditAreaInfo getAuditAreaInfoByRoles(Set<String> roles) {
        // 获取区级审核区域
        List<String> areaList = bizAuditConfigService.list(Wrappers.<BizAuditConfigEntity>lambdaQuery()
                        .in(BizAuditConfigEntity::getAreaRole, roles)).stream()
                .map(BizAuditConfigEntity::getArea)
                .distinct()
                .collect(Collectors.toList());

        // 获取市级审核区域
        List<String> cityList = bizAuditConfigService.list(Wrappers.<BizAuditConfigEntity>lambdaQuery()
                        .in(BizAuditConfigEntity::getCityRole, roles)).stream()
                .map(BizAuditConfigEntity::getArea)
                .distinct()
                .collect(Collectors.toList());

        // 获取无角色限制的区域
        List<String> cityAreaList = bizAuditConfigService.list(Wrappers.<BizAuditConfigEntity>lambdaQuery()
                        .isNull(BizAuditConfigEntity::getAreaRole)
                        .isNull(BizAuditConfigEntity::getCityRole)).stream()
                .map(BizAuditConfigEntity::getArea)
                .distinct()
                .collect(Collectors.toList());

        return new AuditAreaInfo(areaList, cityList, cityAreaList);
    }

    /**
     * 构建订单查询条件
     */
    private QueryWrapper<OrderPagingResult> buildOrderQueryWrapper(AuditAreaInfo auditAreaInfo) {
        QueryWrapper<OrderPagingResult> queryWrapper = Wrappers.query();

        // 基础条件：订单状态为已接单
        queryWrapper.eq("a.order_status", OrderStatus.YiJieDan);

        // 根据审核状态和区域构建复杂查询条件
        queryWrapper.and(wrapper -> {
            // 区级审核条件：区域在区级审核列表中且状态为区待审核
            if (CollUtil.isNotEmpty(auditAreaInfo.getAreaList())) {
                wrapper.in("b.area", auditAreaInfo.getAreaList())
                        .eq("a.audit_status", AuditStatus.QuDaiShenHe);
            }

            // 市级审核条件：区域在市级审核列表中且状态为市待审核
            if (CollUtil.isNotEmpty(auditAreaInfo.getCityList())) {
                wrapper.or(subWrapper ->
                        subWrapper.in("b.area", auditAreaInfo.getCityList())
                                .eq("a.audit_status", AuditStatus.ShiDaiShenHe)
                );
            }

            // 待审核条件：区域在无角色限制列表中且状态为待审核
            if (CollUtil.isNotEmpty(auditAreaInfo.getCityAreaList())) {
                wrapper.or(subWrapper ->
                        subWrapper.in("b.area", auditAreaInfo.getCityAreaList())
                                .eq("a.audit_status", AuditStatus.DaiShenHe)
                );
            }
        });

        return queryWrapper;
    }

    /**
     * 审核区域信息内部类
     */
    private static class AuditAreaInfo {
        private final List<String> areaList;
        private final List<String> cityList;
        private final List<String> cityAreaList;

        public AuditAreaInfo(List<String> areaList, List<String> cityList, List<String> cityAreaList) {
            this.areaList = areaList;
            this.cityList = cityList;
            this.cityAreaList = cityAreaList;
        }

        public List<String> getAreaList() {
            return areaList;
        }

        public List<String> getCityList() {
            return cityList;
        }

        public List<String> getCityAreaList() {
            return cityAreaList;
        }
    }

    /**
     * 根据预警类型代码获取中文名称
     */
    private String getWarnCategoryName(String warnCategory) {
        if (warnCategory == null) {
            return "未知类型";
        }

        for (WarnCategory category : WarnCategory.values()) {
            if (category.getVal().equals(warnCategory)) {
                return category.getTxt();
            }
        }
        return "未知类型";
    }

}
