package com.gci.boot.modules.vehicles.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.annotation.Query.handle.QueryGenerator;
import com.gci.boot.common.vo.Result;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.modules.system.entity.SysPermission;
import com.gci.boot.modules.system.service.ISysPermissionService;
import com.gci.boot.modules.system.vo.LoginUser;
import com.gci.boot.modules.vehicles.controller.*;
import com.gci.boot.modules.vehicles.entity.*;
import com.gci.boot.modules.vehicles.enums.BacklogEnum;
import com.gci.boot.modules.vehicles.enums.BacklogTabEnum;
import com.gci.boot.modules.vehicles.query.AccidentInfoQuery;
import com.gci.boot.modules.vehicles.query.AnnualInspectionInfoQuery;
import com.gci.boot.modules.vehicles.query.AnnualInspectionRemindQuery;
import com.gci.boot.modules.vehicles.service.BacklogService;
import com.gci.boot.modules.vehicles.vo.BacklogStatisVO;
import com.gci.boot.modules.vehicles.vo.RepairInfoListVO;
import com.gci.boot.modules.vehicles.vo.UpkeepInfoListVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@Slf4j
public class BacklogServiceImpl implements BacklogService {
    @Autowired
    private ISysPermissionService sysPermissionService;
    @Autowired
    private RepairController repairController;
    @Autowired
    private UpKeepBillController upKeepBillController;
    @Autowired
    private UpKeepPlanController upKeepPlanController;
    @Autowired
    private TbInsuranceRecordController insuranceRecordController;
    @Autowired
    private TbViolationRecordController violationRecordController;
    @Autowired
    private TbAccidentInfoController accidentInfoController;
    @Autowired
    private TbAnnualInspectionRemindController annualInspectionRemindController;
    @Autowired
    private TbInsuranceRemindController insuranceRemindController;

    @Override
    public Map<String, List<Integer>> getUserBacklogButton() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysPermission> metaList = sysPermissionService.queryByUser(sysUser.getUsername());
        Map<String, List<Integer>> map = new HashMap<>();
        for (SysPermission permission : metaList) {
            if(permission.getMenuType()==null) {
                continue;
            }
            if(permission.getMenuType().equals(CommonConstant.MENU_TYPE_BUTTON) &&CommonConstant.STATUS_1.equals(permission.getStatus())) {
                BacklogEnum backlogEnum = BacklogEnum.getEnum(permission.getPerms());
                if(Objects.nonNull(backlogEnum)){
                    List<Integer> list = map.get(backlogEnum.getMenu());
                    if(CollectionUtils.isEmpty(list)){
                        map.put(backlogEnum.getMenu(), Collections.singletonList(backlogEnum.getDataStatus()));
                    }else{
                        List<Integer> tempList = new ArrayList<>(list);
                        tempList.add(backlogEnum.getDataStatus());
                        map.put(backlogEnum.getMenu(), tempList);
                    }
                }
            }
        }
        return map;
    }

    //1出险 2违章 3事故 4维修 5保养台账 6年检 7保养计划
    @Override
    public Result getBacklogPageList(Integer pageNo, Integer pageSize, String type, HttpServletRequest req) {
        //获取用户对应待办按钮
        Map<String, List<Integer>> map = getUserBacklogButton();
        List<Integer> statusList = map.getOrDefault(type,new ArrayList<>());
        //获取用户对用tab,没权限的不给查看
        List<String> menuTabs = new ArrayList<>();
        if(map != null && !map.isEmpty()){
            menuTabs.addAll(map.keySet());
        }
        if(!menuTabs.contains(type)){
            return Result.error(101,"没有权限!");
        }

        if(BacklogTabEnum.INSURANCE.getType().equals(type)){
            TbInsuranceRecord insuranceRecord = new TbInsuranceRecord();
            if(CollectionUtil.isEmpty(statusList)){
                insuranceRecord.setHandleStatus("-1");
            }else{
                insuranceRecord.setHandleStatus(statusList.get(0).toString());
            }
            Result insuranceResult = insuranceRecordController.page(insuranceRecord, pageNo, pageSize);
            return insuranceResult;
        }
        if(BacklogTabEnum.VIOLATION.getType().equals(type)){
            TbViolationRecord violationRecord = new TbViolationRecord();
            if(CollectionUtil.isEmpty(statusList)){
                violationRecord.setHandleResult(-1);
            }else{
                violationRecord.setHandleResult(statusList.get(0));
            }
            Result violationResult = violationRecordController.queryPageList(violationRecord, pageNo, pageSize,req);
            return violationResult;
        }
        if(BacklogTabEnum.ACCIDENT.getType().equals(type)){
            AccidentInfoQuery accidentInfoQuery = new AccidentInfoQuery();
            if(CollectionUtil.isEmpty(statusList)){
                accidentInfoQuery.setCaseClosed("-1");
            }else{
                accidentInfoQuery.setCaseClosed(statusList.get(0).toString());
            }
            Result accidentResult = accidentInfoController.queryPageList(accidentInfoQuery, pageNo, pageSize,req);
            return accidentResult;
        }
        if(BacklogTabEnum.REPAIR.getType().equals(type)){
            if(CollectionUtil.isEmpty(statusList)){
                statusList.add(-1);
            }
            RepairInfoListVO vo = new RepairInfoListVO();
            vo.setFlowStatusList(statusList);
            Result result = repairController.queryPageList(vo, pageNo, pageSize,req);
            return result;
        }
        if(BacklogTabEnum.UPKEEP_BILL.getType().equals(type)){
            if(CollectionUtil.isEmpty(statusList)){
                statusList.add(-1);
            }
            UpkeepInfoListVO upkeepInfoListVO = new UpkeepInfoListVO();
            upkeepInfoListVO.setFlowStatusList(statusList);
            Result upkeepBillResult = upKeepBillController.queryPageList(upkeepInfoListVO, pageNo, pageSize,req);
            return upkeepBillResult;
        }
        if(BacklogTabEnum.INSPECTION.getType().equals(type)){
            AnnualInspectionRemindQuery query = new AnnualInspectionRemindQuery();
            if(CollectionUtil.isEmpty(statusList)){
                query.setRemindStatus("-1");
            }else{
                //提醒中
                query.setRemindStatus("1");
            }

            Result annualInspectionResult = annualInspectionRemindController.queryPageList(query, pageNo, pageSize,req);
            return annualInspectionResult;
        }
        if(BacklogTabEnum.UPKEEP_PLAN.getType().equals(type)){
            TbUpkeepPlan tbUpkeepPlan = new TbUpkeepPlan();
            if(CollectionUtil.isEmpty(statusList)){
                tbUpkeepPlan.setAuditStatus("-1");
            }else{
                tbUpkeepPlan.setAuditStatus(statusList.get(0).toString());
            }
            Result upkeepPlanResult = upKeepPlanController.queryPageList(tbUpkeepPlan, pageNo, pageSize,req);
            return upkeepPlanResult;
        }
        if(BacklogTabEnum.INSURANCE_LEDGER.getType().equals(type)){
            TbInsuranceRemind tbInsuranceRecord = new TbInsuranceRemind();
            if(CollectionUtil.isEmpty(statusList)){
                tbInsuranceRecord.setStatus("-1");
            }else{
                //提醒中
                tbInsuranceRecord.setStatus("1");
            }
            Result insuranceRemindResult = insuranceRemindController.page(tbInsuranceRecord, pageNo, pageSize);
            return insuranceRemindResult;
        }

        return null;
    }

    @Override
    public List<BacklogStatisVO> getBacklogStatis(HttpServletRequest req) {
        //获取用户对应待办按钮
        Map<String, List<Integer>> map = getUserBacklogButton();
        List<BacklogStatisVO> result = new ArrayList<>();
        //获取用户对用tab
        List<String> menuTabs = new ArrayList<>();
        if(map != null && !map.isEmpty()){
            menuTabs.addAll(map.keySet());
        }

        // 需要处理的 BacklogEnum 列表
        List<BacklogTabEnum> backlogTabEnums = Arrays.asList(
                BacklogTabEnum.INSURANCE_LEDGER,
                BacklogTabEnum.INSURANCE,
                BacklogTabEnum.VIOLATION,
                BacklogTabEnum.ACCIDENT,
                BacklogTabEnum.INSPECTION,
                BacklogTabEnum.REPAIR,
                BacklogTabEnum.UPKEEP_BILL,
                BacklogTabEnum.UPKEEP_PLAN
        );

        for (BacklogTabEnum backlogTabEnum : backlogTabEnums) {
            if(menuTabs.contains(backlogTabEnum.getType())){
                BacklogStatisVO backlogVo = new BacklogStatisVO();
                backlogVo.setType(backlogTabEnum.getType());
                backlogVo.setValue(backlogTabEnum.getValue());
                List<Integer> statusList = map.getOrDefault(backlogTabEnum.getType(),new ArrayList<>());
                backlogVo.setStatisCount(getPageCount(backlogTabEnum,statusList,req));
                result.add(backlogVo);
            }
        }
        return result;
    }


    private long getPageCount(BacklogTabEnum backlogEnum, List<Integer> statusList,HttpServletRequest req) {
        switch (backlogEnum) {
            case INSURANCE:
                TbInsuranceRecord insuranceRecord = new TbInsuranceRecord();
                if(CollectionUtil.isEmpty(statusList)){
                    insuranceRecord.setHandleStatus("-1");
                }else{
                    insuranceRecord.setHandleStatus(statusList.get(0).toString());
                }
                Result insuranceResult = insuranceRecordController.page(insuranceRecord, 1, 1);
                IPage<TbInsuranceRecord> insurancePageList = (IPage<TbInsuranceRecord>) insuranceResult.getResult();
                return insurancePageList.getTotal();
            case VIOLATION:
                TbViolationRecord violationRecord = new TbViolationRecord();
                if(CollectionUtil.isEmpty(statusList)){
                    violationRecord.setHandleResult(-1);
                }else{
                    violationRecord.setHandleResult(statusList.get(0));
                }
                Result violationResult = violationRecordController.queryPageList(violationRecord, 1, 1,req);
                IPage<TbViolationRecord> violationPageList = (IPage<TbViolationRecord>) violationResult.getResult();
                return violationPageList.getTotal();
            case ACCIDENT:
                AccidentInfoQuery accidentInfoQuery = new AccidentInfoQuery();
                if(CollectionUtil.isEmpty(statusList)){
                    accidentInfoQuery.setCaseClosed("-1");
                }else{
                    accidentInfoQuery.setCaseClosed(statusList.get(0).toString());
                }
                Result accidentResult = accidentInfoController.queryPageList(accidentInfoQuery, 1, 1,req);
                IPage<AccidentInfoQuery> accidentPageList = (IPage<AccidentInfoQuery>) accidentResult.getResult();
                return accidentPageList.getTotal();
            case INSPECTION:
                AnnualInspectionRemindQuery query = new AnnualInspectionRemindQuery();
                if(CollectionUtil.isEmpty(statusList)){
                    query.setRemindStatus("-1");
                }else{
                    //提醒中
                    query.setRemindStatus("1");
                }
                Result annualInspectionResult = annualInspectionRemindController.queryPageList(query, 1, 1,req);
                IPage<TbAnnualInspectionRemind> annualInspectionInfoIPage = (IPage<TbAnnualInspectionRemind>) annualInspectionResult.getResult();
                return annualInspectionInfoIPage.getTotal();
            case REPAIR:
                if(CollectionUtil.isEmpty(statusList)){
                    statusList.add(-1);
                }
                RepairInfoListVO repairInfoListVO = new RepairInfoListVO();
                repairInfoListVO.setFlowStatusList(statusList);
                Result repairResult = repairController.queryPageList(repairInfoListVO, 1, 1,req);
                IPage<RepairInfoListVO> repairPageList = (IPage<RepairInfoListVO>) repairResult.getResult();
                return repairPageList.getTotal();
            case UPKEEP_BILL:
                if(CollectionUtil.isEmpty(statusList)){
                    statusList.add(-1);
                }
                UpkeepInfoListVO upkeepInfoListVO = new UpkeepInfoListVO();
                upkeepInfoListVO.setFlowStatusList(statusList);
                Result upkeepBillResult = upKeepBillController.queryPageList(upkeepInfoListVO, 1, 1,req);
                IPage<UpkeepInfoListVO> upkeepBillPageList = (IPage<UpkeepInfoListVO>) upkeepBillResult.getResult();
                return upkeepBillPageList.getTotal();
            case UPKEEP_PLAN:
                TbUpkeepPlan tbUpkeepPlan = new TbUpkeepPlan();
                if(CollectionUtil.isEmpty(statusList)){
                    tbUpkeepPlan.setAuditStatus("-1");
                }else{
                    tbUpkeepPlan.setAuditStatus(statusList.get(0).toString());
                }
                Result upkeepPlanResult = upKeepPlanController.queryPageList(tbUpkeepPlan, 1, 1,req);
                IPage<TbUpkeepPlan> upkeepPlanPageList = (IPage<TbUpkeepPlan>) upkeepPlanResult.getResult();
                return upkeepPlanPageList.getTotal();
            case INSURANCE_LEDGER:
                TbInsuranceRemind tbInsuranceRecord = new TbInsuranceRemind();
                if(CollectionUtil.isEmpty(statusList)){
                    tbInsuranceRecord.setStatus("-1");
                }else{
                    //提醒中
                    tbInsuranceRecord.setStatus("1");
                }
                Result insuranceRemindResult = insuranceRemindController.page(tbInsuranceRecord, 1, 1);
                IPage<TbInsuranceRemind> insuranceRemindPageList = (IPage<TbInsuranceRemind>) insuranceRemindResult.getResult();
                return insuranceRemindPageList.getTotal();
            default:
                return 0;
        }
    }
}