package com.yuchen.saas.park.service.controller.energy;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yuchen.saas.park.api.dto.energy.PowerAddDTO;
import com.yuchen.saas.park.api.entity.park.PmgBatPowerData;
import com.yuchen.saas.park.api.vo.park.energy.EnergyStatisticVO;
import com.yuchen.saas.park.api.vo.park.energy.SevenTrendVO;
import com.yuchen.saas.park.api.vo.park.energy.TotalRankingVO;
import com.yuchen.saas.park.service.service.PmgBatPowerDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.nest.springwrap.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author 颜艺波
 * @date 2022/6/28 18:12
 * @Description
 */
@RestController
@AllArgsConstructor
@RequestMapping("/energy/power")
@Api(value = "电表", tags = "电表")
public class EnergyPowerController {

    @Autowired
    PmgBatPowerDataService powerDataService;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "耗电量统计", notes = "耗电量统计")
    @GetMapping("/energyStatistic/{parkId}")
    public R<EnergyStatisticVO> energyStatistic(@PathVariable("parkId") Long parkId) {
        return R.data(powerDataService.energyStatistic(parkId));
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "七日用量趋势", notes = "七日用量趋势")
    @GetMapping("/sevenTrend/{parkId}")
    public R<List<SevenTrendVO>> sevenTrend(@PathVariable("parkId") Long parkId) {
        return R.data(powerDataService.sevenTrend(parkId));
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "累积耗电量排名", notes = "累积耗电量排名")
    @GetMapping("/totalRanking/{parkId}")
    public R<List<TotalRankingVO>> totalRanking(@PathVariable("parkId") Long parkId) {
        return R.data(powerDataService.totalRanking(parkId));
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增电表数据", notes = "新增电表数据")
    @PostMapping("/add")
    public R<Boolean> add(@RequestBody PowerAddDTO powerAddDTO) {
        powerAddDTO.setReportTime(System.currentTimeMillis());
        PmgBatPowerData data = powerDataService.getOne(Wrappers.<PmgBatPowerData>lambdaQuery()
                .eq(PmgBatPowerData::getProductKey, powerAddDTO.getProductKey())
                .eq(PmgBatPowerData::getDeviceName, powerAddDTO.getDeviceName())
                .orderByDesc(PmgBatPowerData::getReportTime)
                .last("limit 1"));
        // 上报数值在原来基础上增加1.5
        BigDecimal b = data.getValue() != null ? new BigDecimal(data.getValue()) : BigDecimal.ZERO;
        b = b.add(new BigDecimal("1.5"));
        powerAddDTO.setValue(b.toString());
        return R.data(powerDataService.add(powerAddDTO));
    }
}
