package com.rehome.bhdxj.activity;

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.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.azhon.appupdate.manager.DownloadManager;
import com.rehome.bhdxj.R;
import com.rehome.bhdxj.activity.sbxdj.MainSbxdjglActivity;
import com.rehome.bhdxj.activity.sbxj.XscbglActivity;
import com.rehome.bhdxj.adapter.GridViewAdapter;
import com.rehome.bhdxj.base.BaseActivity3;
import com.rehome.bhdxj.bean.ApkUpdateBean;
import com.rehome.bhdxj.bean.GridViewBean;
import com.rehome.bhdxj.bleUtil.BlueTestInfoActivity;
import com.rehome.bhdxj.bleUtil.BluetoothLeService;
import com.rehome.bhdxj.contans.Contans;
import com.rehome.bhdxj.utils.AppManager;
import com.rehome.bhdxj.utils.GsonUtils;
import com.rehome.bhdxj.utils.HttpListener;
import com.rehome.bhdxj.utils.MqttSSLPublishServer;
import com.rehome.bhdxj.utils.NetworkUtil;
import com.rehome.bhdxj.utils.NohttpUtils;
import com.rehome.bhdxj.utils.OAToolbar;
import com.rehome.bhdxj.utils.SPUtils;
import com.rehome.bhdxj.utils.StatusBarUtil;
import com.rehome.bhdxj.weight.toastviewbymyself;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity3 {

    OAToolbar toolbar;
    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};
    private int[] colors = {R.drawable.radius_a1, R.drawable.radius_e3, R.drawable.radius_a4, R.drawable.radius_b1, R.drawable.radius_d1};
    private List<Integer> item;
    private long exitTime = 0;
    private BluetoothLeService mBluetoothLeService;

    MqttSSLPublishServer mqttPublishServer;
    //定时器
    private Timer timer;


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

    @Override
    public void initView() {
        toolbar = findViewById(R.id.toolbar);
        gv = findViewById(R.id.gv);
        toolbar.setBackgroundColor(Color.parseColor("#00000000"));
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//设置透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//设置透明导航栏
        StatusBarUtil.transparencyBar(MainActivity.this);//设置透明状态栏

        if (NetworkUtil.canNetWorkConnect(context)) {
            Log.i("app", "有网络");
        } else {
            Log.i("app", "无网络");
        }
        if(NetworkUtil.canNetWorkConnect(context)&& NetworkUtil.isISPNetWorkConnect(context)){
            Log.i("app", "运营商网络");
            initMqtt();
        }
        if(NetworkUtil.canNetWorkConnect(context)&& NetworkUtil.isWifiNetWorkConnect(context)){
            Log.i("app", "wifi网络");
        }
    }

    @Override
    public void initData() {
        setAdapter();
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        showLog("onRestart");
        checkUpdateApk();
        //检查登录是否已过期
        boolean canOfflineLogin = checkLoginDateNoExpire();
        if (!canOfflineLogin) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            showToast("离线登录有效期只有7天，离线自动登录已失效,请连接wifi后重新登录");
            finish();
        }
    }

    private boolean checkLoginDateNoExpire() {
        String lastLoginDate = (String) SPUtils.get(MainActivity.this, Contans.LASTLOGINDATE, "");
        if (!TextUtils.isEmpty(lastLoginDate)) {
            try {
                //格式化日期的对象(转化成习惯的时间格式)
                SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy年MM月dd日");
                Date date = sdFormat.parse(lastLoginDate);
                Calendar calendarLastLogin = Calendar.getInstance();
                if(date!=null){
                    calendarLastLogin.setTime(date);
                    if (!Calendar.getInstance().after(calendarLastLogin)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    private void setAdapter() {
        item = new ArrayList<>();
        item.addAll(PermissionsResult());
        beanList.addAll(getGridViewData(false));
        gv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridViewAdapter(this, beanList, item, false);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener((parent, view, position, id) -> {
            if (position == 0) {
                startActivity(MainSbxdjglActivity.class);
            } else if (position == 1) {
                startActivity(XscbglActivity.class);
            } else if (position == 2) {
                startActivity(NfcinfoActivity.class);
            } else if (position == 3) {
                startActivity(BlueTestInfoActivity.class);
            } else if (position == 4) {
                startActivity(QxgdActivity.class);
            }
        });
    }

    private List<Integer> PermissionsResult() {
        List<Integer> item = new ArrayList<>();
        item.add(0);
        item.add(1);
        item.add(2);
        item.add(3);
        item.add(4);
        try {
            String result = (String) SPUtils.get(context, Contans.PERMISSIONSRESULT, "");
        } catch (Exception e) {
        }
        return item;
    }

    private List<GridViewBean> getGridViewData(boolean isTask) {

        List<GridViewBean> datas = new ArrayList<>();
        for (int i = 0; i < str.length; i++) {
            GridViewBean bean = new GridViewBean();
            bean.setTitle(str[i]);
            bean.setBackgroup(colors[i]);
            bean.setImageid(imageId[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 onResume() {
        super.onResume();
        if(NetworkUtil.canNetWorkConnect(context)&&NetworkUtil.isISPNetWorkConnect(context)){
            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() {
        super.onDestroy();
        mBluetoothLeService.disconnect();
        mBluetoothLeService.close();
        unbindService(mServiceConnection);
        Intent intent = new Intent(this, BluetoothLeService.class);
        stopService(intent);
        if(mqttPublishServer!=null){
            mqttPublishServer.destroyAll();
            mqttPublishServer=null;
        }
        if(timer!=null){
            timer.cancel();
        }
    }

    //获取运行专业数据
    private void checkUpdateApk() {
        String url = Contans.IP + Contans.CHECK_UPDATA_APK;
        final Request<String> requestxs = NoHttp.createStringRequest(url, RequestMethod.GET);
        NohttpUtils.getInstance().addNoProgress(this, 0, requestxs, new HttpListener<String>() {

            @Override
            public void onSucceed(int what, Response<String> response) {

                String result = response.get();
                showLog("----------------");
                showLog(result);
                ApkUpdateBean apkUpdateBean = GsonUtils.GsonToBean(result, ApkUpdateBean.class);
                if (apkUpdateBean != null && "1".equals(apkUpdateBean.getTotal())) {
                    ApkUpdateBean.RowsBean rowsBean = apkUpdateBean.getRows().get(0);
                    String appURL = rowsBean.getApkurl();
                    String appVersionName = rowsBean.getVersionname();
                    String versioncode = rowsBean.getVersioncode();
                    String appDesc = rowsBean.getAppdesc();
                    showLog(appURL);
                    showLog(appVersionName);
                    showLog(versioncode);
                    showLog(appDesc);
                    if (appVersionName != getVersionName()) {
                        downloadAndInstall(appURL, appVersionName, appDesc, versioncode);
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {

            }
        });
    }

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

    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();
    }

    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();
        }
    }
}
