package com.rehome.sgbaxj.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
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.os.Build;
import android.os.IBinder;
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 com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.rehome.sgbaxj.R;
import com.rehome.sgbaxj.activity.regular.RegularActivity;
import com.rehome.sgbaxj.activity.sbxj.XscbglActivity;
import com.rehome.sgbaxj.adapter.GridViewAdapter;
import com.rehome.sgbaxj.base.BaseActivity3;
import com.rehome.sgbaxj.base.BaseCallBackNoProgress;
import com.rehome.sgbaxj.bean.ApkUpdateBean;
import com.rehome.sgbaxj.bean.GridViewBean;
import com.rehome.sgbaxj.bleUtil.BluetoothLeService;
import com.rehome.sgbaxj.contans.Contans;
import com.rehome.sgbaxj.service.MQTTPushService;
import com.rehome.sgbaxj.utils.AppManager;
import com.rehome.sgbaxj.utils.FlashUtil;
import com.rehome.sgbaxj.utils.HttpUtils;
import com.rehome.sgbaxj.utils.SPUtils;
import com.rehome.sgbaxj.utils.StatusBarUtil;
import com.rehome.sgbaxj.weight.AuditDialog;
import com.rehome.sgbaxj.weight.toastviewbymyself;
import com.google.gson.Gson;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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 com.azhon.appupdate.manager.DownloadManager manager;
    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;


    @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);

        //initMqtt();
        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);//设置透明状态栏
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AuditDialog auditDialog = new AuditDialog(context, "确定要退出登录吗？", new AuditDialog.AuditDialogListener() {
                    @Override
                    public void confirm() {
                        SPUtils.clear(MainActivity.this);
                        SPUtils.remove(MainActivity.this, Contans.LASTLOGINDATE);
                        SPUtils.remove(MainActivity.this,Contans.USERID);
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void cancel() {

                    }
                });
                auditDialog.show();
            }
        });
        //sendBroadcast(new Intent("android.intent.action.STATUSBAR_DISABLE"));
    }

    @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() {
        String nfc = (String) SPUtils.get(context, Contans.NFCBM, "");
        Log.i("app","nfc:---------");
        Log.i("app",String.valueOf(nfc.equals("")));

        checkUpdateApk();
        List<String> permissionsResult=this.getPermissionsResult();
        Log.i("app","---------");
        Log.i("app",new Gson().toJson(permissionsResult));
        boolean isApp_YXXJ = false;
        boolean isApp_RLXJ = false;
        for (String permissions : permissionsResult) {
            if(permissions.equals("App_YXXJ")){
                str.add("运行巡检");
                imageId.add(R.mipmap.icon6);
                colors.add(R.drawable.radius_e3);
                isApp_YXXJ = true;
            }
            if(permissions.equals("App_RLXJ")){
                str.add("燃料巡检");
                imageId.add(R.mipmap.icon10);
                colors.add(R.drawable.radius_b2);
                isApp_RLXJ = true;
            }
            if(permissions.equals("App_BAXJ")){
                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("手电筒");
//        imageId.add(R.mipmap.icon11);
//        colors.add(R.drawable.radius_c7);

        //private int[] imageId = {R.mipmap.icon6, R.mipmap.icon11, R.mipmap.icon_dxj, R.mipmap.icon13};


//        imageId.add(R.mipmap.icon6);
//        imageId.add(R.mipmap.icon10);



        //private int[] colors = {R.drawable.radius_e3, R.drawable.radius_a4, R.drawable.radius_a1, R.drawable.radius_b1};


//        colors.add(R.drawable.radius_c7);
//        colors.add(R.drawable.radius_c6);




        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 (Build.VERSION.SDK_INT <Build.VERSION_CODES.M) {
            flashUtil.toggle(MainActivity.this);
        }else {
            //动态权限申请
            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);
            }
//            //检查权限是否授予
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED) {
//                //权限请求
//                requestPermissions(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, XscbglActivity.class);
                    intentTemp.putExtra("type","YX");
                    startActivity(intentTemp);
                }else if(iconText.equals("燃料巡检")){
                    Intent intentTemp=new Intent(MainActivity.this, XscbglActivity.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;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        mBluetoothLeService.disconnect();
        mBluetoothLeService.close();
        unbindService(mServiceConnection);
        if(flashUtil!=null){
            flashUtil.finishFlashUtils();
        }
        Intent intent = new Intent(this, BluetoothLeService.class);
        stopService(intent);
        //停止MQTT推送服务
        Intent intentMqtt = new Intent(MainActivity.this, MQTTPushService.class);
        stopService(intentMqtt);
        super.onDestroy();
    }

    private void checkUpdateApk() {
        HttpUtils.getApi().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 (!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(true)
                .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推送服务
            Intent intent = new Intent(MainActivity.this, MQTTPushService.class);
            startService(intent);
    }
}
