package com.ruoyi.web.controller.ems;

import com.huashe.common.domain.AjaxResult;
import com.huashe.common.utils.DateUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.Assert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.ems.domain.MeterDevice;
import com.ruoyi.ems.domain.MeterReading;
import com.ruoyi.ems.model.QueryMeter;
import com.ruoyi.ems.service.IMeterDeviceService;
import com.ruoyi.ems.service.IMeterReadingService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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 java.util.Date;
import java.util.List;

/**
 * 抄记录Controller
 *
 * @author ruoyi
 * @date 2024-08-28
 */
@RestController
@RequestMapping("/ems/meterReading")
@Api(value = "MeterReadingManualController", description = "抄表管理")
public class MeterReadingController extends BaseController {
    @Autowired
    private IMeterReadingService meterReadingService;

    @Autowired
    private IMeterDeviceService meterDeviceService;

    /**
     * 查询抄表记录列表
     */
    @GetMapping("/listByParam")
    public AjaxResult listByParam(QueryMeter queryMeterReading) {
        List<MeterReading> list = meterReadingService.selectList(queryMeterReading);
        return success(list);
    }

    /**
     * 获取设备最后一条抄表记录
     */
    @GetMapping(value = "/getLastRecord")
    public AjaxResult getLastRecord(@RequestParam(name = "areaCode") String areaCode,
        @RequestParam(name = "deviceCode") String deviceCode) {
        return success(meterReadingService.selectLastItem(areaCode, deviceCode));
    }

    /**
     * 新增抄表记录
     */
    @PreAuthorize("@ss.hasPermi('ems:meterReading:add')")
    @Log(title = "抄表记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MeterReading nowItem) {
        try {
            MeterReading lastItem = meterReadingService.selectLastItem(nowItem.getAreaCode(), nowItem.getDeviceCode());
            checkAdd(lastItem, nowItem);
            fillData(lastItem, nowItem);
            int count = meterReadingService.insert(nowItem);
            return toAjax(count);
        }
        catch (BusinessException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改抄表记录
     */
    @PreAuthorize("@ss.hasPermi('ems:meterReading:edit')")
    @Log(title = "抄表记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MeterReading nowItem) {
        try {
            MeterReading lastItem = meterReadingService.selectLastItem(nowItem.getAreaCode(), nowItem.getDeviceCode());
            checkMod(lastItem, nowItem);
            meterReadingService.deleteById(nowItem.getId());
            nowItem.setMeterReading(nowItem.getMeterReading());
            fillData(lastItem, nowItem);
            int count = meterReadingService.insert(nowItem);
            return toAjax(count);
        }
        catch (BusinessException e) {
            return error(e.getMessage());
        }
    }

    /**
     * 删除动力箱柜
     */
    @PreAuthorize("@ss.hasPermi('ems:meterReading:remove')")
    @Log(title = "抄表记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(meterReadingService.deleteById(id));
    }

    private void checkAdd(MeterReading lastItem, MeterReading nowItem) {
        if (null != lastItem) {
            Date date = new Date();
            String nowMonth = DateUtils.dateToString(date, "yyyyMM");
            Assert.isTrue(!StringUtils.equals(nowMonth, lastItem.getMeterMonth()), -1, "本月已存在抄表记录");
            Assert.isTrue(nowItem.getMeterReading() >= lastItem.getMeterReading(), -1, "抄表值不能小于上一条记录");
        }
    }

    private void checkMod(MeterReading lastItem, MeterReading nowItem) {
        if (null != lastItem) {
            Assert.isTrue(nowItem.getMeterReading() >= lastItem.getMeterReading(), -1, "抄表值不能小于上一条记录");
        }
    }

    private void fillData(MeterReading lastItem, MeterReading meterRec) {
        MeterDevice meterDevice = meterDeviceService.selectMeterDeviceByCode(meterRec.getDeviceCode());
        Date date = new Date();

        if (null != lastItem) {
            meterRec.setYear(DateUtils.dateToString(date, "yyyy"));
            meterRec.setMeterMonth(DateUtils.dateToString(date, "yyyyMM"));
            meterRec.setLastReading(lastItem.getMeterReading());
            meterRec.setLastTime(lastItem.getMeterTime());
            meterRec.setMeterTime(date);
            meterRec.setIncrease(
                (meterRec.getMeterReading() - lastItem.getMeterReading()) * meterDevice.getMagnification());
        }
        else {
            meterRec.setYear(DateUtils.dateToString(date, "yyyy"));
            meterRec.setMeterMonth(DateUtils.dateToString(date, "yyyyMM"));
            meterRec.setMeterTime(date);
            meterRec.setIncrease(meterRec.getMeterReading() * meterDevice.getMagnification());
        }
    }
}
