package com.example.iot_controlhost.utils.network;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.widget.ImageView;

import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.FileUtils;
import com.example.iot_controlhost.R;
import com.example.iot_controlhost.model.net.CommonResponse;
import com.example.iot_controlhost.ui.dialog.ConfirmDialog;
import com.example.iot_controlhost.utils.DialogUtil;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.QRCodeUtil;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.log.MyLog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import es.dmoral.toasty.Toasty;

/**
 * @Description 通用网络请求
 * @Author DuanKaiji
 * @CreateTime 2023年10月19日 15:18:50
 */
public class PublicNetRequest {

    /**
     * 读取登记作业-签到图片-网络请求
     */
    public static void loadSignImage(Context mContext, ImageView imageView) {
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.qrCodeCreate);
        params.addParameter("AreaCode", RoomSetting.getAreaCode());
        x.http().get(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) throws JSONException {
                String data = model.getData().toString();
                String codeUrl = new JSONObject(data).getString("url");
                Bitmap logoBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo_blue);
                if (imageView != null) {
                    imageView.setImageBitmap(QRCodeUtil.createQRCodeBitmap(codeUrl, 300, 300, logoBitmap, 30));
                }
            }

            @Override
            public void error(Throwable e) {
                Toasty.error(mContext, "扫码签到图片生成失败").show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUtil.hideLoadingDialog();
            }
        });
    }


    /**
     * 语音通知-设备故障预警
     *
     * @param deviceName     设备名称
     * @param noticeTypeCode 通知类型
     *                       只发公众号  0默认
     *                       语音+公众号 1数据采集故障 2设备操作故障 3设备疑似故障
     * @param noticeLevel    通知等级
     * @param noticeContent  通知内容
     */
    public static void AnomalyNotice(String deviceName, int noticeTypeCode, int noticeLevel, String noticeContent) {
        if (RoomSetting.getNoticeType().equals(RoomSetting.NOTICE_TYPE_SPINNER[0])) {
            MyLog.warning("需要预警通知，但是用户设置不需要");
            return;
        } else if (RoomSetting.getNoticeType().equals(RoomSetting.NOTICE_TYPE_SPINNER[1]) && noticeTypeCode != 0) {
            MyLog.warning("需要语音通知，但是用户设置不需要，修改为公众号通知");
            noticeTypeCode = 0;
        }
        MyLog.warning("预警：" +
                "\n方式：" + (noticeTypeCode == 0 ? "公众号" : "公众号+语音") +
                "\n内容：" + noticeContent);
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.notice);
        params.addParameter("areaCode", RoomSetting.getAreaCode());
        params.addParameter("DeviceName", deviceName);
        params.addParameter("NoticeTypeCode", String.valueOf(noticeTypeCode));
        params.addParameter("OccurTime", MyUtil.getDateTime());
        params.addParameter("NoticeLevel", noticeLevel);
        params.addParameter("NoticeContent", noticeContent);
        x.http().post(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                MyLog.warning("设备故障预警成功：发送内容：" + noticeContent);
            }

            @Override
            public void error(Throwable e) {
                MyLog.warning("设备故障预警失败：" + e.getMessage());
            }
        });
    }

    /**
     * 公众号发送温湿度预警消息
     *
     * @param temperatureStr 异常温度
     * @param humidityStr    异常湿度
     * @param remarks        提示信息
     */
    public static void THWarningToWeChat(String temperatureStr, String humidityStr, String remarks) {
        // 发送预警
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.thWarning);
        params.addParameter("Code", RoomSetting.getAreaCode());
        params.addParameter("Temperature", temperatureStr);
        params.addParameter("Humidity", humidityStr);
        params.addParameter("Remarks", remarks);
        x.http().post(params, new XHttpShorthand<CommonResponse>() {
            @Override
            public void success(CommonResponse model) {
                //发送完成
                MyLog.warning("温湿度预警信息发送成功");
            }

            @Override
            public void error(Throwable e) {
                MyLog.warningError("温湿度预警信息发送失败：" + e.getMessage());
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUtil.hideLoadingDialog();
            }
        });
    }

    /**
     * 下载APK
     *
     * @param path 下载地址
     */
    public static void downFile(Context context, final String path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            context.startActivity(intent);
            return;
        }
        String fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "BBIT_FRP.apk";
        FileUtils.delete(fileName);
        String dirPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        File currentFile = new File(dirPath, "BBIT_FRP.apk");
        File lastFile = new File(dirPath, "BBIT_FRP_last.apk");

        // 如果存在旧的备份文件，先删除（只保留一个）
        if (lastFile.exists()) {
            lastFile.delete();
        }
        if (currentFile.exists()) {
            currentFile.renameTo(lastFile);
        }
        RequestParams params = new RequestParams(path);
        params.setSaveFilePath(currentFile.getAbsolutePath());
        params.setAutoRename(true);
        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onStarted() {
                DialogUtil.showProgressIndicatorDialog(context, "开始下载必需文件");
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                if (isDownloading) {
                    int progress = (int) ((current * 100) / total);
                    DialogUtil.setProgressIndicatorDialog("正在下载中，当前已下载" + progress + "%", progress);
                }
            }

            @Override
            public void onSuccess(File result) {
                MyLog.network("下载成功: " + result);
                installAPK(context, fileName);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                MyLog.networkError("下载失败，原因：" + ex.getMessage());
                new ConfirmDialog(context, context.getString(R.string.tip), "下载失败，原因：" + ex.getMessage(), null).show();
            }

            @Override
            public void onWaiting() {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                DialogUtil.hideProgressIndicatorDialog();
            }
        });
    }

    /**
     * 安装程序
     *
     * @param context  上下文
     * @param filePath 安装的文件路径
     */
    public static void installAPK(Context context, String filePath) {
        try {
            File apkFile = new File(filePath);
            if (apkFile.exists()) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } else {
                Toasty.error(context, "安装包文件不存在").show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toasty.error(context, "安装失败：" + e.getMessage()).show();
        }
    }

}
