package com.cpxt.web.task;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cpxt.biz.domain.*;
import com.cpxt.biz.mapper.*;
import com.cpxt.common.utils.DateUtils;
import com.cpxt.common.utils.Helper;
import com.e6yun.project.sdk.api.E6SdkApi;
import com.e6yun.project.sdk.api.exception.ApiException;
import com.e6yun.project.sdk.api.pojo.basevo.basic.VehicleInfoResp;
import com.e6yun.project.sdk.api.pojo.business.GetVehicleInfoVO;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("statTask")
public class StatTask {

    // 域名
    private static final String ADDRESS = "http://api.e6yun.com/";
    // 公钥
    private static final String APP_KEY = "FEB9F91D-BCD7-4DC2-97D1-CB599EEAF9D5";
    // 密钥
    private static final String SECRET_KEY = "A8211E8F-9E95-4C80-9414-CD5E1F675FEF";

    /*添加代码 begin*/
    private static StatTask statTask;

    @Autowired
    private BizCarStateMapper stateMapper;
    @Autowired
    private BizCarMapper carMapper;
    @Autowired
    private BizDriverMapper driverMapper;
    @Autowired
    private TrackTempMapper trackMapper;
    @Autowired
    private StatCarMapper statCarMapper;
    @Autowired
    private StatDriverMapper statDriverMapper;
    @Autowired
    private BizOrderMapper orderMapper;
    @Autowired
    private BizCustomerMapper customerMapper;
    @Autowired
    private BizCustomerRouteMapper routeMapper;
    @Autowired
    private BizCustomerShopMapper shopMapper;
    @Autowired
    private BizCustomerStateMapper customerStateMapper;
    @Autowired
    private BizCustomerRouteStateMapper routeStateMapper;
    @Autowired
    private BizCustomerShopStateMapper shopStateMapper;


    @PostConstruct
    public void init(){
        statTask = this;
//        statTask.commonService = this.commonService;
        statTask.carMapper = this.carMapper;
        statTask.statCarMapper = this.statCarMapper;
        statTask.driverMapper = this.driverMapper;
        statTask.stateMapper = this.stateMapper;
        statTask.trackMapper = this.trackMapper;
        statTask.orderMapper = this.orderMapper;
        statTask.customerMapper = this.customerMapper;
        statTask.routeMapper = this.routeMapper;
        statTask.shopMapper = this.shopMapper;
        statTask.customerStateMapper = this.customerStateMapper;
        statTask.routeStateMapper = this.routeStateMapper;
        statTask.shopStateMapper = this.shopStateMapper;
    }

    public void statCustomerData(){
        Date now = new Date();

        // 统计各路线平均配送时间
        List<Map> route_avgtime_list = statTask.routeStateMapper.selectAvgTimes();
        for (Map item : route_avgtime_list) {
            int routeId = Helper.FInt(item.get("route_id"));
            int avgtimes = Helper.FInt(item.get("avgtimes"));
            if (routeId>0) {
                BizCustomerRouteState routeState = statTask.routeStateMapper.selectOneByRouteId(routeId);
                if (routeState==null || routeState.getId()==0)
                    routeState = new BizCustomerRouteState();

                routeState.setRouteId(routeId);
                routeState.setAvgTimes(avgtimes);

                if (Helper.FInt(routeState.getId())>0)
                    statTask.routeStateMapper.updateById(routeState);
                else
                    statTask.routeStateMapper.insert(routeState);
            }
        }

        // 统计各路线今日订单数据
        List<Map> route_order_count_list = statTask.routeStateMapper.selectOrderCount();
        for (Map item : route_order_count_list) {
            int routeId = Helper.FInt(item.get("route_id"));
            int order_count = Helper.FInt(item.get("order_count"));
            int finish_count = Helper.FInt(item.get("finish_count"));

            if (routeId>0) {
                BizCustomerRouteState routeState = statTask.routeStateMapper.selectOneByRouteId(routeId);
                if (routeState==null || routeState.getId()==0)
                    routeState = new BizCustomerRouteState();

                routeState.setRouteId(routeId);
                routeState.setTodayOrders(order_count);
                routeState.setFinishOrders(finish_count);

                if (Helper.FInt(routeState.getId())>0)
                    statTask.routeStateMapper.updateById(routeState);
                else
                    statTask.routeStateMapper.insert(routeState);
            }
        }

        // 统计各路线当前订单数据
        List<Map> route_order_list = statTask.routeStateMapper.selectCurrentOrder();
        for (Map item : route_order_list) {
            int routeId = Helper.FInt(item.get("route_id"));
            String orderSn = Helper.NStr(item.get("order_sn"));
            int carId = Helper.FInt(item.get("car_id"));
            int driverId = Helper.FInt(item.get("driver_id"));
            int copilotId = Helper.FInt(item.get("copilot_id"));

            if (routeId>0) {
                BizCustomerRouteState routeState = statTask.routeStateMapper.selectOneByRouteId(routeId);
                if (routeState==null || routeState.getId()==0)
                    routeState = new BizCustomerRouteState();

                routeState.setRouteId(routeId);
                routeState.setCurrentOrder(orderSn);
                routeState.setCurrentCarId(carId);
                routeState.setCurrentDriverId(driverId);
                routeState.setCurrentCopilotId(copilotId);

                if (Helper.FInt(routeState.getId())>0)
                    statTask.routeStateMapper.updateById(routeState);
                else
                    statTask.routeStateMapper.insert(routeState);
            }
        }

        // 统计各门店平均配送时间
        List<Map> shop_avgtime_list = statTask.shopStateMapper.selectAvgTimes();
        for (Map item : shop_avgtime_list) {
            int shopId = Helper.FInt(item.get("shop_id"));
            int avgtimes = Helper.FInt(item.get("avgtimes"));
            if (shopId>0) {
                BizCustomerShopState state = statTask.shopStateMapper.selectOneByShopId(shopId);
                if (state==null || state.getId()==0)
                    state = new BizCustomerShopState();

                state.setShopId(shopId);
                state.setAvgTimes(avgtimes);

                if (Helper.FInt(state.getId())>0)
                    statTask.shopStateMapper.updateById(state);
                else
                    statTask.shopStateMapper.insert(state);
            }
        }

        // 统计各门店平均配送时间
        List<Map> shop_order_list = statTask.shopStateMapper.selectCurrentOrder();
        for (Map item : shop_order_list) {
            int shopId = Helper.FInt(item.get("shop_id"));
            int avgtimes = Helper.FInt(item.get("avgtimes"));
            if (shopId>0) {
                BizCustomerShopState state = statTask.shopStateMapper.selectOneByShopId(shopId);
                if (state==null || state.getId()==0)
                    state = new BizCustomerShopState();

                state.setShopId(shopId);
                state.setIsFinish(Helper.FInt(item.get("order_status"))==3?1:0);
                state.setCurrentOrder(Helper.NStr(item.get("order_sn")));
                state.setCurrentCarId(Helper.FInt(item.get("car_id")));
                state.setCurrentDriverId(Helper.FInt(item.get("driver_id")));
                state.setCurrentCopilotId(Helper.FInt(item.get("copilot_id")));

                if (Helper.FInt(state.getId())>0)
                    statTask.shopStateMapper.updateById(state);
                else
                    statTask.shopStateMapper.insert(state);
            }
        }

    }

    // 定时统计车辆使用情况
    public void statWorkData(){
        Date now = new Date();

        LambdaQueryWrapper<BizCar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizCar::getStatus,1);

        List<BizCar> carList = statTask.carMapper.selectList(queryWrapper);

        String today = DateUtils.getDate();
        LambdaQueryWrapper<StatCar> statCarQueryWrapper = new LambdaQueryWrapper<>();
        statCarQueryWrapper.eq(StatCar::getStatDate, today);
        List<StatCar> statCarList = statTask.statCarMapper.selectList(statCarQueryWrapper);

        // 当天没有统计数据，初始化所有车辆统计数
        if (statCarList==null || statCarList.size()<=0){
            statTask.statCarMapper.initStatCar(today);
        }

        for (BizCar car : carList) {
            StatCar todayStat = statTask.statCarMapper.selectTodayByCarId(car.getId());
            Map map = statTask.statCarMapper.getTodayOdometer(car.getId().toString());
            BigDecimal odometer = new BigDecimal(0);
            if (map!=null && Helper.FInt(map.get("minOdometer"))>0) {
                BigDecimal min = new BigDecimal(Helper.FDouble(map.get("minOdometer")));
                BigDecimal max = new BigDecimal(Helper.FDouble(map.get("maxOdometer")));

                odometer = max.subtract(min);
            }
            todayStat.setOdometer(odometer);

            // 获取车辆今日订单数
            Map jrdd = statTask.statCarMapper.getTodayOrderCount(car.getId());
            if (jrdd!=null)
                todayStat.setOrderCount(Helper.FInt(jrdd.get("orderCount")));

            Map jrsj = statTask.statCarMapper.selectDriverByCarId(car.getId());
            int usetime = 0;
            if (jrsj!=null){
                Long driverId = Helper.FLong(jrsj.get("driver_id"));
                List<BizDriverClock> clocks = statTask.statDriverMapper.selectDriverClockList(driverId);

                for (BizDriverClock clock : clocks) {
                    Date ontime = clock.getOnTime();
                    Date offtime = clock.getOffTime();

                    if (offtime==null)
                        offtime  = now;

                    if (ontime.getDay()!=now.getDay())
                        ontime = DateUtils.dateTime(DateUtils.YYYY_MM_DD, DateUtils.getDate());

                    int diffsecond = Helper.FInt( (offtime.getTime() - ontime.getTime()) / 1000);
                    usetime += diffsecond;
                }
            }
            todayStat.setUseTime(usetime);

            statTask.statCarMapper.updateById(todayStat);
        }

        LambdaQueryWrapper<BizDriver> bizDriverQueryWrapper = new LambdaQueryWrapper<>();
        bizDriverQueryWrapper.eq(BizDriver::getStatus,1);

        List<BizDriver> driverList = statTask.driverMapper.selectList(bizDriverQueryWrapper);

        LambdaQueryWrapper<StatDriver> statDriverQueryWrapper = new LambdaQueryWrapper<>();
        statDriverQueryWrapper.eq(StatDriver::getStatDate, today);
        List<StatDriver> statDriverList = statTask.statDriverMapper.selectList(statDriverQueryWrapper);

        // 当天没有统计数据，初始化所有车辆统计数
        if (statDriverList==null || statDriverList.size()<=0){
            statTask.statDriverMapper.initStatDriver(today);
        }

        for (BizDriver driver : driverList) {
            StatDriver todayStat = statTask.statDriverMapper.selectTodayByDriverId(driver.getId());

            List<BizDriverClock> clocks = statTask.statDriverMapper.selectDriverClockList(driver.getId());

            int usetime = 0;
            BigDecimal odometer = new BigDecimal(0);

            for (BizDriverClock clock : clocks) {
                Date ontime = clock.getOnTime();
                Date offtime = clock.getOffTime();

                if (offtime==null)
                    offtime  = now;

                if (ontime.getDay()!=now.getDay())
                    ontime = DateUtils.dateTime(DateUtils.YYYY_MM_DD, DateUtils.getDate());

                int diffsecond = Helper.FInt( (offtime.getTime() - ontime.getTime()) / 1000);
                usetime += diffsecond;

                if (Helper.FInt(driver.getCurrentCarId())>0) {
                    Map map = statTask.statDriverMapper.getTodayOdometer(
                            driver.getCurrentCarId().toString(),
                            DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, ontime),
                            DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, offtime));
                    if (map != null && Helper.FInt(map.get("minOdometer")) > 0) {
                        BigDecimal min = new BigDecimal(Helper.FDouble(map.get("minOdometer")));
                        BigDecimal max = new BigDecimal(Helper.FDouble(map.get("maxOdometer")));

                        odometer = odometer.add(max.subtract(min));
                    }
                }
            }

            todayStat.setOnlineTime(usetime);
            todayStat.setOdometer(odometer);

            Map jrdd = statTask.statDriverMapper.getTodayOrderCount(driver.getId());
            if (jrdd!=null)
                todayStat.setOrderCount(Helper.FInt(jrdd.get("orderCount")));

            statTask.statDriverMapper.updateById(todayStat);
        }
    }


}
