package com.ho.business.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ho.business.entity.ElecPrice;
import com.ho.business.mapper.ElecPriceMapper;
import com.ho.business.service.ElecPriceService;
import com.ho.common.tools.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yule
 * @description 针对表【elec_price】的数据库操作Service实现
 * @createDate 2022-08-25 16:07:53
 */
@Service
@Slf4j
public class ElecPriceServiceImpl implements ElecPriceService {

    @Autowired
    ElecPriceMapper elecPriceMapper;

    //插入
    @Override
    public int insertSelective(ElecPrice record) {
        int i = elecPriceMapper.insertSelective(record);
        return i;
    }

    //查询所有
    @Override
    public List<ElecPrice> selectAll() {
        List<ElecPrice> elecPrices = elecPriceMapper.selectAll();
        return elecPrices;
    }

    //根据id查询 这个id是原来的stationId
    @Override
    public List<ElecPrice> selectByStationIdAndTime(Integer stationId, String startTime) {
        List<ElecPrice> elecPrices = elecPriceMapper.selectByStationIdAndTime(null, stationId, startTime, null);
        return elecPrices;
    }

    @Override
    public List<ElecPrice> selectLatestPrices(Integer groupId, Integer stationId, String startTime, String endTime) {
        List<ElecPrice> elecPrices = new ArrayList<>();
        String newTime = selectStartTime(groupId);
        if (newTime == null) {
            return elecPrices;
        }
        //取这个最新日期的开始时间
        Date day = null;
        SimpleDateFormat sd = new SimpleDateFormat(CommonConstant.DATE);
        try {
            day = sd.parse(newTime);
        } catch (ParseException e) {
        }
        if (day == null) {
            return elecPrices;
        }
        //如果传入的时间为空,从电价表查最新的那个时间日期
        if (StringUtils.isEmpty(startTime)) {
            DateTime dateTime = DateUtil.beginOfDay(day);
            startTime = DateUtil.format(DateUtil.beginOfDay(dateTime), CommonConstant.DATE);
            endTime = DateUtil.format(DateUtil.endOfDay(dateTime), CommonConstant.DATE);
        }
        //根据时间戳查询当天电价
        log.info("startTime:" + startTime);
        elecPrices = elecPriceMapper.selectByStationIdAndTime(groupId, stationId, startTime, endTime);
        return elecPrices;
    }

    //查询最新时间
    @Override
    public String selectStartTime(Integer id) {
        String startTime = elecPriceMapper.selectStartTime(id);
        return startTime;
    }


}
