package com.bonus.material.largeScreen.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.bonus.common.biz.domain.SysDept;
import com.bonus.common.biz.utils.MathUtil;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.device.domain.DevInfo;
import com.bonus.material.device.domain.DevInfoDt;
import com.bonus.material.device.domain.vo.DevInfoVo;
import com.bonus.material.device.mapper.DevInfoMapper;
import com.bonus.material.device.service.DevInfoService;
import com.bonus.material.largeScreen.entity.*;
import com.bonus.material.largeScreen.service.LargeScreenService;
import com.bonus.material.lease.domain.MaLeaseInfo;
import com.bonus.material.lease.mapper.MaLeaseInfoMapper;
import com.bonus.material.lease.service.MaLeaseInfoService;
import com.bonus.material.order.domain.OrderDetailDto;
import com.bonus.material.order.domain.OrderInfoDto;
import com.bonus.material.order.mapper.OrderMapper;
import com.bonus.material.order.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import static com.bonus.common.biz.constant.MaterialConstants.ADMIN_ID;
import static com.bonus.common.biz.constant.MaterialConstants.PROVINCE_COMPANY_DEPT_ID;
import static com.bonus.common.core.utils.PageUtils.startPage;

/**
 * @Author：liang.chao
 * @Date：2024/12/24 - 15:46
 */

@Api(value = "大屏", tags = {"大屏"})
@RestController
@RequestMapping("/largeScreen")
public class LargeScreenController extends BaseController {
    @Resource
    private OrderService orderService;

    @Resource
    private DevInfoService devInfoService;

    @Resource
    private MaLeaseInfoService maLeaseInfoService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private DevInfoMapper devInfoMapper;

    @Resource
    private MaLeaseInfoMapper leaseInfoMapper;

    @Resource
    private LargeScreenService largeScreenService;

    @ApiOperation("闲置装备分析")
    @GetMapping("/getIdleDevRatio")
    public AjaxResult getIdleDevRatio() {
        try {
            DevInfo list = largeScreenService.getIdleDevRatio();
            return AjaxResult.success(list);
        } catch (Exception e) {
            return AjaxResult.error("闲置装备分析异常");
        }
    }

    @ApiOperation("出租装备分析")
    @GetMapping("/getLeaseCountByTypeName")
    public AjaxResult getLeaseCountByTypeName() {
        List<DevInfo> list = devInfoMapper.getLeaseCountByTypeName();
        Integer total = list.stream().mapToInt(DevInfo::getDeviceCount).sum();
        list.forEach(item -> {
            double ratio = total == 0 ? 0 : (double) item.getDeviceCount() / total;
            double ratioPercent = ratio * 100;

            BigDecimal bd = new BigDecimal(ratioPercent).setScale(2, RoundingMode.HALF_UP);
            item.setRatio(bd);
        });
        return AjaxResult.success(list);
    }

    @ApiOperation("装备租赁互联")
    @GetMapping("/getLeaseCouples")
    public AjaxResult getLeaseCouples() {
        List<OrderData> list = orderMapper.getBuyerAndSellerCouples();
        Map<String, List<OrderData>> groupedBuyerMap = list.stream()
                .collect(Collectors.groupingBy(OrderData::getBuyerCompany));
        List<List<OrderData>> groupedList = new ArrayList<>(groupedBuyerMap.values());
        int randomIndex = (int) (Math.random() * groupedList.size());
        List<OrderData> orderDataList = groupedList.get(randomIndex);
        Map<String, Map<String, Long>> resultMap = new HashMap();
        Map<String, Long> sellerCount = orderDataList.stream()
                .collect(Collectors.groupingBy(OrderData::getSellerCompany, Collectors.counting()));
        resultMap.put(orderDataList.get(0).getBuyerCompany(), sellerCount);
        return AjaxResult.success(resultMap);
    }

    @ApiOperation("装备上架统计")
    @GetMapping("/devCount")
    public AjaxResult devCount() {
        Integer devNum = devInfoMapper.getDevNum();
        Integer devUpNum = devInfoMapper.getDevUpNum();
        List<DevInfo> devInfos = devInfoMapper.getDevUpCountByType();
        Integer devTypeNum = devInfoMapper.getDevTypeNum();
        Integer devQcWarningNum = devInfoMapper.getDevQcWarningNum();
        OrderData orderData = new OrderData();
        orderData.setDevNum(devNum);
        orderData.setDevUpNum(devUpNum);
        orderData.setDevInfos(devInfos);
        orderData.setDevTypeNum(devTypeNum);
        orderData.setDevQcWaningNum(devQcWarningNum);
        return AjaxResult.success(orderData);
    }

    @ApiOperation("装备租赁统计")
    @GetMapping("/devLeaseCount")
    public AjaxResult devRentalCount() {
        OrderData orderData = new OrderData();
        //OrderDto orderDto = orderMapper.getOrderCount();
        //orderData.setOrderNum(orderDto.getOrderNum());
        Integer maTypeLeasingNum = devInfoMapper.getMaTypeLeasingNum();
        orderData.setMaTypeLeasingNum(maTypeLeasingNum);
        Integer devLeasingNum = devInfoMapper.getDevLeasingNum();
        orderData.setDevLeasingNum(devLeasingNum);
        Integer repairingDevNum = devInfoMapper.getRepairingDevNum();
        orderData.setDevRepairingNum(repairingDevNum);
        Integer rentToalNum = devInfoMapper.getRentToalNum();
        orderData.setRentToalNum(rentToalNum);
        DevInfo devInfo = devInfoMapper.getDevUsageRatio();
       /* if (devInfo != null) {
            orderData.setDevUsageRatio(MathUtil.calculatePercentage(devInfo.getTotalLeaseDay(), devInfo.getTotalUpDay() + devInfo.getTotalLeaseDay()));
        }*/
        return AjaxResult.success(orderData);
    }


    @ApiOperation("公司出租/租赁数")
    @GetMapping("/devLeaseAndRentCount")
    public AjaxResult devLeaseAndRentCount() {
        List<LeaseInfo> leaseInfo = devInfoMapper.getDevLeaseCount();
        List<RentInfo> rentInfo = devInfoMapper.getDevRentCount();
        return AjaxResult.success(new LeaseAndRentInfo(leaseInfo, rentInfo));
    }

    @ApiOperation("装备需求统计")
    @GetMapping("/demandCount")
    public AjaxResult demandCount() {
        OrderData orderData = new OrderData();
        Integer leaseNum = leaseInfoMapper.getLeaseCount();
        Integer leaseOrderNum = leaseInfoMapper.getLeaseOrderCount();
        Integer maTypeCountFromLease = leaseInfoMapper.getMaTypeCountFromLease();
        String topPopularTypeName = leaseInfoMapper.getTopPopularTypeName();
        Integer demandUnitNum = leaseInfoMapper.getDemandUnit();
        orderData.setLeaseNum(leaseNum);
        orderData.setMaTypeCountFromLease(maTypeCountFromLease);
        //orderData.setLeaseOrderRatio(MathUtil.calculatePercentage(leaseOrderNum, leaseNum));
        orderData.setTopPopularTypeName(topPopularTypeName);
        orderData.setDemandUnitNum(demandUnitNum);
        return AjaxResult.success(orderData);
    }

    @ApiOperation("装备共享排名")
    @GetMapping("/getDeviceShareRanking")
    public AjaxResult getDeviceShareRanking() {
        List<DevInfo> list = devInfoMapper.getDeviceShareRanking();
        return AjaxResult.success(list);
    }

    @ApiOperation("租赁跟踪")
    @GetMapping("/getOrderTracking")
    public AjaxResult getOrderTracking() {
        List<OrderInfoDto> list = orderMapper.getOrderStatusCount(new OrderDetailDto());
        return AjaxResult.success(list);
    }

    @ApiOperation("租赁需求分析")
    @GetMapping("/getLeaseCountByPublishCompany")
    public AjaxResult getLeaseCountByPublishCompany() {
        List<MaLeaseInfo> list = leaseInfoMapper.getLeaseCountByPublishCompany();
        return AjaxResult.success(list);
    }

    @ApiOperation("租赁装备数及订单数")
    @GetMapping("/getCompanyNum")
    public AjaxResult getCompanyNum(DevInfoVo dto) {
        List<DevInfoVo> infoVos = new ArrayList<>();
        // 查询公司对应订单数
        List<DevInfoVo> list = devInfoMapper.getOrderByCompanyId(dto.getCompanyId());
        Map<String, Integer> orderNumMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (DevInfoVo infoVo : list) {
                // 根据订单id查询所买公司id和名称
                DevInfoVo infoVo1 = devInfoMapper.getBuyCompanyList(infoVo);
                // 如果 Map 中已经存在该公司 ID,则数量增加1
                if (orderNumMap.containsKey(infoVo1.getCompanyId())) {
                    orderNumMap.put(infoVo1.getCompanyId(), orderNumMap.get(infoVo1.getCompanyId()) + 1);
                } else {
                    orderNumMap.put(infoVo1.getCompanyId(), 1);
                }
            }
        }
        // 根据orderNumMap去遍历查询公司名称
        if (CollectionUtil.isNotEmpty(orderNumMap)) {
            for (Map.Entry<String, Integer> entry : orderNumMap.entrySet()) {
                DevInfoVo vo = new DevInfoVo();
                DevInfoVo devInfoVo = devInfoMapper.selectDeptList(entry.getKey());
                if (devInfoVo != null) {
                    vo.setCompanyId(devInfoVo.getCompanyId());
                    vo.setCompanyName(devInfoVo.getCompanyName());
                }
                vo.setOrderNum(entry.getValue());
                infoVos.add(vo);
            }
            if (CollectionUtil.isNotEmpty(list)) {
                DevInfoVo infoVo = list.get(0);
                infoVo.setOrderNum(list.size());
                infoVos.add(0, infoVo);
            }
            // 根据 orderNum 降序排序，并取前 10 个元素
            infoVos = infoVos.stream()
                    .sorted((vo1, vo2) -> Integer.compare(vo2.getOrderNum(), vo1.getOrderNum()))
                    .limit(10)
                    .collect(Collectors.toList());
        }
        return AjaxResult.success(infoVos);
    }

    @ApiOperation("入住装备数二级页面")
    @GetMapping("/getDevNum")
    public AjaxResult getDevNum(DevInfoVo devInfoVo) {
        startPage();
        List<DevInfoVo> list = devInfoMapper.getDevNumList(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("上架装备数二级页面")
    @GetMapping("/getDevUpNum")
    public AjaxResult getDevUpNum(DevInfoVo devInfoVo) {
        startPage();
        List<DevInfoVo> list = devInfoMapper.getDevUpNumList(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("装备总类型数二级页面")
    @GetMapping("/getDevTypeNum")
    public AjaxResult getDevTypeNum(DevInfoVo devInfoVo) {
        startPage();
        List<DevInfoVo> list = devInfoMapper.getDevTypeNumList(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("保养告警二级页面")
    @GetMapping("/getDevQcWarningNum")
    public AjaxResult getDevQcWarningNum(DevInfoVo devInfoVo) {
        startPage();
        List<DevInfoVo> list = devInfoMapper.getDevQcWarningNumList(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("在租赁种类二级页面")
    @GetMapping("/getMaTypeLeasingNum")
    public AjaxResult getMaTypeLeasingNum(DevInfoVo devInfoVo) {
        startPage();
        List<DevInfoVo> list = devInfoMapper.getMaTypeLeasingNumList(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("装备租赁-累计数二级页面")
    @GetMapping("/getMaTypeLeasingDetail")
    public AjaxResult getMaTypeLeasingDetail(DevInfoVo devInfoVo) {
        startPage();
        List<DevInfoVo> list = devInfoMapper.getMaTypeLeasingDetail(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("装备需求-需求单位二级页面")
    @GetMapping("/getDemandUnit")
    public AjaxResult getDemandUnit(DevInfoVo devInfoVo) {
        startPage();
        List<SysDept> list = devInfoMapper.getDemandUnit(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("在租赁装备数二级页面")
    @GetMapping("/getDevLeasingNum")
    public AjaxResult getDevLeasingNum(DevInfoVo devInfoVo) {
        startPage();
        List<DevInfoVo> list = devInfoMapper.getDevLeasingNumList(devInfoVo);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 应答率二级页面
     *
     * @param dto
     * @return
     */
    @ApiOperation("应答率二级页面")
    @GetMapping("/getLeaseAnswerRate")
    public AjaxResult getLeaseAnswerRate(MaLeaseAnswerInfo dto) {
        startPage();
        List<MaLeaseAnswerInfo> list = leaseInfoMapper.getLeaseAnswerRate(dto);
        if (!CollectionUtils.isEmpty(list)) {
            for (MaLeaseAnswerInfo maLeaseAnswerInfo : list) {
                // 根据 typeId 查询设备名称
                if (maLeaseAnswerInfo.getTypeId() != null) {
                    // 获取list集合
                    List<String> typeIds = Arrays.asList(maLeaseAnswerInfo.getTypeId().split(","));
                    // 查询类型名称
                    String typeName = leaseInfoMapper.selectMaTypeList(typeIds);
                    maLeaseAnswerInfo.setTypeName(typeName);
                }
            }
            if (!StringUtils.isBlank(dto.getKeyWord())) {
                list = list.stream()
                        .filter(item -> containsKeyword(item, dto.getKeyWord()))
                        .collect(Collectors.toList());
            }
        }
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 总应答率二级页面
     *
     * @param dto
     * @return
     */
    @ApiOperation("总应答率二级页面")
    @GetMapping("/getTotalLeaseAnswerRate")
    public AjaxResult getTotalLeaseAnswerRate(MaLeaseAnswerInfo dto) {
        List<MaLeaseAnswerInfo> list = leaseInfoMapper.getLeaseAnswerRate(dto);
        if (!CollectionUtils.isEmpty(list)) {
            for (MaLeaseAnswerInfo maLeaseAnswerInfo : list) {
                // 根据 typeId 查询设备名称
                if (maLeaseAnswerInfo.getTypeId() != null) {
                    // 获取list集合
                    List<String> typeIds = Arrays.asList(maLeaseAnswerInfo.getTypeId().split(","));
                    // 查询类型名称
                    String typeName = leaseInfoMapper.selectMaTypeList(typeIds);
                    maLeaseAnswerInfo.setTypeName(typeName);
                }
            }
            if (!StringUtils.isBlank(dto.getKeyWord())) {
                list = list.stream()
                        .filter(item -> containsKeyword(item, dto.getKeyWord()))
                        .collect(Collectors.toList());
            }
        }
        Integer publishCount = 0;
        Integer orderCount = 0;
        MaLeaseAnswerInfo info = new MaLeaseAnswerInfo();
        if (!CollectionUtils.isEmpty(list)) {
            for (MaLeaseAnswerInfo maLeaseAnswerInfo : list) {
                publishCount += maLeaseAnswerInfo.getPublishCount();
                orderCount += maLeaseAnswerInfo.getOrderCount();
            }
            info.setPublishCount(publishCount);
            info.setOrderCount(orderCount);
            // 计算装备利用率，保持2位小数百分比（leaseTotal/leaseTotal + upTotal）
            BigDecimal result = MathUtil.calculatePercentage(orderCount, publishCount);
            info.setAnswerRate(result.setScale(2, RoundingMode.HALF_UP).toString());
        }
        return AjaxResult.success(info);
    }

    /**
     * 判断关键字
     *
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsKeyword(MaLeaseAnswerInfo item, String keyWord) {
        return (item.getDeviceName() != null && item.getDeviceName().contains(keyWord)) ||
                (item.getTypeName() != null && item.getTypeName().contains(keyWord));
    }

    /**
     * 最需装备二级页面
     *
     * @param dto
     * @return
     */
    @ApiOperation("最需装备二级页面")
    @GetMapping("/getLeaseOnlyInfo")
    public AjaxResult getLeaseOnlyInfo(MaLeaseOnlyInfo dto) {
        List<MaLeaseOnlyInfo> list = new ArrayList<>();
        startPage();
        if (dto.getIsHot() != null && dto.getIsHot()) {
            list = maLeaseInfoService.getDetails(dto);
        } else {
            list = leaseInfoMapper.getLeaseOnlyInfo(dto);
        }
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 需求装备种类
     *
     * @param dto
     * @return
     */
    @ApiOperation("需求装备种类")
    @GetMapping("/getLeaseTypeList")
    public AjaxResult getLeaseTypeList(MaLeaseOnlyInfo dto) {
        startPage();
        List<MaLeaseOnlyInfo> list = leaseInfoMapper.getLeaseTypeList(dto);
        if (!CollectionUtils.isEmpty(list)) {
            for (MaLeaseOnlyInfo maLeaseOnlyInfo : list) {
                // 获取list集合
                List<String> typeIds = Arrays.asList(maLeaseOnlyInfo.getTypeId().split(","));
                // 查询类型名称
                String typeName = leaseInfoMapper.selectMaTypeList(typeIds);
                maLeaseOnlyInfo.setTypeName(typeName);
                long daysDifference = calculateDaysDifference(maLeaseOnlyInfo.getStartTime(), maLeaseOnlyInfo.getEndTime());
                maLeaseOnlyInfo.setEstimateDays((int) daysDifference);
            }
            if (!StringUtils.isBlank(dto.getKeyWord())) {
                list = list.stream()
                        .filter(item -> containsTypeKeyword(item, dto.getKeyWord()))
                        .collect(Collectors.toList());
            }
        }
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 判断关键字
     *
     * @param item
     * @param keyWord
     * @return
     */
    private boolean containsTypeKeyword(MaLeaseOnlyInfo item, String keyWord) {
        return (item.getDeviceName() != null && item.getDeviceName().contains(keyWord)) ||
                (item.getTypeName() != null && item.getTypeName().contains(keyWord));
    }

    /**
     * 计算租赁天数差
     *
     * @param startTime
     * @param rentEndTime
     * @return
     */
    private long calculateDaysDifference(Date startTime, Date rentEndTime) {
        // 将 java.util.Date 转换为 java.time.LocalDate
        LocalDate preOutboundLocalDate = convertToLocalDate(startTime);
        LocalDate rentEndLocalDate = convertToLocalDate(rentEndTime);
        // 计算天数差
        long days = ChronoUnit.DAYS.between(preOutboundLocalDate, rentEndLocalDate);
        if (days == 0) {
            days = 1;
        } else {
            days = days + 1;
        }
        return days;
    }

    /**
     * 将 java.util.Date 转换为 java.time.LocalDate
     *
     * @param date
     * @return
     */
    public static LocalDate convertToLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
    }

    /**
     * 装备利用率
     *
     * @param dto
     * @return
     */
    @ApiOperation("装备利用率")
    @GetMapping("/getDevRate")
    public AjaxResult getDevRate(MaDevRateInfo dto) {
        startPage();
        List<MaDevRateInfo> list = leaseInfoMapper.getDevRate(dto);
        return AjaxResult.success(getDataTable(list));
    }

    @ApiOperation("装备总利用率")
    @GetMapping("/getTotalDevRate")
    public AjaxResult getTotalDevRate(MaDevRateInfo dto) {
        List<MaDevRateInfo> list = leaseInfoMapper.getDevRate(dto);
        MaDevRateInfo info = new MaDevRateInfo();
        Integer upTotal = 0;
        Integer leaseTotal = 0;
        if (!CollectionUtils.isEmpty(list)) {
            for (MaDevRateInfo maDevRateInfo : list) {
                upTotal += maDevRateInfo.getUpTotal();
                leaseTotal += maDevRateInfo.getLeaseTotal();
            }
            info.setUpTotal(upTotal);
            info.setLeaseTotal(leaseTotal);
            // 计算装备利用率，保持2位小数百分比（leaseTotal/leaseTotal + upTotal）
            BigDecimal result = MathUtil.calculatePercentage(leaseTotal, leaseTotal + upTotal);
            info.setRate(result.setScale(2, RoundingMode.HALF_UP).toString());
        }
        return AjaxResult.success(info);
    }

    /**
     * 退租装备
     *
     * @param dto
     * @return
     */
    @ApiOperation("退租装备")
    @GetMapping("/getReturnDev")
    public AjaxResult getReturnDev(MaDevRateInfo dto) {
        startPage();
        List<MaDevRateInfo> list = leaseInfoMapper.getReturnDev(dto);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 按公司纬度获取设备入驻数
     *
     * @param dto
     * @return
     */
    @ApiOperation("按公司纬度获取设备入驻数")
    @GetMapping("/getDevNumList")
    public AjaxResult getDevNumList(DevInfo dto) {
        startPage();
        List<DevInfo> list = leaseInfoMapper.getDevNumList(dto);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 入驻设备明细
     *
     * @param dto
     * @return
     */
    @ApiOperation("入驻设备明细")
    @GetMapping("/getDevNumDetailsList")
    public AjaxResult getDevNumDetailsList(DevInfo dto) {
        startPage();
        List<DevInfoDt> list = leaseInfoMapper.getDevNumDetailsList(dto);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 导出入驻设备明细
     *
     * @param dto
     * @return
     */
    @ApiOperation("导出入驻设备明细")
    @PostMapping("/exportDevNumDetailsList")
    public void exportDevNumDetailsList(HttpServletResponse response, @RequestBody DevInfo dto) {
        List<DevInfoDt> list = leaseInfoMapper.getDevNumDetailsList(dto);
        ExcelUtil<DevInfoDt> util = new ExcelUtil<>(DevInfoDt.class);
        util.exportExcel(response, list, "入驻设备明细数据");
    }

    @GetMapping("/getAddress")
    public AjaxResult getAddress() {
        try {
            List<Map<String, Object>> address = leaseInfoMapper.getAddress();
            return !address.isEmpty() ? AjaxResult.success(address) : AjaxResult.error();
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    @GetMapping("/getDept")
    public AjaxResult getDept(String code) {
        try {
            List<Map<String, Object>> dept = leaseInfoMapper.getDept(code);
            return !dept.isEmpty() ? AjaxResult.success(dept) : AjaxResult.error();
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    @GetMapping("/getMaType")
    public AjaxResult getMaType(@RequestParam Long firstLevelId) {
        try {
            List<Map<String, Object>> maType = leaseInfoMapper.getMaType(firstLevelId);
            return !maType.isEmpty() ? AjaxResult.success(maType) : AjaxResult.error();
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    @GetMapping("/statByTypeAndAge")
    public AjaxResult statByTypeAndAge() {
        try {
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            Long userId = SecurityUtils.getLoginUser().getUserid();
            // 管理员和省公司可查看所有数据
            if (userId != null && deptId != null
                    && !userId.equals(ADMIN_ID)
                    && !deptId.equals(PROVINCE_COMPANY_DEPT_ID)) {
                deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            } else {
                deptId = null;
            }
            List<Map<String, Object>> maType = leaseInfoMapper.statByTypeAndAge(deptId);
            return AjaxResult.success(maType);
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }


    @GetMapping("/statByTypeAndAgeDetails")
    public AjaxResult statByTypeAndAgeDetails(@RequestParam String type) {
        try {
            List<Map<String, Object>> maType = leaseInfoMapper.statByTypeAndAgeDetails(type);
            return AjaxResult.success(maType);
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }


    @GetMapping("/statByTypeAndAgeByEquipment")
    public AjaxResult statByTypeAndAgeByEquipment(@RequestParam String type) {
        try {
            List<Map<String, Object>> maType = leaseInfoMapper.statByTypeAndAgeByEquipment(type);
            return AjaxResult.success(maType);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return AjaxResult.error();
        }
    }


    @GetMapping("/statByTypeAndAgeByCity")
    public AjaxResult statByTypeAndAgeByCity(@RequestParam String type) {
        try {
            List<Map<String, Object>> maType = leaseInfoMapper.statByTypeAndAgeByCity(type);
            return AjaxResult.success(maType);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return AjaxResult.error();
        }
    }


    @GetMapping("/statByTypeAndAgeByConfiguration")
    public AjaxResult statByTypeAndAgeByConfiguration() {
        try {
            List<Map<String, Object>> maType = leaseInfoMapper.statByTypeAndAgeByConfiguration();
            return AjaxResult.success(maType);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return AjaxResult.error();
        }
    }


    @GetMapping("/statByTypeAndAgeByTurnoverRate")
    public AjaxResult statByTypeAndAgeByTurnoverRate() {
        try {
            List<Map<String, Object>> maType = leaseInfoMapper.statByTypeAndAgeByTurnoverRate();
            return AjaxResult.success(maType);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return AjaxResult.error();
        }
    }


    @GetMapping("/statByTypeAndAgeByUsageRate")
    public AjaxResult statByTypeAndAgeByUsageRate() {
        try {
            List<Map<String, Object>> maType = leaseInfoMapper.statByTypeAndAgeByUsageRate();
            return AjaxResult.success(maType);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return AjaxResult.error();
        }
    }





}
