package com.example.beijing_daxing.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
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.Window;

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


import com.example.beijing_daxing.R;
import com.google.gson.Gson;
import com.handheld.uhfr.*;
import com.uhf.api.cls.Reader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;

public  class BaseActivity extends AppCompatActivity {
    public static String url = "http://192.168.137.1:8090/api";
    // public static String url = "http://119.45.202.115:8090/api";
    public ProgressDialog dialog;
    public Gson gson;
    public MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public UHFRManager uhfLongerManager;
    private MediaPlayer mediaPlayer;
    public MyReceiver myReceiver;
    public Intent broadcastIntent;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gson = new Gson();
        initDialog();
        initSan();
        broadcastIntent = new Intent("android.rfid.FUN_KEY");
        broadcastIntent.putExtra("keydown", false);
    }

    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            var keydown = intent.getBooleanExtra("keydown", false);
            Log.e("TAG", "接收到广播:" + keydown);
            if (!keydown) {
                sanEpc();
            }
        }
    }

    public void sanEpc() {
        List<Reader.TAGINFO> strings = uhfLongerManager.tagInventoryRealTime();
        if (strings == null || strings.isEmpty()) {
            return;
        }
        mediaPlayer.start();
        sanRfid(strings);
    }

    private void initDialog() {
        dialog = new ProgressDialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("请求网络...");
    }

    private void initSan() {
        uhfLongerManager = MyApplication.getApplication().getUhfrManager();
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.rfid.FUN_KEY");
        registerReceiver(myReceiver, intentFilter);
        mediaPlayer = MediaPlayer.create(this, R.raw.msg);
    }

    public void setPower(int power) {
        try {
            Reader.READER_ERR readerErr = uhfLongerManager.setPower(power, power);
            Log.e("TAG", "setPower:" + readerErr.name());
            int[] power1 = uhfLongerManager.getPower();
            Log.e("TAG", "readPower:" + power1[0] + "," + power1[1]);
        } catch (Exception e) {

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }


    public   void sanRfid(List<Reader.TAGINFO> epcs){

    };

    public static final int CAMERA_PHOTO = 0X02;
    public File outputImage;
    public Uri img_uri;
    public SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
   private boolean addWatermarkType;
   private String addWatermarkLocation;
    // 拍照
    public void takePhoto(boolean type,String location) {
        this.addWatermarkType=type;
        addWatermarkLocation=location;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }
        outputImage = new File(getExternalCacheDir(), "output_imgage" + format.format(new Date()) + ".jpg");
        try {
            outputImage.createNewFile();
        } catch (IOException e) {
            Log.e("TAG", "teke_photo:文件创建错误");
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24) {
            img_uri = FileProvider.getUriForFile(this, "com.example.beijing_daxing", 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);
        }
    }

    public void takePhotoCall(File outputImage, Bitmap bitmap) {

    }

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

        if (requestCode == CAMERA_PHOTO && resultCode == RESULT_OK) {
            Bitmap bitmap = null;
            try {
                Log.e("TAG", "onActivityResult:" + img_uri.getPath());
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(img_uri));
                if (addWatermarkType){
                    // 添加水印
                    bitmap = addWatermark(bitmap);
                }
                FileOutputStream outputStream = new FileOutputStream(outputImage);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
                takePhotoCall(outputImage, bitmap);
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    private String[] strings=new String[]{"星期日","星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
    @SuppressLint("NewApi")
    private Bitmap addWatermark(Bitmap src) {
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(30);
        paint.setTextSize(150);
        paint.setAntiAlias(true);
        // 获取当前日期
        LocalDate today = LocalDate.now(ZoneId.systemDefault());
        // 获取当前日期是周几
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        canvas.drawText("机位："+addWatermarkLocation, 10, h - 400, paint);
        canvas.drawText(dateFormat.format(new Date()), 10, h - 200, paint);
        canvas.drawText(strings[dayOfWeek.getValue()], 10, h - 20, paint);
        return result;
    }
}