package com.ruoyi.iot.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.iot.domain.TDevicePlan;
import com.ruoyi.iot.domain.WeitiandiDeviceInfo;
import com.ruoyi.iot.entity.param.DeviceParam;
import com.ruoyi.iot.mapper.TDeviceRecordMapper;
import com.ruoyi.iot.queue.MsgQueue;
import com.ruoyi.iot.service.*;
import com.ruoyi.iot.transdata.RpcResult;
import com.ruoyi.iot.transdata.entity.MainBoard;
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.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

@Slf4j
@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private ITDevicePlanService itDevicePlanService;
    @Autowired
    private ITDeviceRecordService itDeviceRecordService;

    @Autowired
    private ITChargeRecordService itChargeRecordService;

    @Autowired
    private DeviceControlerService deviceControlerService;

    @Autowired
    private IWeitiandiDeviceInfoService iWeitiandiDeviceInfoService;
    @Autowired
    private MsgQueue msgQueue;

    @Autowired
    private TDeviceRecordMapper tDeviceRecordMapper;

    @GetMapping("/testrpc")
    @Anonymous
    public RpcResult testRpc(){
        return null;
    }
    @PostMapping("/checkVersion")
    @ApiOperation("检测版本")
    public AjaxResult checkVersion(@RequestParam("versionCode")Integer appVersionCode, HttpServletRequest request){
        String appfrom = request.getParameter("appfrom");
        if(StringUtils.isEmpty(appfrom)){
            appfrom = "normal";
        }
        Map<String, Object> deviceData = tDeviceRecordMapper.getDeviceData("select * from cz_app_version where `from` = '"+appfrom+"' order by create_time desc limit 1");
        return AjaxResult.success(deviceData);
    }


    @GetMapping("/downUrl")
    @ApiOperation("检测版本")
    public RedirectView downUrl(){
        Map<String, Object> deviceData = tDeviceRecordMapper.getDeviceData("select * from dowload_url limit 1");
        Object url = deviceData.get("url");
        String urlString = url.toString();
        return new RedirectView(urlString);
    }

    @PostMapping("/bindDevice")
    @ApiOperation("绑定设备")
    public AjaxResult bindDevice(@RequestParam("qrcode") String qrcode){
        Long userId = getLoginUser().getUserId();
        WeitiandiDeviceInfo deviceInfoByQrcode = iWeitiandiDeviceInfoService.bindDevice(qrcode, userId);
        return AjaxResult.success(deviceInfoByQrcode);
    }


    @PostMapping("/unbindDevice")
    @ApiOperation("解绑设备")
    public AjaxResult unbindDevice(@RequestParam("qrcode") String qrcode){
        Long userId = getLoginUser().getUserId();
        WeitiandiDeviceInfo deviceInfoByQrcode = iWeitiandiDeviceInfoService.unbindDevice(qrcode, userId);
        return AjaxResult.success(deviceInfoByQrcode);
    }

    @PostMapping("/deviceList")
    @ApiOperation("设备列表")
    public AjaxResult deviceList(){
        Long userId = getLoginUser().getUserId();
        List<WeitiandiDeviceInfo> list = iWeitiandiDeviceInfoService.listDevice(userId);
        return AjaxResult.success(list);
    }

    @PostMapping("/getDeviceInfo")
    @ApiOperation("获取设备详情")
    public AjaxResult getDeviceInfo(@RequestParam("qrcode") String qrcode){
        Long userId = getLoginUser().getUserId();
        WeitiandiDeviceInfo deviceInfoByQrcode = iWeitiandiDeviceInfoService.getDeviceInfoByQrcode(qrcode, userId);
        return AjaxResult.success(deviceInfoByQrcode);
    }

    @PostMapping("/sendPortDetailCmd")
    @ApiOperation("发送获取端口详情CMD")
    public AjaxResult sendPortDetailCmd (@RequestBody DeviceParam deviceParam) {
        deviceControlerService.sendPortDetailCmd(deviceParam);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        return AjaxResult.success(sdf.format(date));
    }

    @PostMapping("/getPortDetail")
    @ApiOperation("根据设备编号查询设备详情")
    public AjaxResult getPortDetail (@RequestBody DeviceParam deviceParam) {
        JSONObject portDetail = itDeviceRecordService.getPortDetail(deviceParam);
        return AjaxResult.success(portDetail);
    }

    @PostMapping("/startCharge")
    public AjaxResult startCharge(@RequestBody DeviceParam deviceParam) {
        // 对电流值进行处理
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        itChargeRecordService.startCharge(deviceParam.getDeviceId(),deviceParam.getCcid(),userId,deviceParam.getPort());
        return AjaxResult.success();
    }

    @PostMapping("/stopCharge")
    public AjaxResult stopCharge(@RequestBody DeviceParam deviceParam) {
        // 对电流值进行处理
        deviceControlerService.stopCharge(deviceParam.getDeviceId(),deviceParam.getCcid(),deviceParam.getPort());
        return AjaxResult.success();
    }

    /**
     * 1.在开始充电后，需要做一个定时任务检测是否结束充电
     *
     * 2.在普通情况下 检查枪是否变动  暂定 感觉是枪口连上了 才有
     * @return
     */
    @PostMapping("/statusChange")
    public AjaxResult checkStatusChange(@RequestBody DeviceParam deviceParam){
        JSONObject object = itDeviceRecordService.checkStatus(deviceParam);
        return AjaxResult.success(object);
    }

    @PostMapping("/setCurrent")
    public AjaxResult setCurrent(@RequestBody DeviceParam deviceParam,@RequestParam("current") Integer current) {
        MainBoard mainBoard = new MainBoard();
        mainBoard.setMaxCurrent(current);
        String deviceId = deviceParam.getDeviceId();
        String ccid = deviceParam.getCcid();
        deviceControlerService.setMainBoard(deviceId,ccid,mainBoard);
        return AjaxResult.success(current);
    }

    @PostMapping("/sendMainboardCmd")
    public AjaxResult sendMainboardCmd(@RequestBody DeviceParam deviceParam) {

        deviceControlerService.getMainBoard(deviceParam.getDeviceId(),deviceParam.getCcid());
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        return AjaxResult.success(sdf.format(date));
    }

    @PostMapping("/getMainboardConfig")
    public AjaxResult getMainboardConfig(@RequestBody DeviceParam deviceParam) {
        JSONObject mainboardConfig = itDeviceRecordService.getMainboardConfig(deviceParam);
        return AjaxResult.success(mainboardConfig);
    }

    @PostMapping("/resetMainboard")
    public AjaxResult resetMainboard(@RequestBody DeviceParam deviceParam) {
        // 恢复默认配置
        deviceControlerService.reset(deviceParam.getDeviceId(),deviceParam.getCcid());
        return AjaxResult.success();
    }

    @PostMapping("/restartMainboard")
    public AjaxResult restartMainboard(@RequestBody DeviceParam deviceParam) {
        // 重启充电桩
        deviceControlerService.restart(deviceParam.getDeviceId(),deviceParam.getCcid());
        return AjaxResult.success();
    }

    @RequestMapping("/addMsg")
    public String addMsg(@RequestParam("msg") String msg){
        msgQueue.add(msg);
        return "ok";
    }


    @RequestMapping("/getPlanInfo")
    public AjaxResult getPlanInfo(String deviceId,String port){
        Long userId = getLoginUser().getUserId();
        TDevicePlan tDevicePlan = itDevicePlanService.getPlanInfo(deviceId,port,userId);
        return  AjaxResult.success(tDevicePlan);
    }

    @RequestMapping("/cancelPlan/{id}")
    public RpcResult cancelPlan(@PathVariable("id") Long planId){
        RpcResult rpcResult = itDevicePlanService.cancelPlan(planId);
        return rpcResult;
    }

}
