package http.client;

import android.net.Uri;
import android.util.Log;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ShellUtils;
import com.hikvision.dmb.EthernetConfig;
import com.hikvision.dmb.network.InfoNetworkApi;
import com.hikvision.dmb.system.InfoSystemApi;
import com.hikvision.dmb.util.InfoUtilApi;

import http.OkHttpUtils;
import http.vo.request.TerminalAuthReq;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import okhttp3.Response;
import xn.xxp.app.LabApp;
import xn.xxp.home.auth.AuthType;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.DeviceConfig;
import xn.xxp.room.bean.LabConfig;
import xn.xxp.utils.Tool;

public final class HttpTool {

    public static Response terminalAuth(String devId) throws IOException {
        TerminalAuthReq terminalAuthReq = new TerminalAuthReq();
        terminalAuthReq.setDeviceCode(devId);
        terminalAuthReq.setCode("aio_infobord");
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        return OkHttpUtils.postSync(deviceConfig.getBaseUrl() + "terminal/authorize", GsonUtils.toJson(terminalAuthReq));
    }

    public static Response queryLabConfig(String devId) throws IOException {
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        return OkHttpUtils.getSync(deviceConfig.getBaseUrl() + "terminal/lab/getSubjectIdByNum/" + devId);
    }

    public static String checkUrl(String url) {
        try {
            String uriStr = url;
            if (!url.matches("https?://.*") && !url.matches("http?://.*")) {
                DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
                uriStr = Uri.parse(deviceConfig.getBaseUrl() + url).toString();
            }
            return uriStr;
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
            return url;
        }
    }

    public static Response getLabFaceList() {
        try {
            DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
            LabConfig labConfig = RoomTool.getInstance().labConfigDao().getLabConfig();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("subId", labConfig.getLabId());
            return OkHttpUtils.postSync(deviceConfig.getBaseUrl() + "terminal/sys/face/data/sub", jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        return null;
    }

    public static Response getRectifyAdviceNoteView(String noticeId) throws IOException {
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        return OkHttpUtils.getSync(deviceConfig.getBaseUrl() + "terminal/sec/getRectifyAdviceNoteView?noticeId=" + noticeId);
    }

    public static Response getLabStatusById(String labId, String userId) throws IOException {
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        return OkHttpUtils.getSync(deviceConfig.getBaseUrl() + "terminal/lab/getLabStatusById?labId=" + labId + "&userId=" + userId);
    }

    public static Response heartbeat(String devId) throws IOException {
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        return OkHttpUtils.getSync(deviceConfig.getBaseUrl() + "terminal/device/aio/heartbeat?deviceNo=" + devId);
    }


    /**
     * 设备状态
     *
     * @param metrics json字符串 记录设备状态
     */
    public static Response deviceStatus(String devId, String metrics) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceNo", devId);
            jsonObject.put("metrics", metrics);
            DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
            return OkHttpUtils.postSync(deviceConfig.getBaseUrl() + "terminal/device/aio/upload/status", jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        return null;
    }

    /**
     * 远程开锁发送状态
     */
    public static Response remoteUnlock(long messageId) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("messageId", messageId);
            jsonObject.put("status", 1);
            DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
            return OkHttpUtils.postSync(deviceConfig.getBaseUrl() + "terminal/lock/callback", jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        return null;
    }

    /**
     * 进出记录和授权记录配置
     *
     * @param openType 开门类型
     * @return
     */
    public static Response updateRecord(String userId, AuthType openType) {
        try {
            JSONObject jsonObject = new JSONObject();
            LabConfig labConfig = RoomTool.getInstance().labConfigDao().getLabConfig();
            jsonObject.put("subId", labConfig.getLabId());
            jsonObject.put("userId", userId);
            jsonObject.put("openType", openType.getType());
            DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
            String json = jsonObject.toString();
            LogUtils.d("updateRecord", json);
            return OkHttpUtils.postSync(deviceConfig.getBaseUrl() + "laboratory/app/board/updateRecord", jsonObject.toString());
        } catch (Exception e) {
            LogUtils.e("updateRecord", Log.getStackTraceString(e));
        }
        return null;
    }

    /**
     * 查询二维码登录状态
     *
     * @param code 时间
     */
    public static Response infoBordLogin(String devId, String code) throws IOException {
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        return OkHttpUtils.getSync(deviceConfig.getBaseUrl() + "terminal/lab/infobordLogin?macId=" + devId + "&code=" + code);
    }

    public static Response heartbeat() throws JSONException, IOException {
        DeviceConfig deviceConfig = RoomTool.getInstance().deviceConfigDao().getDeviceConfig();
        JSONObject jsonObject = new JSONObject();
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd("dumpsys activity activities", true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(commandResult.successMsg.getBytes())));
        String line;
        boolean isShow = false;
        while ((line = reader.readLine()) != null) {
            if (line.contains("mResumedActivity") || line.contains("mCurrentFocus")) {
                String[] itemArray = line.split(" ", -1);
                for (String item : itemArray) {
                    if (item.contains("/")) {
                        String packageName = item.substring(0, item.indexOf("/"));
                        isShow = AppUtils.getAppPackageName().equals(packageName);
                        break;
                    }
                }
                break;
            }
        }

        boolean adbEnabled = (1 == InfoSystemApi.getAdbStatus());
        EthernetConfig ethernetConfig = InfoNetworkApi.getEthernetConfig();
        // Ip
        String ip = ethernetConfig.getIpAddress();
        jsonObject.put("deviceNo", "EBOARD_" + InfoSystemApi.getSerialNumber());
        jsonObject.put("versionName", AppUtils.getAppVersionName());
        jsonObject.put("packageName", AppUtils.getAppPackageName());
        jsonObject.put("isShow", isShow);
        jsonObject.put("adbEnabled", adbEnabled);
        jsonObject.put("ip", ip);
        String json = jsonObject.toString();
        LogUtils.d(json);
        return OkHttpUtils.postSync(deviceConfig.getBaseUrl() + "terminal/machine/heartbeat", json);
    }
}
