package com.rc.httpcore.client;

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

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ShellUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.rc.httpcore.HttpClient;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.OkHttpUtils;
import com.rc.httpcore.bean.AddChemical;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.vo.request.FaceCompare1Req;

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

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import xn.hxp.app.ChemicalApp;
import xn.hxp.ui.StartActivity;
import xn.hxp.utils.Tool;

public final class HttpTool {


    public static void getCheck(String deviceNum, String type, double version, Callback callback) throws IOException {
        OkHttpUtils.get(HttpConfig.Companion.getAPI_BASE_URL() + "iot/aio/report?deviceNo=" + deviceNum + "&code=" + type + "&version=" + version, callback);
    }


    public static String checkUrl(String url) {
        try {
            String uriStr = url;
            if (!url.matches("https?://.*") && !url.matches("http?://.*")) {
                uriStr = Uri.parse(HttpConfig.Companion.getAPI_BASE_URL() + url).toString();
            }
            return uriStr;
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
            return url;
        }
    }

    /**
     * 获取柜子信息
     */
    public static Response getCabinetList(String labId) throws IOException {
        return OkHttpUtils.getSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/getCabinetListBySub?subId=" + labId);
    }

    /**
     * 获取柜子信息
     */
    public static Response getApplyOrder(String labId) throws IOException {
        return OkHttpUtils.getSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/getApplyOrder?subId=" + labId);
    }

    /**
     * 查询化学品
     */
    public static Response searchchemical(String searchValue, String chemicalLevel) throws IOException {
        return OkHttpUtils.getSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/searchChemica?searchValue=" + searchValue + "&chemicalLevel=" + chemicalLevel);
    }

    /**
     * 待入库前校验待入库的化学品是否合法
     */
    public static Response addStockCheck(HxpChemicalVo hxpChemicalVo) throws IOException {
        String json = GsonUtils.toJson(hxpChemicalVo);
        LogUtils.d(json);
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/addStockCheck", json);
    }

    /**
     * 根据化学品code查询化学品信息
     */
    public static Response scanCodeChemical(String code, String subId) throws IOException {
        return OkHttpUtils.getSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/stockWait/scanCodeChemical?" + "label=" + code + "&subId=" + subId);
    }

    /**
     * 入库
     */
    public static Response addChemical(List<HxpChemicalVo> hxpChemicalList) throws Exception {
        String json = GsonUtils.toJson(new AddChemical(hxpChemicalList));
        LogUtils.d(json);
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/addStock", json);
    }

    /**
     * 国睿一键入库
     */
    public static Response autoChemicals(String json) throws Exception {
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/addBatchStock", json);
    }

    /**
     * 国睿修改存储位置
     */

    public static Response changeDoor(List<HxpChemicalVo> beanArrayList) throws IOException {
        String json = GsonUtils.toJson(beanArrayList);
        LogUtils.d(json);
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/updateStore", json);
    }

    /**
     * 双人验证人脸
     *
     * @param photoFile       图片
     * @param faceCompare1Req 支持多个柜门权限验证
     */
    public static Response checkUserFaceByPic1(File photoFile, String subjectId, FaceCompare1Req faceCompare1Req) throws IOException {
        return OkHttpUtils.postFileAndJson(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/verify/checkUserFaceByPic1", photoFile, subjectId, faceCompare1Req);
    }

    /**
     * 双人验证刷卡
     */
    public static Response useCardVerify1(String card, String subjectId, List<String> doorIds) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("cardNum", card);
        map.put("subId", subjectId);
        map.put("doorIds", doorIds);
        LogUtils.json(map);
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/verify/useCardVerify1", GsonUtils.toJson(map));
    }

    /**
     * 获取已申领未入库列表
     *
     * @param type          0:与自己相关 1:其它
     * @param subjectId     实验室ID
     * @param page          页数
     * @param pageSize      每页行数
     * @param applyOrder    申领单号
     * @param applyUserName 申领人名字
     * @param topicUserName 归属姓名
     * @return
     * @throws IOException
     */
    public static Response getHxpStockWait(int type, String subjectId, int page, int pageSize, String applyOrder, String applyUserName, String topicUserName) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("subId", subjectId);
        map.put("page", page);
        map.put("pageSize", pageSize);
        map.put("applyOrder", applyOrder);
        map.put("applyUserName", applyUserName);
        map.put("topicUserName", topicUserName);
        LogUtils.json(map);
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/getHxpStockWait", GsonUtils.toJson(map));
    }

    /**
     * 双人验证扫码
     * 小程序扫码后查询小程序扫码登录状态
     */
    public static Response aioScanLogin1(String time, String subjectId, List<String> doorIds) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", time);
        map.put("subId", subjectId);
        map.put("doorIds", doorIds);
        LogUtils.json(map);
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "chemical/aio/verify/aioScanLogin1", GsonUtils.toJson(map));
    }

    /**
     * 获取版本信息
     */
    public static Response getCheck() throws IOException {
        return OkHttpUtils.getSync(HttpConfig.Companion.getAPI_BASE_URL() + "iot/aio/report?" + "deviceNo=" + Tool.INSTANCE.getSerialNumber() + "&code=" + "aio_chemical" + "&version=100");
    }

    /**
     * 登出
     *
     * @throws IOException
     */
    public static void logout() throws IOException {
        WaitDialog.show("退出中...");
        OkHttpUtils.get(HttpConfig.Companion.getAPI_BASE_URL() + "auth/logout", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                WaitDialog.dismiss();
                ThreadUtils.runOnUiThread(() -> Toast.makeText(ActivityUtils.getTopActivity(), e.getMessage(), Toast.LENGTH_LONG).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                WaitDialog.dismiss();
                ChemicalApp.userData = null;
                ChemicalApp.subjectId = null;
                HttpClient.INSTANCE.setToken(null);
                ActivityUtils.startActivity(StartActivity.class);
            }
        });
    }

    public static Response heartbeat() throws JSONException, IOException {
        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;
            }
        }

        jsonObject.put("deviceNo", Tool.INSTANCE.getSerialNumber());
        jsonObject.put("versionName", AppUtils.getAppVersionName());
        jsonObject.put("packageName", AppUtils.getAppPackageName());
        jsonObject.put("isShow", isShow);
        jsonObject.put("adbEnabled", true);
        jsonObject.put("ip", NetworkUtils.getIPAddress(true));
        LogUtils.d("心跳", jsonObject);
        return OkHttpUtils.postSync(HttpConfig.Companion.getAPI_BASE_URL() + "terminal/machine/heartbeat", jsonObject.toString());
    }

}
