package com.ruoyi.ems.controller;

import com.alibaba.fastjson2.JSONObject;
import com.huashe.common.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.ems.domain.EnergyMeter;
import com.ruoyi.ems.domain.ElecMeterH;
import com.ruoyi.ems.model.QueryMeter;
import com.ruoyi.ems.service.IBoundaryObjService;
import com.ruoyi.ems.service.IElecMeterHService;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用电计量-小时Controller
 *
 * @author ruoyi
 * @date 2024-12-03
 */
@RestController
@RequestMapping("/elecMeterH")
@Api(value = "ElecMeterHController", description = "用电计量-小时")
public class ElecMeterHController extends BaseController {
    @Autowired
    private IElecMeterHService elecMeterHService;

    @Autowired
    private IBoundaryObjService boundaryObjService;

    /**
     * 查询用电计量-小时列表
     */
    @RequiresPermissions("ems:elecMeterH:list")
    @GetMapping("/list")
    public TableDataInfo list(QueryMeter queryMeter) {
        startPage();
        List<ElecMeterH> list = elecMeterHService.selectByMeterDev(queryMeter);
        return getDataTable(list);
    }

    /**
     * 查询设施用能统计数据
     *
     * @param queryMeter 查询条件
     * @return
     */
    @GetMapping("/staByTime")
    public AjaxResult staByTime(QueryMeter queryMeter) {
        List<EnergyMeter> list = elecMeterHService.staByTime(queryMeter);
        JSONObject jsonObject = new JSONObject();

        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, EnergyMeter> map = list.stream()
                .collect(Collectors.toMap(EnergyMeter::getObjName, Function.identity()));
            BigDecimal quantity = BigDecimal.ZERO;
            BigDecimal useCost = BigDecimal.ZERO;

            EnergyMeter lowElec = map.computeIfAbsent("lowElec", k -> new EnergyMeter("-1", "lowElec", 0.0, 0.0));
            EnergyMeter normalElec = map.computeIfAbsent("normalElec", k -> new EnergyMeter("0", "normalElec", 0.0, 0.0));
            EnergyMeter highElec = map.computeIfAbsent("highElec", k -> new EnergyMeter("1", "highElec", 0.0, 0.0));
            EnergyMeter peakElec = map.computeIfAbsent("peakElec", k -> new EnergyMeter("-1", "peakElec", 0.0, 0.0));

            quantity = quantity.add(new BigDecimal(String.valueOf(lowElec.getQuantity())));
            useCost = useCost.add(new BigDecimal(String.valueOf(lowElec.getUseCost())));
            quantity = quantity.add(new BigDecimal(String.valueOf(normalElec.getQuantity())));
            useCost = useCost.add(new BigDecimal(String.valueOf(normalElec.getUseCost())));
            quantity = quantity.add(new BigDecimal(String.valueOf(highElec.getQuantity())));
            useCost = useCost.add(new BigDecimal(String.valueOf(highElec.getUseCost())));
            quantity = quantity.add(new BigDecimal(String.valueOf(peakElec.getQuantity())));
            useCost = useCost.add(new BigDecimal(String.valueOf(peakElec.getUseCost())));

            jsonObject.put("total", new EnergyMeter("total", "total", quantity.doubleValue(), useCost.doubleValue()));
            jsonObject.put("lowElec", lowElec);
            jsonObject.put("normalElec", normalElec);
            jsonObject.put("highElec", highElec);
            jsonObject.put("peakElec", peakElec);
        }
        else {
            jsonObject.put("total", new EnergyMeter("total", "total", 0.0, 0.0));
            jsonObject.put("lowElec", new EnergyMeter("-1", "lowElec", 0.0, 0.0));
            jsonObject.put("normalElec", new EnergyMeter("0", "normalElec", 0.0, 0.0));
            jsonObject.put("highElec", new EnergyMeter("1", "highElec", 0.0, 0.0));
            jsonObject.put("peakElec", new EnergyMeter("2", "peakElec", 0.0, 0.0));
        }

        return success(jsonObject);
    }

    /**
     * 查询设施用能统计数据
     *
     * @param queryMeter 查询条件
     * @return
     */
    @GetMapping("/hour/listFacsMeterTotal")
    public AjaxResult listFacsMeterTotal(QueryMeter queryMeter) {
        List<EnergyMeter> list = boundaryObjService.getMeterStaByFacsCategory(queryMeter);
        return success(list);
    }

    /**
     * 查询设施用能统计数据
     *
     * @param queryMeter 查询条件
     * @return
     */
    @GetMapping("/hour/listFacsMeter")
    public TableDataInfo listFacsMeter(QueryMeter queryMeter) {
        startPage();
        List<ElecMeterH> list = boundaryObjService.getMeterByFacsCategory(queryMeter);
        return getDataTable(list);
    }

    /**
     * 计算时间范围内日平均
     *
     * @param queryMeter 支持areaCode、deviceCode、date范围筛选
     * @return ElecMeter
     */
    @GetMapping("/day/avg")
    public AjaxResult selectElecDayAvg(QueryMeter queryMeter) {
        EnergyMeter ElecMeter = elecMeterHService.selectElecDayAvg(queryMeter);
        return success(ElecMeter);
    }

    /**
     * 导出用电计量-小时列表
     */
    @RequiresPermissions("ems:elecMeterH:export")
    @Log(title = "用电计量-小时", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QueryMeter queryMeter) {
        List<ElecMeterH> list = elecMeterHService.selectByMeterDev(queryMeter);
        ExcelUtil<ElecMeterH> util = new ExcelUtil<ElecMeterH>(ElecMeterH.class);
        util.exportExcel(response, list, "用电计量-小时数据");
    }

    /**
     * 新增用电计量-小时
     */
    @RequiresPermissions("ems:elecMeterH:add")
    @Log(title = "用电计量-小时", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElecMeterH elecMeterH) {
        return toAjax(elecMeterHService.insertElecMeterH(elecMeterH));
    }

    /**
     * 修改用电计量-小时
     */
    @RequiresPermissions("ems:elecMeterH:edit")
    @Log(title = "用电计量-小时", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElecMeterH elecMeterH) {
        return toAjax(elecMeterHService.updateElecMeterH(elecMeterH));
    }

    /**
     * 删除用电计量-小时
     */
    @RequiresPermissions("ems:elecMeterH:remove")
    @Log(title = "用电计量-小时", businessType = BusinessType.DELETE)
    @DeleteMapping("/delByDate")
    public AjaxResult removeByDate(@RequestParam(name = "date") String date) {
        return toAjax(elecMeterHService.deleteElecMeterHByDate(date));
    }

    @GetMapping("/sum/byDate/{date}")
    public AjaxResult qryElecMeterByDate(@PathVariable("date") String date,
        @RequestParam(name = "areaCode", required = false) String areaCode) {
        return success(elecMeterHService.qryElecMeterByDate(date, areaCode));
    }

    @GetMapping("/sum/timeIndex/byDate/{date}/{timeIndex}")
    public AjaxResult qryTimeIndexElecMeterByDay(@PathVariable("date") String date,
        @PathVariable("timeIndex") Integer timeIndex) {
        return success(elecMeterHService.qryTimeIndexElecMeterByDay(date, timeIndex));
    }

    @GetMapping("/sum/date/byDate/{date}")
    public AjaxResult qryDateElecMeterByDate(@PathVariable("date") String date) {
        return success(elecMeterHService.qryDateElecMeterByDate(date));
    }

    @GetMapping("/sum/date/byYear/{date}")
    public AjaxResult qryDateElecMeterByYear(@PathVariable("date") String date) {
        return success(elecMeterHService.qryDateElecMeterByYear(date));
    }

    @GetMapping("/sum/device/day")
    public AjaxResult qryDeviceDay(ElecMeterH elecMeterH) {
        return success(elecMeterHService.qryDeviceTypeElecMeterByDay(elecMeterH));
    }

}
