package com.xhpc.order.controller;

import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.page.TableDataInfo;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.order.api.XhpcChargeOrderController;
import com.xhpc.order.service.IXhpcChargeOrderService;
import com.xhpc.order.service.IXhpcStopChargingOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * program: ruoyi
 * User: HongYun
 * Date:2021-09-07 15
 */
@RestController
@RequestMapping(value = "/stopChargingOrder")
public class XhpcStopChargingOrderController extends BaseController {

    @Autowired
    private IXhpcStopChargingOrderService iXhpcStopChargingOrderService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private PowerPileService powerPileService;

    @Autowired
    private IXhpcChargeOrderService xhpcChargeOrderService;

    @GetMapping("/list")
    public TableDataInfo list(Long userId, Long chargingStationId, Long terminalId){
        startPage();
        return getDataTable(iXhpcStopChargingOrderService.list(userId, chargingStationId, terminalId));
    }

    /**
     * 停止充电
     * @param serialNumber   终端编号
     * @return
     */
    @GetMapping("/stopUp")
    public AjaxResult stopUp(@RequestParam String serialNumber,@RequestParam Long chargingPileId){
        //查询缓存是否该终端在充电
        Map<String, Object> cacheMap = redisService.getCacheMap("gun:" + serialNumber);

        if(cacheMap!=null){
            if(cacheMap.get("orderkey") !=null){
                String orderkey = cacheMap.get("orderkey").toString().substring(6);

                Map<String, Object> xhpcChargingPileById = xhpcChargeOrderService.getXhpcChargingPileById(chargingPileId);
                String version ="0A";
                if(xhpcChargingPileById.get("communicationProtocolVersion")!=null && !"".equals(xhpcChargingPileById.get("communicationProtocolVersion").toString())){
                    version=xhpcChargingPileById.get("communicationProtocolVersion").toString();
                }
                R r = powerPileService.stopCharging(orderkey, orderkey.substring(0,14), orderkey.substring(0,16), version);

                if(r.getCode()==200){
                    return AjaxResult.success("停止充电命令已下发");
                }else{
                    return AjaxResult.success(r.getMsg());
                }
            }
        }
        return AjaxResult.success("无车辆充电");
    }
}
