package com.ygtx.emcs.comm;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.HomeActivity;
import com.ygtx.emcs.activity.LivePreviewActivity;
import com.ygtx.emcs.activity.MainActivity;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.HttpsUtil;
import com.ygtx.emcs.util.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.xutils.http.RequestParams;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;

public abstract class BaseActivity extends AppCompatActivity {
    public final static String SCAN_ACTION = "urovo.rcv.message";
    public final static String ET_SCAN_ACTION = "android.intent.ACTION_DECODE_DATA";
    public final static String ACTION_PDA_SERVICE_SCANNER_DATA = "com.service.scanner.data";

    private  Context context;
    private SoundPoolMgr soundPoolMgr;
    public ActivityResultLauncher<Intent> intentActivityResultLauncher;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setTranslucentStatus(true);
//            SystemBarTintManager tintManager = new SystemBarTintManager(this);
//            tintManager.setStatusBarTintEnabled(true);
//            tintManager.setStatusBarTintResource(R.color.status);//通知栏所需颜色
//        }
        initResult();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        Res.init(this);
        AppManager.getAppManager().addActivity(this);
        soundPoolMgr = SoundPoolMgr.getInstance(context);
    }

    protected void initCommonTop2(){
        TextView c_common_top2_title = (TextView) findViewById(R.id.c_common_top2_title);
        if(c_common_top2_title != null){
            c_common_top2_title.setText(getCommonTopTitle());
        }

        ImageView c_iv_common_back = (ImageView) findViewById(R.id.c_iv_common_back);
        if(c_iv_common_back != null){
            c_iv_common_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    backActivity();
                }
            });
        }
    }

    /**
     * 获得顶部公共部分的标题名称
     * @return
     */
    protected abstract String getCommonTopTitle();

    /**
     * 获得顶部公共部分的图标id
     * @return
     */
    protected abstract int getCommonTopICO();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);

    }

    /**
     * 界面跳转
     *
     * @param nextActivity
     */
    public void toActivity(Class nextActivity) {
        Intent intent = new Intent(BaseActivity.this, nextActivity);
        startActivity(intent);
    }

    /**
     * 界面跳转 可传参
     *
     * @param nextActivity
     */
    public void toActivity(Class nextActivity, Bundle bundle) {
        Intent intent = new Intent(BaseActivity.this, nextActivity);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void toTopActivity(Class nextActivity, Bundle bundle){
        Intent intent = new Intent(BaseActivity.this, nextActivity);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private final static int SCANNIN_GREQUEST_CODE = 1;
    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    protected String getParamString(String key) {
        Bundle bundle = getIntent().getExtras();
        String values = "";
        if (bundle != null) {
            Object obj = bundle.get(key);
            if (obj != null) {
                values = obj.toString();
            }
        }
        return values;
    }

    protected int getParamInteger(String key) {
        Bundle bundle = getIntent().getExtras();
        int obj = 0;
        if (bundle != null) {
            obj = bundle.getInt(key);
        }
        return obj;
    }

    protected Long getParamLong(String key) {
        Bundle bundle = getIntent().getExtras();
        long obj = 0;
        if (bundle != null) {
            obj = bundle.getLong(key);
        }
        return obj;
    }

    protected Object getParamSerializable(String key) {
        try {
            Bundle bundle = getIntent().getExtras();
            Object obj = bundle.get(key);
            return obj;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    public void scrollMyListViewToBottom(final ListView listView) {
        listView.post(new Runnable() {
            @Override
            public void run() {
                // Select the last row so it will scroll into view...
                listView.setSelection(listView.getAdapter().getCount() - 1);
            }
        });
    }

    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(Integer.MAX_VALUE);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] barocode = intent.getByteArrayExtra("barocode");
            if(barocode==null){
                barocode = intent.getByteArrayExtra("barcode");
            }
            if(barocode==null){
                return;
            }
            int barocodelen = intent.getIntExtra("length", 0);
            String scanResult = new String(barocode, 0, barocodelen);
            System.out.println("=============="+scanResult);
            long t = new Date().getTime();
            long last_time = 0;
            String last_time_str = CacheService.getInstance(context).getCache("TEMP_FLAGE", "scan_time");
            String last_value = CacheService.getInstance(context).getCache("TEMP_FLAGE", "scan_value");
            if(!StringUtils.isEmpty(last_time_str)){
                last_time = Long.parseLong(last_time_str);
            }
            long lt = t - last_time;
            System.out.println("=============="+lt);
            if(scanResult.equals(last_value)
                    && lt < 500){
                return;
            }
            last_value = scanResult;
            CacheService.getInstance(context).saveCache("TEMP_FLAGE", "scan_time", String.valueOf(t));
            CacheService.getInstance(context).saveCache("TEMP_FLAGE", "scan_value", last_value);
            soundPoolMgr.play(2,0);
            process(scanResult);
        }
    };

    public BroadcastReceiver mHkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            //接收广播内容
            if (action.equals(ACTION_PDA_SERVICE_SCANNER_DATA)) {
                //条码内容
                String code = intent.getStringExtra("ScanCode");
                //ocr识别内容
                String phone = intent.getStringExtra("ScanOcrPhone");
                //条码
                String codeType = intent.getStringExtra("ScanCodeType");
                System.out.println("条码:" + code);
                process(code);
            }
        }
    };

    private void process(String barcode) {
        System.out.println("当前扫码：" + barcode);
        if (StringUtils.isEmpty(barcode)) {
            return;
        }
        BaseActivity scan = (BaseActivity)getCurrentActivity();
        scan.receiverTask(barcode);
    }

    public abstract void receiverTask(String barcode);


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);
        if(keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if(!(getCurrentActivity() instanceof LivePreviewActivity)) {
                Intent intent = new Intent(context, LivePreviewActivity.class);
                intentActivityResultLauncher.launch(intent);
            }
        }
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(getCurrentActivity() instanceof HomeActivity){
                myLogout();
            }else{
                finish();
            }
        }
        return false;
    }

    private void initResult(){
        intentActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent intent = result.getData();
                        if(intent==null){
                            return;
                        }
                        int result_code = intent.getIntExtra("result_code", 0);
                        if(result_code == Constant.REQUEST_CODE_MLKIT_SCAN_ONE) {
                            String value = intent.getStringExtra("scan_result");
                            if (!StringUtils.isEmpty(value)) {
                                soundPoolMgr.play(2, 0);
                                process(value);
                            }
                        }
                    }
                });
    }

    public static String getTopActivity(Context context) throws ClassNotFoundException {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        Log.d("测试", "pkg:"+cn.getPackageName());//包名
        Log.d("测试", "cls:"+cn.getClassName());//包名加类名
        return cn.getClassName();
    }

    public Activity getCurrentActivity () {
        try {
            String cls = getTopActivity(context);
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(
                    null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field activityField = activityRecordClass.getDeclaredField("activity");
                activityField.setAccessible(true);
                Object obj = activityField.get(activityRecord);
                if(obj==null){
                    continue;
                }
                String cls_name = obj.getClass().getName();
                if(cls_name.equals(cls)) {
                    return (Activity) activityField.get(activityRecord);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void logoutAuth(int code){
        if(code == 401){
            EventMessage message = new EventMessage(1, "退出");
            EventBus.getDefault().post(message);
            AppManager.getAppManager().finishSecActivity(HomeActivity.class);
        }
    }

    public void myLogout(){
        AlertDialog alert = new AlertDialog.Builder(BaseActivity.this)
                .setTitle("提示")
                .setMessage("确定退出系统吗?")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {// 设置确定按钮
                            @Override
                            // 处理确定按钮点击事件
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    EventMessage message = new EventMessage(1, "退出");
                                    EventBus.getDefault().post(message);
                                }catch (Exception ex){
                                    ex.printStackTrace();
                                }
                                dialog.cancel();// 对话框关闭。
                                new Handler().postDelayed(()->{finish();}, 300);
                            }
                        })
                .setNegativeButton("取消", null)
                .setCancelable(true).create();
        alert.show();
    }


    public RequestParams httParams(String url){
        return HttpsUtil.httParams(url);
    }

    public String getMac(){
        return Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    protected void backActivity(){
        finish();
    }


    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }
}
