package com.bjzc.bhzhgd.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.activity.regular.RegularActivity;
import com.bjzc.bhzhgd.activity.sbxj.XscbglActivity;
import com.bjzc.bhzhgd.activity.zhgd.DeviceListActivity;
import com.bjzc.bhzhgd.adapter.GridViewAdapter;
import com.bjzc.bhzhgd.base.BaseActivity3;
import com.bjzc.bhzhgd.base.BaseCallBackNoProgress;
import com.bjzc.bhzhgd.bean.ApkUpdateBean;
import com.bjzc.bhzhgd.bean.GridViewBean;
import com.bjzc.bhzhgd.bean.MemberCallBackBean;
import com.bjzc.bhzhgd.bleUtil.BluetoothLeService;
import com.bjzc.bhzhgd.contans.Contans;
import com.bjzc.bhzhgd.utils.AppManager;
import com.bjzc.bhzhgd.utils.FlashUtil;
import com.bjzc.bhzhgd.utils.GsonUtils;
import com.bjzc.bhzhgd.utils.HttpUtils;
import com.bjzc.bhzhgd.utils.MqttSSLPublishServer;
import com.bjzc.bhzhgd.utils.SPUtils;
import com.bjzc.bhzhgd.utils.StatusBarUtil;
import com.bjzc.bhzhgd.weight.AuditDialog;
import com.bjzc.bhzhgd.weight.toastviewbymyself;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;

public class MainActivity extends BaseActivity3 {
    Button btnLogout;
    TextView tvLoginUser;
    GridView gv;

    private List<GridViewBean> beanList = new ArrayList<>();
    private GridViewAdapter adapter;
    //    private String[] str = {"点检管理", "巡检管理", "读取NFC", "蓝牙管理", "缺陷工单提交(Maximo)", "测温", "测振"};
//    private int[] imageId = {R.mipmap.icon_dxj, R.mipmap.icon6, R.mipmap.icon11, R.mipmap.icon13, R.mipmap.icon10, R.mipmap.icon10, R.mipmap.icon10};
//    private int[] colors = {R.drawable.radius_a1, R.drawable.radius_e3, R.drawable.radius_a4, R.drawable.radius_b1, R.drawable.radius_d1, R.drawable.radius_d1, R.drawable.radius_d1};
    //private String[] str = {"运行巡检", "读取NFC", "测温", "测振"};
    private List<String> str = new ArrayList<>();
    private List<Integer> imageId = new ArrayList<>();
    private List<Integer> colors = new ArrayList<>();
    private FlashUtil flashUtil = null;
    private static final int CAMERA_REQUEST_CODE = 3;//请求码

    //private int[] imageId = {R.mipmap.icon6, R.mipmap.icon11, R.mipmap.icon_dxj, R.mipmap.icon13};
    //private int[] colors = {R.drawable.radius_e3, R.drawable.radius_a4, R.drawable.radius_a1, R.drawable.radius_b1};
    private long exitTime = 0;
    private BluetoothLeService mBluetoothLeService;
    public static final int REQUEST_CHECK_TEMPERATURE = 1;
    public static final int REQUEST_CHECK_VIBRATION = 2;
    private String userID;
    MqttSSLPublishServer mqttPublishServer;
    //定时器
    //private Timer timer;

    private LocalBroadcastManager localBroadcastManager;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Contans.ACTION__MEMBER_CALL_BACK.equals(action)) {
                Log.i("app", String.valueOf(isMainThread()));
                //刷新页面
                String callbackStr = intent.getStringExtra("callbackStr");
                if (callbackStr != null) {
                    Log.i("app", callbackStr);
                    List<MemberCallBackBean> memberCallBackList = GsonUtils.parseString2List(callbackStr, MemberCallBackBean.class);
                    if (memberCallBackList != null && memberCallBackList.size() > 0) {
                        Log.i("app", String.valueOf(memberCallBackList.size()));
                        //Log.i("app",String.valueOf(userID==null));
                        for (int i = 0; i < memberCallBackList.size(); i++) {
                            MemberCallBackBean item = memberCallBackList.get(i);
                            if (userID.equals(item.getUserId())) {
                                Log.i("app", "召回我了!");
//                                AuditDialog auditDialog = new AuditDialog(context, "确定要退出登录吗？", new AuditDialog.AuditDialogListener() {
//                                    @Override
//                                    public void confirm() {
//
//                                    }
//
//                                    @Override
//                                    public void cancel() {
//
//                                    }
//                                });
//                                auditDialog.show();
                                Intent intentTemp = new Intent(MainActivity.this, MemberCallbackDialogActivity.class);
                                intentTemp.putExtra("userId", item.getUserId());
                                intentTemp.putExtra("msg", item.getMsg());
                                intentTemp.putExtra("time", item.getTime());
                                startActivity(intentTemp);
                                MediaPlayer mMediaPlayer;
                                mMediaPlayer = MediaPlayer.create(context, R.raw.callback);
                                mMediaPlayer.start();

                                break;
                            }
                        }
                    }
                }
            }
        }
    };

    public boolean isMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    //@RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void initView() {
        btnLogout = findViewById(R.id.btn_logout);
        tvLoginUser = findViewById(R.id.tv_login_user);
        gv = findViewById(R.id.gv);

        userID = (String) SPUtils.get(MainActivity.this, Contans.USERID, "");
        flashUtil = new FlashUtil();
        toolbar.setBackgroundColor(Color.parseColor("#00000000"));
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//设置透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//设置透明导航栏
        StatusBarUtil.transparencyBar(MainActivity.this);//设置透明状态栏
        //当选择外网时才会开启一键招回
        if (Contans.IP.equals(Contans.network_type_extranet)) {
            //initMqtt();
        }
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AuditDialog auditDialog = new AuditDialog(context, "确定要退出登录吗？", new AuditDialog.AuditDialogListener() {
                    @Override
                    public void confirm() {
                        SPUtils.remove(MainActivity.this, "save");
                        SPUtils.remove(MainActivity.this, Contans.USERID);
                        SPUtils.remove(MainActivity.this, Contans.USERPWD);
                        SPUtils.remove(MainActivity.this, Contans.LOGIN_TOKEN);
                        SPUtils.remove(MainActivity.this, Contans.USERNAME);
                        SPUtils.remove(MainActivity.this, Contans.BZBH);
                        SPUtils.remove(MainActivity.this, Contans.BZMC);
                        SPUtils.remove(MainActivity.this, Contans.PERMISSIONSRESULT);
                        SPUtils.remove(MainActivity.this, Contans.ZY);
                        SPUtils.remove(MainActivity.this, Contans.NFCBM);
                        SPUtils.remove(MainActivity.this, Contans.LASTLOGINDATE);
                        SPUtils.clear(MainActivity.this);

                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void cancel() {

                    }
                });
                auditDialog.show();
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION__MEMBER_CALL_BACK);
        //registerReceiver(myReceiver, filter);
        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, filter);

    }

//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        // TODO Auto-generated method stub
//        super.onWindowFocusChanged(hasFocus);
//        try {
//            @SuppressLint("WrongConstant") Object service = getSystemService("statusbar");
//            Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
//            Method test = statusbarManager.getMethod("collapse");
//            test.invoke(service);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }

    @Override
    public void initData() {
        //checkUpdateApk();
        //List<String> permissionsResult = this.getPermissionsResult();
//        Log.i("app","---------");
//        Log.i("app",new Gson().toJson(permissionsResult));


        str.add("二级电箱");
        imageId.add(R.mipmap.icon11);
        colors.add(R.drawable.radius_c6);

        str.add("工作台");
        imageId.add(R.mipmap.icon10);
        colors.add(R.drawable.radius_e3);


//        str.add("燃料巡检");
//        imageId.add(R.mipmap.icon10);
//        colors.add(R.drawable.radius_b2);
//
//
//        str.add("保安巡检");
//        imageId.add(R.mipmap.icon8);
//        colors.add(R.drawable.radius_e2);


//        str.add("读取NFC");
//        imageId.add(R.mipmap.icon3);
//        colors.add(R.drawable.radius_a4);
//
//        str.add("测温");
//        str.add("测振");
//        imageId.add(R.mipmap.icon_xs1);
//        imageId.add(R.mipmap.icon13);
//        colors.add(R.drawable.radius_a1);
//        colors.add(R.drawable.radius_b1);



        setAdapter();
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        String username = (String) SPUtils.get(MainActivity.this, Contans.USERNAME, String.valueOf(""));
        if (username != null) {
            tvLoginUser.setText("登录用户：" + username);
        }
    }

    private void checkPermission() {
        /**
         * 检测 设备是否支持闪光灯
         */
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            showToast("设备没有闪光灯，无法开启手电筒");
            return;
        }

        //动态权限申请
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //权限请求
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE);
        } else {
            flashUtil.toggle(MainActivity.this);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (CAMERA_REQUEST_CODE == requestCode) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                flashUtil.toggle(MainActivity.this);
            } else {
                //权限拒绝
                Toast.makeText(this, "权限拒绝,无法打开闪光灯,请手动设置开启APP访问摄像头权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void setAdapter() {
        //item.addAll(PermissionsResult());
        beanList.addAll(getGridViewData(false));
        gv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridViewAdapter(this, beanList, new ArrayList<Integer>(), true);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener((parent, view, position, id) -> {
            GridViewAdapter.ViewHolder holder = (GridViewAdapter.ViewHolder) view.getTag();
            String iconText = (String) holder.tv.getText();
            if (iconText != null) {
                //Toast.makeText(context,iconText,Toast.LENGTH_SHORT).show();
//                str.add("运行巡检");
//                str.add("燃料巡检");
//                str.add("保安巡检");
//                str.add("读取NFC");
//                str.add("测温");
//                str.add("测振");
                if (iconText.equals("二级电箱")) {
                    Intent intentTemp = new Intent(MainActivity.this, DeviceListActivity.class);
                    intentTemp.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intentTemp.putExtra("type", "YX");
                    startActivity(intentTemp);
                } else if (iconText.equals("工作台")) {
                    Intent intentTemp = new Intent(MainActivity.this, WorkTableActivity.class);
                    intentTemp.putExtra("type", "RL");
                    startActivity(intentTemp);
                } else if (iconText.equals("运行定期工作")) {
                    Intent intentTemp = new Intent(MainActivity.this, RegularActivity.class);
                    intentTemp.putExtra("type", "YX");
                    startActivity(intentTemp);
                } else if (iconText.equals("燃料定期工作")) {
                    Intent intentTemp = new Intent(MainActivity.this, RegularActivity.class);
                    intentTemp.putExtra("type", "RL");
                    startActivity(intentTemp);
                } else if (iconText.equals("读取NFC")) {
                    startActivity(NfcinfoActivity.class);
                } else if (iconText.equals("测温")) {
                    Intent intentTemp = new Intent(MainActivity.this, CustomDialogActivity.class);
                    intentTemp.putExtra("type", "7");
                    startActivity(intentTemp);
                } else if (iconText.equals("测振")) {
                    Intent intentVibration = new Intent(MainActivity.this, CustomDialogActivity.class);
                    intentVibration.putExtra("type", "11");
                    startActivity(intentVibration);
                } else if (iconText.equals("保安巡检")) {
                    Intent intentTemp = new Intent(MainActivity.this, XscbglActivity.class);
                    intentTemp.putExtra("type", "BA");
                    startActivity(intentTemp);
                } else if (iconText.equals("手电筒")) {
                    checkPermission();
                } else if (iconText.equals("Q4工单")) {

                }
            }
        });
    }

    private List<String> getPermissionsResult() {
        List<String> item = new ArrayList<>();
        String result = (String) SPUtils.get(context, Contans.PERMISSIONSRESULT, String.valueOf(""));
        if (!result.equals("")) {
            return stringToList(result);
        }
        return item;
    }

    private List<String> stringToList(String strs) {
        String[] str = strs.split(";");
        return Arrays.asList(str);
    }

    private List<GridViewBean> getGridViewData(boolean isTask) {

        List<GridViewBean> datas = new ArrayList<>();
        for (int i = 0; i < str.size(); i++) {
            GridViewBean bean = new GridViewBean();
            bean.setTitle(str.get(i));
            bean.setBackgroup(colors.get(i));
            bean.setImageid(imageId.get(i));
            bean.setShow(false);
            if (i == 4) {
                if (isTask) {
                    bean.setShow(true);
                } else {
                    bean.setShow(false);
                }
            }
            datas.add(bean);
        }

        return datas;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                toastviewbymyself.makeText(context, "再按一次退出程序", Toast.LENGTH_LONG).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
                AppManager.getAppManager().AppExit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String temperatureValue = data.getStringExtra("value");
            if (temperatureValue != null) {
                //先判断是哪个页面返回过来的
                switch (requestCode) {
                    case REQUEST_CHECK_TEMPERATURE:
                        //测温
                        //成功了
                        Toast.makeText(MainActivity.this, temperatureValue, Toast.LENGTH_SHORT).show();
                        break;
                    case REQUEST_CHECK_VIBRATION:
                        //测振
                        //成功了
                        Toast.makeText(MainActivity.this, temperatureValue, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }


    private void checkUpdateApk() {
        HttpUtils.getApi(context).getCheckUpdataApk().enqueue(new BaseCallBackNoProgress<ApkUpdateBean>(context) {
            @Override
            public void onSuccess(Call<ApkUpdateBean> call, retrofit2.Response<ApkUpdateBean> response) {
                ApkUpdateBean appUploadInfo = response.body();
                if (appUploadInfo != null) {
                    if (appUploadInfo.getTotal().equals("1")) {
                        String appURL = appUploadInfo.getRows().get(0).getApkurl();
                        String appversionname = appUploadInfo.getRows().get(0).getVersionname();
                        String versioncode = appUploadInfo.getRows().get(0).getVersioncode();
                        String appdesc = appUploadInfo.getRows().get(0).getAppdesc();

                        if (appURL != null && appURL.contains("http://")) {
                            if (appURL.length() > 26) {
                                String baseApkUrl = appURL.substring(26);
                                appURL = Contans.IP + baseApkUrl;
                            }
                        } else {
                            appURL = Contans.IP + appURL;
                        }

                        if (!appversionname.equals(getVersionName())) {
                            DownloadAndInstall(appURL, appversionname, appdesc, versioncode);
                        }
                    }
                }
            }

            @Override
            public void onError(Call<ApkUpdateBean> call, Throwable t) {
            }
        });
    }

    private void DownloadAndInstall(String downloadURL, String versionName, String description, String versionCode) {
        new DownloadManager.Builder(this)
                .apkUrl(downloadURL)
                .apkName("云浮电厂点巡检.apk")
                .smallIcon(R.mipmap.logo1)
                .showNewerToast(false)
                .apkVersionCode(Integer.parseInt(versionCode))
                .apkVersionName(versionName)
                .apkDescription(description)
                .enableLog(true)
                .jumpInstallPage(true)
                .dialogButtonTextColor(Color.WHITE)
                .dialogButtonColor(Color.parseColor("#FF8247"))
                .dialogProgressBarColor(Color.parseColor("#FF8247"))
                .showNotification(true)
                .showBgdToast(true)
                .forcedUpgrade(true)
                .onDownloadListener(new OnDownloadListener() {
                    @Override
                    public void start() {

                    }

                    @Override
                    public void downloading(int i, int i1) {

                    }

                    @Override
                    public void done(@NonNull File file) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void error(@NonNull Throwable throwable) {

                    }
                }).onButtonClickListener(new OnButtonClickListener() {
                    @Override
                    public void onButtonClick(int i) {

                    }
                }).build().download();
    }

    private String getVersionName() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void initMqtt() {
        //开启MQTT一键招回
        mqttPublishServer = new MqttSSLPublishServer(this);
        try {
//            timer = new Timer();
//            timer.schedule(new TimerTask() {
//                public void run() {
//                    mqttPublishServer.start();
//                }
//            }, 1000, 60000);
            // 设定指定的时间time,此处为10000毫秒
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Contans.IP.equals(Contans.network_type_extranet)) {
            if (mqttPublishServer == null) {
                mqttPublishServer = new MqttSSLPublishServer(this);
            }
//            if(timer==null){
//                try {
//                    timer = new Timer();
//                    timer.schedule(new TimerTask() {
//                        public void run() {
//                            mqttPublishServer.start();
//                        }
//                    }, 1000, 60000);
//                    // 设定指定的时间time,此处为10000毫秒
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
        }
    }

    @Override
    public void onDestroy() {
        if (mBluetoothLeService != null) {
            mBluetoothLeService.disconnect();
            mBluetoothLeService.close();
        }
        unbindService(mServiceConnection);
        if (flashUtil != null) {
            flashUtil.finishFlashUtils();
        }
        if (mqttPublishServer != null) {
            mqttPublishServer.destroyAll();
            mqttPublishServer = null;
        }
//        if(timer!=null){
//            timer.cancel();
//        }
        Intent intent = new Intent(this, BluetoothLeService.class);
        stopService(intent);

        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);

        super.onDestroy();
    }

}


//XSCB/YX_XJGL.ashx
//XSCB/BA_XJGL.ashx
//XSCB/CURRENT_CHECK_LOCALTION.ashx
//XSCB/CURRENT_CHECK_LOCALTION_TXM.ashx
//XSCB/LAST_UPLOAD_POINT_CHECKED.ashx
//XSCB/LAST_UPLOAD_POINT_CHECKED_TXM.ashx
//XSCB/MY_UPLOAD.ashx
//XSCB/STATISTICS_CHECKED.ashx
