package com.pwt.web.controller;

import com.pwt.Globals;
import com.pwt.common.annotation.Log;
import com.pwt.common.core.controller.BaseController;
import com.pwt.common.core.domain.AjaxResult;
import com.pwt.common.core.page.TableDataInfo;
import com.pwt.common.enums.BusinessType;
import com.pwt.common.utils.poi.ExcelUtil;
import com.pwt.netty.ChargerConfig;
import com.pwt.netty.ChargerServer;
import com.pwt.netty.common.charger.ChargerException;
import com.pwt.netty.common.charger.ResponseMessage;
import com.pwt.netty.common.charger.client.ClientResponseData;
import com.pwt.netty.message2.Charger;
import com.pwt.netty.message2.ChargerGun;
import com.pwt.web.domain.PwtChargeRecordVo;
import com.pwt.web.domain.PwtEmergencyVo;
import com.pwt.web.domain.StatisticsRecord;
import com.pwt.web.service.IPwtChargeRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.pwt.Globals.emergencyChargerId;

/**
 * 充电记录Controller
 * 
 * @author linyun
 * @date 2022-11-17
 */
@Api("充电记录")
@Slf4j
@RestController
@RequestMapping("/web/chargeRecord")
public class PwtChargeRecordController extends BaseController
{
    @Autowired
    private ChargerServer chargerServer;
    @Autowired
    private IPwtChargeRecordService pwtChargeRecordService;

    /**
     * 查询充电机编号字典
     * @return
     */
    @GetMapping("/getChargerNoDict")
    public AjaxResult getChargerNoDict()
    {
        return AjaxResult.success(pwtChargeRecordService.getChargerNoDict());
    }

    /**
     * 导出统计记录
     * @param response
     */
    @ApiOperation("导出统计记录")
    @PreAuthorize("@ss.hasPermi('web:chargeRecord:exportData')")
    @PostMapping("/exportData")
    public void statisticsRecordExport(HttpServletResponse response, StatisticsRecord statisticsRecord)
    {
        List<StatisticsRecord> list = pwtChargeRecordService.getStatisticsRecord(statisticsRecord);
        ExcelUtil<StatisticsRecord> util = new ExcelUtil<>(StatisticsRecord.class);
        util.exportExcel(response, list, "统计记录");
    }

    /**
     * 统计记录
     * @param statisticsRecord
     * @return
     */
    @ApiOperation("查询统计记录")
    @GetMapping("/getStatisticsRecord")
    public AjaxResult getStatisticsRecord(StatisticsRecord statisticsRecord)
    {
        return AjaxResult.success(pwtChargeRecordService.getStatisticsRecord(statisticsRecord));
    }

    /**
     * 查询充电记录列表
     */
    @ApiOperation("查询充电记录列表")
    @PreAuthorize("@ss.hasPermi('web:chargeRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(PwtChargeRecordVo pwtChargeRecordVo)
    {
        startPage();
        List<PwtChargeRecordVo> list = pwtChargeRecordService.selectPwtChargeRecordList(pwtChargeRecordVo);
        return getDataTable(list);
    }

    /**
     * 导出充电记录列表
     */
    @ApiOperation("导出充电记录列表")
    @PreAuthorize("@ss.hasPermi('web:chargeRecord:export')")
    @Log(title = "充电记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PwtChargeRecordVo pwtChargeRecordVo)
    {
        List<PwtChargeRecordVo> list = pwtChargeRecordService.selectPwtChargeRecordList(pwtChargeRecordVo);
        ExcelUtil<PwtChargeRecordVo> util = new ExcelUtil<PwtChargeRecordVo>(PwtChargeRecordVo.class);
        util.exportExcel(response, list, "充电记录");
    }

    /**
     * 获取充电记录详细信息
     */
    @ApiOperation("获取充电记录详细信息")
    @ApiImplicitParam(name = "recordId", value = "记录id", required = true, dataType = "Long", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermi('web:chargeRecord:query')")
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId)
    {
        return AjaxResult.success(pwtChargeRecordService.selectPwtChargeRecordById(recordId));
    }

//    /**
//     * 新增充电记录
//     */
//    @ApiOperation("新增充电记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "recordId", value = "记录id", dataType = "Long", dataTypeClass = Long.class),
//            @ApiImplicitParam(name = "vehicleNo", value = "车辆编号", dataType = "String", dataTypeClass = String.class),
//            @ApiImplicitParam(name = "chargerNo", value = "充电机编号", dataType = "String", dataTypeClass = String.class),
//            @ApiImplicitParam(name = "batterySn", value = "电池SN", dataType = "String", dataTypeClass = String.class),
//            @ApiImplicitParam(name = "chargeQuantity", value = "充电电量", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
//            @ApiImplicitParam(name = "chargeBeginTime", value = "充电开始时间", dataType = "Date", dataTypeClass = Date.class),
//            @ApiImplicitParam(name = "chargeEndTime", value = "充电结束时间", dataType = "Date", dataTypeClass = Date.class),
//            @ApiImplicitParam(name = "chargeDuration", value = "充电时长", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
//            @ApiImplicitParam(name = "startSoc", value = "开始SOC", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
//            @ApiImplicitParam(name = "endSoc", value = "结束SOC", dataType = "BigDecimal", dataTypeClass = BigDecimal.class),
//            @ApiImplicitParam(name = "stopReason", value = "停机原因", dataType = "String", dataTypeClass = String.class),
//            @ApiImplicitParam(name = "chargeMode", value = "充电模式", dataType = "String", dataTypeClass = String.class),
//    })

//    @PreAuthorize("@ss.hasPermi('web:chargeRecord:add')")
//    @Log(title = "充电记录", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody PwtChargeRecordVo pwtChargeRecordVo)
//    {
//        return toAjax(pwtChargeRecordService.insertPwtChargeRecord(pwtChargeRecordVo));
//    }

//    /**
//     * 修改充电记录
//     */
//    @ApiOperation("修改充电记录")
//    @PreAuthorize("@ss.hasPermi('web:chargeRecord:edit')")
//    @Log(title = "充电记录", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody PwtChargeRecordVo pwtChargeRecordVo)
//    {
//        return toAjax(pwtChargeRecordService.updatePwtChargeRecord(pwtChargeRecordVo));
//    }

    /**
     * 删除充电记录
     */
    @ApiOperation("删除充电记录")
    @PreAuthorize("@ss.hasPermi('web:chargeRecord:remove')")
    @Log(title = "充电记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds)
    {
        return toAjax(pwtChargeRecordService.deletePwtChargeRecordByIds(recordIds));
    }

    /**
     * 应急充电
     * @return
     */
    @ApiOperation("应急充电")
    @PreAuthorize("@ss.hasPermi('web:chargeRecord:add')")
    @Log(title = "应急充电", businessType = BusinessType.EXPORT)
    @PostMapping("/valid")
    public AjaxResult valid(@RequestBody PwtEmergencyVo pwtEmergencyVo) {
        // 拿到带有应急充电的充电机
//        Charger charger = Globals.uiData.getChargers().stream().filter(e -> e.isEnableEmergency()).collect(Collectors.toList()).get(0);
        // 拿到应急充电机的第一把枪
        ChargerGun chargerGun = Globals.uiData.getChargerGuns().stream().filter(e -> e.getId().equals(emergencyChargerId + "1")).collect(Collectors.toList()).get(0);
        if (chargerGun.getState().getState() == 2) {
            return AjaxResult.error("充电机目前正在充电，无法启用应急充电！");
        }
        if (chargerGun.getState().getState() == 4) {
            return AjaxResult.error("充电机存在故障，无法启用应急充电！");
        }
        return AjaxResult.success(pwtEmergencyVo);
    }

    /**
     * 开启充电
     * @param pwtEmergencyVo
     * @return
     */
    @ApiOperation("开启应急充电")
    @PreAuthorize("@ss.hasPermi('web:chargeRecord:add')")
    @Log(title = "开启应急充电", businessType = BusinessType.EXPORT)
    @PostMapping("/addCharging")
    public AjaxResult addCharging(@RequestBody PwtEmergencyVo pwtEmergencyVo) {
        try {
            ResponseMessage responseMessage = chargerServer.startCharge(pwtEmergencyVo.getCarNo(), pwtEmergencyVo.getChargerId(), pwtEmergencyVo.getChargerGunId(), 0, true);
            ClientResponseData responseData = ((ClientResponseData) responseMessage.getMessageData());
            return AjaxResult.success("resp status:" + responseData.getStatus());
        } catch (IllegalAccessException iae) {
            return AjaxResult.error("启动应急充电失败, 参数错误!");
        } catch (ChargerException ce) {
            return AjaxResult.error(ce.getMessage());
        } catch (Exception e) {
            log.error("启动应急充电失败: param: {}", pwtEmergencyVo, e);
            return AjaxResult.error("启动应急充电失败, 未知错误!");
        }
    }
}
