package com.ruoyi.web.core.config;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ruoyi.bd.domain.UWBAuth;
import com.ruoyi.bd.service.rpc.UWBWebService;
import com.ruoyi.bd.socket.UWBSocket.UWBSocketClient;
import com.ruoyi.common.utils.DateTimeUtil;

import cn.hutool.core.map.MapUtil;

@Configuration
@ConfigurationProperties(prefix = "bd.uwb")
@ConditionalOnProperty(name = "bd.uwb.enabled", havingValue = "true")
public class UWBCfg {
    private static final Logger log = LoggerFactory.getLogger(UWBCfg.class);

    private String uwbSocket;

    private String uwbUsr;

    private String uwbPwd;

    private String uwbHost;

    public String getUwbHost() {
        return uwbHost;
    }

    public void setUwbHost(String uwbHost) {
        this.uwbHost = uwbHost;
    }

    @Resource
    private UWBWebService uwbWebService;

    public String getUwbSocket() {
        return uwbSocket;
    }

    public void setUwbSocket(String uwbSocket) {
        this.uwbSocket = uwbSocket;
    }

    public String getUwbUsr() {
        return uwbUsr;
    }

    public void setUwbUsr(String uwbUsr) {
        this.uwbUsr = uwbUsr;
    }

    public String getUwbPwd() {
        return uwbPwd;
    }

    public void setUwbPwd(String uwbPwd) {
        this.uwbPwd = uwbPwd;
    }

    @Bean
    public WebSocketClient webSocketClient() throws URISyntaxException {
        String ws = this.getUwbSocket();
        UWBSocketClient webSocketClient = new UWBSocketClient(new URI(ws));
        UWBAuth uwbAuth = authUWB();
        if (ObjectUtils.isEmpty(uwbAuth)) {
            return null;
        }
        webSocketClient.setAuthToken(uwbAuth);
        webSocketClient.connect();
        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (webSocketClient.isClosed()) {
                    UWBAuth uwbAuth = authUWB();
                    if (ObjectUtils.isEmpty(uwbAuth)) {
                        return;
                    }
                    webSocketClient.setAuthToken(uwbAuth);
                    webSocketClient.reconnect();
                }
            }
        }, 1000, 5000);
        return webSocketClient;
    }

    private UWBAuth authUWB() {
        Map map = uwbWebService.exchangeToken(new HashMap<String, Object>() {
            {
                {
                    put("username", uwbUsr);
                    put("password", uwbPwd);
                    put("isfresh", 1);
                }
            }
        });
        Integer code = MapUtil.getInt(map, "code", 400);
        if (code != 200) {
            log.error("获取token失败");
            return null;
        }
        JSONObject data = MapUtil.get(map, "data", JSONObject.class);
        UWBAuth uwbAuth = new UWBAuth();
        String accessToken = data.getString("access_token");
        if (StringUtils.isBlank(accessToken)) {
            log.error("获取token失败{}", data);
            return null;
        }
        uwbAuth.setAccessToken(data.getString("access_token"));
        uwbAuth.setRegister(Long.toString(DateTimeUtil.timestampMillis()));
        return uwbAuth;
    }

}
