package com.xhpc.order.api;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhpc.common.api.WebSocketService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.HttpUtils;
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.common.security.service.TokenService;
import com.xhpc.order.service.IXhpcChargeOrderService;
import com.xhpc.order.service.IXhpcHistoryOrderService;
import com.xhpc.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author yuyang
 * @date 2021/8/4 9:59
 */
@RestController
@RequestMapping("/api/chargeOrder")
@Api(value = "充电订单接口", tags = "充电订单接口")
public class XhpcChargeOrderController extends BaseController {

    @Autowired
    private IXhpcChargeOrderService iXhpcChargeOrderService;
    @Autowired
    private IXhpcHistoryOrderService xhpcHistoryOrderService;
    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TokenService tokenService;

    private static final Logger logger = LoggerFactory.getLogger(XhpcChargeOrderController.class);

    /**
     * 实时订单(川逸充)
     */
    @GetMapping("/getCYCHistotyChargeOrderMessage")
    public AjaxResult getCYCHistotyChargeOrderMessage(Long userId, Integer userType, String tenantId,String thirdCode){
        return iXhpcChargeOrderService.getCYCHistotyChargeOrderMessage(userId,userType,tenantId,thirdCode);
    }

    /**
     * 我的实时订单(微信)
     */
    @GetMapping("/getUserHistotyChargeOrderMessage")
    public AjaxResult getUserHistotyChargeOrderMessage(HttpServletRequest request)
    {
        return iXhpcChargeOrderService.getUserHistotyChargeOrderMessage(request);
    }

    /**
     * 启动充电检查(微信)
     */
    @GetMapping("/getHistotyChargeOrderMessage")
    public AjaxResult getHistotyChargeOrderMessage(HttpServletRequest request)
    {
        return iXhpcChargeOrderService.getHistotyChargeOrderMessage(request);
    }

    /**
     * 异常订单(微信)
     */
    @GetMapping("/getHistotyChargeOrderStatusList")
    public TableDataInfo getHistotyChargeOrderStatusList(HttpServletRequest request)
    {
        List<Map<String, Object>> list = iXhpcChargeOrderService.getHistotyChargeOrderStatusList(request);
        return getDataTable(list);
    }


    /**
     * 启动充电
     * @param userId
     * @param serialNumber   终端编码
     * @param type           1 微信 2支付宝 3 APP  4.刷卡 5vin
     * @return
     */
    @GetMapping("/startUp")
    public AjaxResult startUp(HttpServletRequest request, @RequestParam Long userId, @RequestParam String serialNumber, @RequestParam Integer type){
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<启动充电>>>>>>>>>>>>>>>>>"+serialNumber);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<启动充电>>>>>>>>>>>>>>>>>"+serialNumber);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<启动充电：userId>>>>>>>>>>>>>>>>>"+userId);
        return iXhpcChargeOrderService.startUp(request,userId, serialNumber, type);
    }


    /**
     * 停止充电
     * @param userId
     * @param serialNumber   终端编码
     * @param chargingOrderId   充电id
     * @return
     */
    @GetMapping("/stopUp")
    public AjaxResult stopUp(HttpServletRequest request,@RequestParam Long userId,@RequestParam String serialNumber,@RequestParam Long chargingOrderId){
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<停止充电>>>>>>>>>>>>>>chargingOrderId>>>"+chargingOrderId);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<停止充电>>>>>>>>>>>>>>chargingOrderId>>>"+chargingOrderId);
        return iXhpcChargeOrderService.stopUp(request,userId, serialNumber, chargingOrderId);
    }


    /**
     * 用户历史订单列表接口
     */
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request)
    {
        List<Map<String,Object>> list = xhpcHistoryOrderService.list(request);
        return getDataTable(list);
    }


    /**
     * 用户订单详情接口
     * @param userId                 用户id
     * @param historyOrderId         历史订单id
     * @param type                   1 历史订单id 2 充电订单id (暂时没用)
     * @param chargingOrderId        充电订单id
     * @return
     */
    @GetMapping("/gethistotyOrderMessage")
    public AjaxResult gethistotyOrderMessage(HttpServletRequest request,@RequestParam Long userId,Long historyOrderId,Integer type,Long chargingOrderId)
    {
        return xhpcHistoryOrderService.gethistotyOrderMessage(request,userId,historyOrderId,type,chargingOrderId);
    }


    /**
     * 实时数据接口
     * @param userId                 用户id
     * @return
     */
    @GetMapping("/getOrderMessage")
    public void getOrderMessage(HttpServletRequest request,@RequestParam Long userId)
    {
        logger.info("<<<<<<<<<<再次<<<<<<<<<<<<<<实时数据接口>>>>>>>>>>>>>>>>>");
        LoginUser loginUser = tokenService.getLoginUser(request);
        String tenantId = loginUser.getTenantId();
        String userTypeUtil = loginUser.getUserTypeUtil();
        String message = tenantId + userTypeUtil + loginUser.getUserid();
        logger.info("<<<<<<<<<<再次<<<<<<<<<<<<<<"+message+">>>>>>>>>>>>>>>>>");
        Map<String, Object> cacheMap = redisService.getCacheMap("realTimeTenantId:"+message);
        Map<String,Object> map =new HashMap<>();
        map.put("code", 200);
        map.put("message", "实时数据");
        map.put("userId", userId);
        if(cacheMap==null){
            Map<String, Object> data = new HashMap<>();
            BigDecimal decimal = new BigDecimal(0);
            data.put("amountCharged",decimal);
            data.put("gunNumber","0");
            data.put("chargingOrderId",0L);
            data.put("soc",0);
            data.put("chargingTime","0");
            data.put("electricCurrent",decimal);
            data.put("voltage", decimal);
            data.put("power", "0");
            data.put("chargingDegree", decimal);
            data.put("remainingTime","0");
            data.put("chargingTimeNumber",0);
            data.put("serialNumber","0");
            data.put("type","-1");
            data.put("parkingInstructions","充电完成请尽快离场,超时车位占用费10元/小时");
            map.put("data", data);
            logger.info("<<<<<<<<<<不是缓存数据<<<<<<<<<<<<<<");
        }else{
            map.put("data",cacheMap);
            logger.info("<<<<<<<<<<是缓存数据<<<<<<<<<<<<<<");
            logger.info("<<<<<<<<<<是缓存数据<<<<<<<<<<<<<<");
        }
        JSONObject json = new JSONObject(map);
        webSocketService.getMessage(message,json.toString());
        logger.info("<<<<<<<<<<发送数据<<<<<<<<<<<<<<"+ json.toString()+">>>>>>>>>>>>>>>>>");
    }

    /**
     * 卡启动前判断
     * @return
     */
    @GetMapping("/cardStartup")
    public R cardStartup(Long userId, String serialNumber, Integer userType, String tenantId, Integer type, String grantOperator,String rateModelId)
    {
        logger.info("<<<<<<<<<<卡启动前判断<<<<<<<<<<<<<<"+ serialNumber+">>>>>>>>"+grantOperator+">>>>>>"+rateModelId+">>>");
        logger.info("<<<<<<<<<<卡启动前判断<<<<<<<<<<<<<<"+ userId+">>>>>>>>"+userType+">>>>>>"+tenantId+">>>"+type+">>>>>");
        return iXhpcChargeOrderService.cardStartup(userId,serialNumber,userType,tenantId,type,grantOperator,rateModelId);
    }


    @GetMapping("/pileVin")
    public R pileVin(String serialNumber,String vinNumber)
    {
        logger.info("<<<<<<<<<<VIN码启动前判断<<<<<<<<<<<<<<serialNumber>>>>>>>>"+serialNumber+">>>vinNumber>>>"+vinNumber+">>>");
        return iXhpcChargeOrderService.pileVin(serialNumber,vinNumber);
    }

    @GetMapping("/constantSoc")
    public R constantSoc(@RequestParam(value = "orderNo") String orderNo,@RequestParam(value = "soc") String soc) {
        iXhpcChargeOrderService.constantSoc(orderNo, soc);
        return null;
    }

    @GetMapping("/zhbSoc")
    public R zhbSoc(@RequestParam(value = "orderNo") String orderNo,@RequestParam(value = "soc") String soc) {
        iXhpcChargeOrderService.zhbSoc(orderNo, soc);
        return null;
    }

    /**
     * 川逸充启动充电
     * @param userId
     * @param serialNumber   终端编码
     * @param type           1 微信
     * @param type           1 微信
     * @return
     */
    @GetMapping("/cycStartUp")
    public R cycStartUp(HttpServletRequest request, @RequestParam Long userId, @RequestParam String serialNumber, @RequestParam Integer type,@RequestParam Integer source,@RequestParam BigDecimal money,@RequestParam String phone,@RequestParam String PlateNum){
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<川逸充启动充电>>>>>>>>>>>>>>>>>"+serialNumber);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<川逸充启动充电：userId>>>>>>>>>>>>>>>>>"+userId);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<川逸充启动充电：source>>>>>>>>>>>>>>>>>"+source);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<川逸充启动充电金额：money>>>>>>>>>>>>>>>>>"+money);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<川逸充启动充电手机：phone>>>>>>>>>>>>>>>>>"+phone);
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<川逸充启动充电手机：PlateNum>>>>>>>>>>>>>>>>>"+PlateNum);
        return iXhpcChargeOrderService.cycStartUp(request,userId, serialNumber, type,source,money,phone,PlateNum);
    }


    /**
     * 按照输入充电量启动充电
     * @param userId
     * @param serialNumber   终端编码
     * @param type           1 微信 2支付宝 3 APP
     * @param chargingCapacity   充电量
     * @return
     */
    @GetMapping("/chargingCapacityStartUp")
    public AjaxResult chargingCapacityStartUp(HttpServletRequest request, @RequestParam Long userId, @RequestParam String serialNumber, @RequestParam Integer type, @RequestParam Integer chargingCapacity){

        return iXhpcChargeOrderService.chargingCapacityStartUp(request,userId, serialNumber, type,chargingCapacity);
    }

    @GetMapping("/ceshi")
    public AjaxResult ceshi(String phone,String vin, String plateNnum,Long chargingStationId,String time){
        String format = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        int blacklistUser = iXhpcChargeOrderService.getBlacklistUser(phone, vin, plateNnum, chargingStationId, format);
        return AjaxResult.success(blacklistUser);
    }



    /**
     * 查询订单
     */
    @GetMapping("/getUserOrderMessage")
    public AjaxResult getUserOrderMessage(Long userId, Integer source){
        return iXhpcChargeOrderService.getUserOrderMessage(userId,source);
    }


    /**
     * 18 19单独处理，实时订单数据10分钟之内没有数据，就自动结算
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void getAutomaticSettlement(){
        iXhpcChargeOrderService.getAutomaticSettlement();
    }


    //查询当前用户是否有充电中的订单，适合与C端用户、社区用户和B端用户
    @GetMapping("/getUserOderMassage")
    public AjaxResult getUserOderMassage(HttpServletRequest request){
        return iXhpcChargeOrderService.getUserOderMassage(request);
    }

}
