package com.ruoyi.logistics.service.impl;

import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.datascope.aspect.DataScopeAspect;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.logistics.annotation.LargeDataScope;
import com.ruoyi.logistics.domain.LargeRequest;
import com.ruoyi.logistics.mapper.BizWaybillOrderMapper;
import com.ruoyi.logistics.mapper.LargeScreenReportMapper;
import com.ruoyi.logistics.service.LargeScreenReportService;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class LargeScreenReportServiceImpl  implements LargeScreenReportService {

    @Autowired
    private LargeScreenReportMapper largeScreenReportMapper;


    @Override
    @LargeDataScope
    public List<Map> queryOrderTypeReport(LargeRequest largeRequest) {
        return largeScreenReportMapper.queryOrderTypeReport(largeRequest);
    }

    @Override
    @LargeDataScope
    public Map queryDayOrdersReport(LargeRequest largeRequest) {
        Map<String,Object> result=new HashMap<>();
        List<String> month= new ArrayList<>();
        List<String> orderNum= new ArrayList<>();  //订单
        List<String> deliveryNum= new ArrayList<>();  //配送中
        List<String> properNum= new ArrayList<>();  //妥投

        //年月日拿到最近三十天起始日期
        largeRequest.setStartTime(get30DaysAgo());
        largeRequest.setEndTime( LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        List<Map<String,Object>> list= largeScreenReportMapper.queryDayOrdersReport(largeRequest);
        for(int i=0;i<list.size();i++){
            month.add(list.get(i).get("time").toString()) ;
            orderNum.add(list.get(i).get("order_num").toString()) ;
            deliveryNum.add(list.get(i).get("delivery_num").toString()) ;
            properNum.add(list.get(i).get("proper_num").toString()) ;
        }
        result.put("month",month);
        result.put("orderNum",orderNum);
        result.put("deliveryNum",deliveryNum);
        result.put("properNum",properNum);

        return result;

    }

    @Override
    @LargeDataScope
    public Map queryProvinceOrdersReport(LargeRequest largeRequest) {
        Map<String,Object> result=new HashMap<>();
        List<String> allProvince= new ArrayList<>();
        List<String> allMergerProvince= new ArrayList<>();
        List<Integer> outflowNum= new ArrayList<>();
        List<Integer> inflowNum= new ArrayList<>();
        List<BigDecimal> outflowAmounts = new ArrayList<>();
        List<BigDecimal> inflowAmounts = new ArrayList<>();
        
        // 一次查询获取订单数量和金额数据
        List<Map<String,Object>> list= largeScreenReportMapper.queryProvinceOrdersReport(largeRequest);
        for(int i=0;i<list.size();i++){
            allProvince.add(list.get(i).get("province_name").toString()) ;
            outflowNum.add(Integer.parseInt(list.get(i).get("outflowNum").toString())) ;
            inflowNum.add(Integer.parseInt(list.get(i).get("inflowNum").toString())) ;
            allMergerProvince.add(list.get(i).get("merger_name").toString());
            outflowAmounts.add(new BigDecimal(list.get(i).get("outflowAmount").toString()));
            inflowAmounts.add(new BigDecimal(list.get(i).get("inflowAmount").toString()));
        }
        result.put("allProvince",allProvince);
        result.put("allMergerProvince",allMergerProvince);
        result.put("outflowNum",outflowNum);
        result.put("inflowNum",inflowNum);
        result.put("outflowAmounts", outflowAmounts);
        result.put("inflowAmounts", inflowAmounts);

        return result;

    }

    @Override
    @LargeDataScope
    public List<Map> queryFreeOrdersReport(LargeRequest largeRequest) {
        return largeScreenReportMapper.queryFreeOrdersReport(largeRequest);

    }

    @Override
    @LargeDataScope
    public List<Map> queryOrdersReportByType(LargeRequest largeRequest) {
        if("1".equals(largeRequest.getRankType())){
            return largeScreenReportMapper.queryOrdersReportByFree(largeRequest);
        }
        if("2".equals(largeRequest.getRankType())){
            return largeScreenReportMapper.queryOrdersReportByNum(largeRequest);
        }
       return null ;

    }

    @LargeDataScope
    @Override
    public Map queryDeptMonthlyGrowthRate(LargeRequest largeRequest) {

        Map<String,Object> result=new HashMap<>();
        List<String> month= new ArrayList<>();
        List<BigDecimal> rateAmount= new ArrayList<>();
        List<String> growthRate= new ArrayList<>();
        List<Map<String,Object>> list= largeScreenReportMapper.queryDeptMonthlyGrowthRate(largeRequest);
        for(int i=0;i<list.size();i++){
            month.add(list.get(i).get("month").toString()) ;
            rateAmount.add(new BigDecimal(list.get(i).get("rate_amount").toString()));
            growthRate.add(list.get(i).get("growth_rate").toString());
        }
        result.put("month",month);
        result.put("rateAmount",rateAmount);
        result.put("growthRate",growthRate);
        return result;




    }

    @Override
    @LargeDataScope
    public List<Map> queryTransportTypeReport(LargeRequest largeRequest) {
        return largeScreenReportMapper.queryTransportTypeReport(largeRequest);
    }

    @Override
    @LargeDataScope
    public List<Map> queryDeptList(LargeRequest largeRequest) {
     /*   largeRequest.getParams().put("dataScope", "");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getSysUser();

        if (!user.isAdmin()) {
            StringBuilder sql = new StringBuilder();

            // 只拼接【部门权限】，彻底忽略【本人权限】
            for (SysRole role : user.getRoles()) {
                String ds = role.getDataScope();

                if (DataScopeAspect.DATA_SCOPE_CUSTOM.equals(ds)) {
                    // 自定义部门权限
                    sql.append(" OR d.dept_id IN (SELECT dept_id FROM sys_role_dept WHERE role_id = ").append(role.getRoleId()).append(")");
                } else if (DataScopeAspect.DATA_SCOPE_DEPT.equals(ds)) {
                    // 本部门
                    sql.append(" OR d.dept_id = ").append(user.getDeptId());
                } else if (DataScopeAspect.DATA_SCOPE_DEPT_AND_CHILD.equals(ds)) {
                    // 本部门及子级
                    sql.append(" OR d.dept_id IN (SELECT dept_id FROM sys_dept WHERE dept_id = ").append(user.getDeptId()).append(" OR find_in_set(").append(user.getDeptId()).append(", ancestors))");
                }


                // 关键：这里 不处理 仅本人权限！
            }

            if (sql.length() > 0) {
                largeRequest.getParams().put("dataScope", " AND (" + sql.substring(4) + ")");
            }
        }*/



        return largeScreenReportMapper.queryDeptList(largeRequest);
    }

    @Override
    @LargeDataScope
    public List<Map> queryProvinceList(LargeRequest largeRequest) {
        return largeScreenReportMapper.queryProvinceList(largeRequest);

    }

    @Override
    @LargeDataScope
    public Map queryLogisticsTrajectory(LargeRequest largeRequest) {
        //根据传入的 时间  物流公司 供应商 省份 进行查询 流入和流出省份轨迹
        Map<String,Object> result=new HashMap<>();
        List<Map<String,Object>> OutflowProvince= new ArrayList<>();
        List<Map<String,Object>> InflowProvince= new ArrayList<>();
        Map location=new HashMap<>();
        //先把查询的省份经纬度存一下
        List<Double> searchProvinceLocation = new ArrayList<>();
        searchProvinceLocation.add(largeRequest.getLongitude());
        searchProvinceLocation.add(largeRequest.getLatitude());
        location.put(largeRequest.getSearchProvince(),searchProvinceLocation);
        //流出
        List<Map<String,Object>> Outflow= largeScreenReportMapper.queryLogisticsTrajectoryOutflow(largeRequest);
        for(int i=0;i<Outflow.size();i++){
            //定义流出省份
            Map<String,Object> outflowProvince=new HashMap<>();
            outflowProvince.put("form",largeRequest.getSearchProvince());
            outflowProvince.put("to",Outflow.get(i).get("provinceName"));
            outflowProvince.put("value",Outflow.get(i).get("num"));
            outflowProvince.put("amt",Outflow.get(i).get("amt"));
            OutflowProvince.add(outflowProvince);
            //给经纬度也加上
            List<Double> locationOn = new ArrayList<>();
            locationOn.add(Double.parseDouble( Outflow.get(i).get("lng").toString()));
            locationOn.add(Double.parseDouble(Outflow.get(i).get("lat").toString()));
            location.put(Outflow.get(i).get("provinceName"),locationOn);
        }
        //流入
        List<Map<String,Object>> inflow= largeScreenReportMapper.queryLogisticsTrajectoryinflow(largeRequest);
        for(int i=0;i<inflow.size();i++){
            //定义流入省份
            Map<String,Object> inflowProvince=new HashMap<>();
            inflowProvince.put("form",inflow.get(i).get("provinceName"));
            inflowProvince.put("to",largeRequest.getSearchProvince());
            inflowProvince.put("value",inflow.get(i).get("num"));
            inflowProvince.put("amt",inflow.get(i).get("amt"));
            InflowProvince.add(inflowProvince);
            //给经纬度也加上
            List<Double> locationOn = new ArrayList<>();
            locationOn.add(Double.parseDouble( inflow.get(i).get("lng").toString()));
            locationOn.add(Double.parseDouble( inflow.get(i).get("lat").toString()));
            location.put(inflow.get(i).get("provinceName"),locationOn);
        }

        result.put("outflow",OutflowProvince);
        result.put("inflow",InflowProvince);
        result.put("loaction",location);
        return  result;
    }


    public static String get30DaysAgo() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate now = LocalDate.now();
        LocalDate before30Days = now.minusDays(15);
        return before30Days.format(formatter);
    }
}
