package com.casic.dcms.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.casic.dcms.ui.BigImageActivity;
import com.casic.dcms.ui.CaseProcessActivity;
import com.casic.dcms.utils.callback.IDownloadListener;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OtherUtils {
    private static final String TAG = "OtherUtils";

    /**
     * 绘制文字到右下角
     */
    public static String drawTextToRightBottom(Context context, Bitmap bitmap, String name, String date, String time) {
        //初始化画笔
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);
        paint.setDither(true); // 获取跟清晰的图像采样
        paint.setFilterBitmap(true);// 过滤一些
        paint.setTextSize(QMUIDisplayHelper.dp2px(context, 20));
        Rect nameBounds = new Rect();
        paint.getTextBounds(name, 0, name.length(), nameBounds);
        Rect dateBounds = new Rect();
        paint.getTextBounds(date, 0, date.length(), dateBounds);
        Rect timeBounds = new Rect();
        paint.getTextBounds(time, 0, time.length(), timeBounds);

        //添加水印
        android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.RGB_565;
        }
        bitmap = bitmap.copy(bitmapConfig, true);

        Canvas canvas = new Canvas(bitmap);
        final int bitmapWidth = bitmap.getWidth();
        final int bitmapHeight = bitmap.getHeight();
        final int paddingRight = QMUIDisplayHelper.dp2px(context, 10);
        //有几行就写几行
        canvas.drawText(name, bitmapWidth - nameBounds.width() - paddingRight,
                bitmapHeight - QMUIDisplayHelper.dp2px(context, 55), paint);
        canvas.drawText(date, bitmapWidth - dateBounds.width() - paddingRight,
                bitmapHeight - QMUIDisplayHelper.dp2px(context, 30), paint);
        canvas.drawText(time, bitmapWidth - timeBounds.width() - paddingRight,
                bitmapHeight - QMUIDisplayHelper.dp2px(context, 10), paint);

        //将带有水印的图片保存
        File file = FileUtils.getWaterImageFile();
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    //查看大图
    public static void showBigImage(Context context, int index, ArrayList<String> imageList) {
        Intent intent = new Intent(context, BigImageActivity.class);
        intent.putExtra("index", index);
        intent.putStringArrayListExtra("images", imageList);
        context.startActivity(intent);
    }

    //查看案卷处理记录
    public static void showCaseProcess(Context context, String processId) {
        Intent intent = new Intent(context, CaseProcessActivity.class);
        intent.putExtra("processId", processId);
        context.startActivity(intent);
    }

    //获取SimSerialNumber
    @SuppressLint({"HardwareIds"})
    public static String obtainSimCardSerialNumber(Context context) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //Android 10改为获取Android_ID
            return Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } else {
            TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            Class<?> telephonyClass;
            try {
                telephonyClass = Class.forName(telephony.getClass().getName());
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return "";
                }
                String imei = telephony.getDeviceId();
                if (TextUtils.isEmpty(imei)) {
                    Method m = telephonyClass.getMethod("getSimSerialNumber", int.class);
                    //主卡，卡1
                    String mainCard = (String) m.invoke(telephony, 0);
                    //副卡，卡2
                    String otherCard = (String) m.invoke(telephony, 1);
                    return mainCard;
                } else {
                    return imei;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public static void downloadFile(String url, IDownloadListener listener) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = FileUtils.getDownloadFilePath();
                try {
                    ResponseBody body = response.body();
                    if (body != null) {
                        is = body.byteStream();
                        long total = body.contentLength();
                        listener.onDownloadStart(total);
                        File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            listener.onProgressChanged(sum);
                        }
                        fos.flush();
                        listener.onDownloadEnd(file);
                    } else {
                        Log.d(TAG, "onResponse: body is null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
