package com.example.tyre.maintenance.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.android.hdhe.uhf.reader.UhfReader;
import com.example.tyre.MyApplication;
import com.example.tyre.R;
import com.example.tyre.maintenance.receiver.MyKeyInfoCall;
import com.example.tyre.maintenance.receiver.MyKeyReceiver;
import com.example.tyre.util.MyUrl;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.pda.serialport.Tools;
import okhttp3.MediaType;

public class BaseActivity extends AppCompatActivity {
    public static final int CAMERA_PHOTO = 1;
    public SimpleDateFormat dateFormat;
    public ProgressDialog dialog;
    public Context context;
    public Gson gson;
    public String url;
    public MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public byte[] accessBytes = Tools.HexString2Bytes("00000000");
    @SuppressLint("SimpleDateFormat")
    public SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
    public UhfReader uhfReader;
    public MediaPlayer music;
    public MyKeyReceiver keyReceiver;
    // 拍照
    private Uri img_uri;
    private File outputImage;

    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        gson = new Gson();
        initDialog();
        url = MyUrl.url;
    }

    public void onBackClick(View view) {
        finish();
    }

    private void initDialog() {
        dialog = new ProgressDialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("loading...");
    }

    public int getDeptId(String name) {
        if (name.equals("光明修理厂")) {
            return 200;
        } else if (name.equals("石岩修理厂")) {
            return 201;
        }else if (name.equals("运维部门")) {
            return 107;
        }
        return 229;
    }

    public String getTypeCode(String typeName) {
        if (typeName.equals("二级保养")) {
            return "1";
        } else if (typeName.equals("抢碎修")) {
            return "2";
        } else if (typeName.equals("拆报废车")) {
            return "3";
        } else if (typeName.equals("月检")) {
            return "4";
        } else if (typeName.equals("小修")) {
            return "5";
        } else if (typeName.equals("轮胎修补")) {
            return "6";
        }
        return "7";


    }

    public void teke_photo() throws IOException {
        outputImage = new File(getExternalCacheDir(), "output_imgage" + format.format(new Date()) + ".jpg");
        outputImage.createNewFile();
        if (Build.VERSION.SDK_INT >= 24) {
            img_uri = FileProvider.getUriForFile(this, "com.example.tyre", outputImage);
        } else {
            img_uri = Uri.fromFile(outputImage);
        }
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, img_uri);
            startActivityForResult(intent, CAMERA_PHOTO);
        } else {
            // 提示用户开户权限   拍照和读写sd卡权限
            String[] perms =
                    {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
            ActivityCompat.requestPermissions(this, perms, CAMERA_PHOTO);
        }
    }

    // 拍照的回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

   /*         Bitmap compressedImageBitmap = BitmapFactory.decodeFile(outputImage.getPath());
            // 选择压缩质量
            int quality = 10;
            // 创建一个字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 将Bitmap压缩成JPEG格式，并将压缩后的数据保存到字节数组输出流中
            compressedImageBitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            // 将字节数组输出流中的数据转换为字节数组
            byte[] compressedImageData = baos.toByteArray();
            // 清空字节数组输出流
            baos.reset();
            // 将压缩后的字节数组保存到文件中
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputImage);
                fos.write(compressedImageData);
                fos.flush();
                fos.close();*/
            if (requestCode == CAMERA_PHOTO) {
                tekePhotoResult(img_uri.toString(), outputImage);
            }

          /*  } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }*/

        }
    }

    public void tekePhotoResult(String fileUrl, File file) {

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            boolean isKeyboardShown =
                    v != null && (v instanceof EditText) && isKeyboardShowing(getCurrentFocus(), this);
            if (isKeyboardShown) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
                    hideSoftKeyboard(this);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }

    private boolean isKeyboardShowing(View v, Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isAcceptingText();
    }

    public void initRFID() {
        uhfReader = MyApplication.getManager();
        music = MediaPlayer.create(this, R.raw.msg);
    }

    public void initRFIDAndKeyReceiver() {
        initRFID();
        initKeyRecriver(this::readEPC);
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public void initKeyRecriver(MyKeyInfoCall call) {
        keyReceiver = new MyKeyReceiver(call);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.rfid.FUN_KEY");
        filter.addAction("android.intent.action.FUN_KEY");
        registerReceiver(keyReceiver, filter);
    }


    // 扫描epc
    protected void readEPC() {
        var tagModels = uhfReader.inventoryRealTime();
        if (tagModels == null || tagModels.isEmpty()) {
            Toast.makeText(context, "读取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        // tagModels.forEach(t-> {
        //     byte[] bytes = t.getmEpcBytes();
        //     var epc = Tools.Bytes2HexString(bytes, bytes.length);
        //
        //     Log.e("TAG", "读取到: "+epc);
        // });
        byte[] bytes = tagModels.get(0).getmEpcBytes();
        // uhfReader.selectEPC(epcBytes);// 选择epc
        //
        // byte[] bytes = uhfReader.readFrom6C(1, 2, 4, accessBytes);
        if (bytes == null || bytes.length == 0) {
            // Toast.makeText(context, "读取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        music.start();
        var epc = Tools.Bytes2HexString(bytes, bytes.length);
        Log.e("TAG", "onkeyDown:" + epc);
        sanEpcCall(epc);
    }

    // 扫描epc返回
    public void sanEpcCall(String epc) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (keyReceiver != null) {
                unregisterReceiver(keyReceiver);
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}
