package com.bjzc.zjyxdxj.activity;

import static com.bjzc.zjyxdxj.utils.GsonUtils.GsonToBean;
import static org.litepal.crud.DataSupport.where;

import android.Manifest;
import android.content.ComponentName;
import android.content.ContentValues;
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.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.zjyxdxj.DBModel.XSJJHDataBean;
import com.bjzc.zjyxdxj.DBModel.XSJJHXZBean;
import com.bjzc.zjyxdxj.DBModel.XSJJHXZDataBean;
import com.bjzc.zjyxdxj.DBModel.Xjjh;
import com.bjzc.zjyxdxj.DBModel.XjjhList;
import com.bjzc.zjyxdxj.R;
import com.bjzc.zjyxdxj.activity.regular.RegularActivity;
import com.bjzc.zjyxdxj.activity.sbxj.XscbglActivity;
import com.bjzc.zjyxdxj.adapter.GridViewAdapter;
import com.bjzc.zjyxdxj.base.BaseActivity3;
import com.bjzc.zjyxdxj.base.BaseCallBackNoProgress;
import com.bjzc.zjyxdxj.bean.ApkUpdateBean;
import com.bjzc.zjyxdxj.bean.GridViewBean;
import com.bjzc.zjyxdxj.bean.ScxjjhBean;
import com.bjzc.zjyxdxj.bean.StatusInfo2;
import com.bjzc.zjyxdxj.bean.XsRequestInfo;
import com.bjzc.zjyxdxj.bleUtil.BluetoothLeService;
import com.bjzc.zjyxdxj.contans.Contans;
import com.bjzc.zjyxdxj.utils.AppManager;
import com.bjzc.zjyxdxj.utils.FlashUtil;
import com.bjzc.zjyxdxj.utils.GsonUtils;
import com.bjzc.zjyxdxj.utils.HttpListener;
import com.bjzc.zjyxdxj.utils.HttpUtils;
import com.bjzc.zjyxdxj.utils.MqttSSLPublishServer;
import com.bjzc.zjyxdxj.utils.NetworkUtil;
import com.bjzc.zjyxdxj.utils.NoProgresshttpUtils;
import com.bjzc.zjyxdxj.utils.RSAUtils;
import com.bjzc.zjyxdxj.utils.SPUtils;
import com.bjzc.zjyxdxj.utils.StatusBarUtil;
import com.bjzc.zjyxdxj.utils.UiUtlis;
import com.bjzc.zjyxdxj.weight.AuditDialog;
import com.bjzc.zjyxdxj.weight.toastviewbymyself;
import com.google.gson.Gson;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
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.Arrays;
import java.util.Calendar;
import java.util.Date;
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 List<Xjjh> dbxjjh = new ArrayList<>();
    static int needUploadCount = 0;
    private RequestQueue queue;

    private String username;

    //    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;

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


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

    //@RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void initView() {
        String UserIDTemp = (String) SPUtils.get(context, Contans.USERID, "");
        username = RSAUtils.decryptBASE64StrLocal(UserIDTemp);
        queue = NoHttp.newRequestQueue(1);

        showLog("MainActivity");

        btnLogout = findViewById(R.id.btn_logout);
        tvLoginUser = findViewById(R.id.tv_login_user);
        gv = findViewById(R.id.gv);

        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();
        }
        initAutoUploadTimer();
        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, Contans.USERID);
                        SPUtils.remove(MainActivity.this, Contans.USERPWD);
                        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.LASTLOGINDATE);
                        SPUtils.remove(MainActivity.this, Contans.REQUEST_ID);
                        SPUtils.remove(MainActivity.this, Contans.LOGIN_TOKEN);

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

                    @Override
                    public void cancel() {

                    }
                });
                auditDialog.show();
            }
        });
        //LocalBroadcastManager.getInstance(context).sendBroadcast(intent);(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 (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);
                    Intent intentTemp = new Intent(MainActivity.this, XscbglActivity.class);
                    intentTemp.putExtra("type", "BA");
                    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
    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();
                }
            }
            if (timerUpload == null) {
                try {
                    timerUpload = new Timer();
                    timerUpload.schedule(new TimerTask() {
                        public void run() {
                            autoUpload();
                            deleteOldPlanData();
                        }
                    }, 30000, 30000);
                    // 设定指定的时间time,此处为30秒
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @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推送服务
        if (mqttPublishServer != null) {
            mqttPublishServer.destroyAll();
            mqttPublishServer = null;
        }
        if (timer != null) {
            timer.cancel();
        }
        if (timerUpload != null) {
            timerUpload.cancel();
        }
        super.onDestroy();
    }

    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() != null && 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://")) {
                            int startIndex = appURL.indexOf("Apps");
                            if (startIndex != -1) {
                                String baseApkUrl = appURL.substring(startIndex);
                                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(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一键招回
        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();
        }
    }

    //自动上传定时器初始化
    public void initAutoUploadTimer() {

        try {
            timerUpload = new Timer();
            timerUpload.schedule(new TimerTask() {
                public void run() {
                    autoUpload();
                    deleteOldPlanData();
                }
            }, 30000, 30000);
            // 设定指定的时间time,此处为10000毫秒
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void autoUpload() {
        if (NetworkUtil.hasNetWorkStatus(context, false)) {
            showLog("有wifi网络");
            //检查是否有数据需要上传
            checkNeedUpload();
        } else {
            showLog("无网络");
        }
    }

    //检查是否有数据需要上传
    public void checkNeedUpload() {
        needUploadCount = 0;
        dbxjjh.clear();
        dbxjjh.addAll(where("download = ? and mk = ?  and username = ?", "1", "BA", username).find(Xjjh.class));
        if (dbxjjh.size() > 0) {
            for (int i = 0; i < dbxjjh.size(); i++) {
                Xjjh dataBean = dbxjjh.get(i);
                List<XSJJHXZDataBean> qydDataBeen = DataSupport.where("zxid = ?  and username = ?", dataBean.getZxid(), username).find(XSJJHXZDataBean.class);
                if (qydDataBeen != null && qydDataBeen.size() > 0) {
                    for (int j = 0; j < qydDataBeen.size(); j++) {
                        if (qydDataBeen.get(j).isBAChecked()) {
                            needUploadCount++;
                        }
                    }
                }

            }
        }
        //有需要上传的数据
        if (needUploadCount > 0) {
            autoUploadDataByBa();
        }
    }

    public void autoUploadDataByBa() {
        if (dbxjjh.size() > 0) {
            String idTemp = (String) SPUtils.get(context, Contans.REQUEST_ID, "");
            String id = RSAUtils.decryptBASE64StrLocal(idTemp);

            for (int i = 0; i < dbxjjh.size(); i++) {
                Xjjh dataBean = dbxjjh.get(i);
                String zxid = dataBean.getZxid();
                List<XSJJHXZDataBean> qydDataBeen = DataSupport.where("zxid = ?  and username = ?", zxid, username).find(XSJJHXZDataBean.class);

                ScxjjhBean scxjjhbean = new ScxjjhBean();
                scxjjhbean.setAction("BA_XJGL_RWSC_SET");
                scxjjhbean.setId(id);
                scxjjhbean.setQZWC(0);
                scxjjhbean.setZxid(zxid);
                List<ScxjjhBean.data> datalist = new ArrayList<>();

                if (qydDataBeen != null && qydDataBeen.size() > 0) {
                    for (int j = 0; j < qydDataBeen.size(); j++) {
                        if (qydDataBeen.get(j).isBAChecked()) {
                            XSJJHXZDataBean xsjjhdatabeanItem = qydDataBeen.get(j);

                            ScxjjhBean.data datas = new ScxjjhBean.data();
                            datas.setScid(xsjjhdatabeanItem.getScid());
                            datas.setDbh(xsjjhdatabeanItem.getQybh());
                            if (xsjjhdatabeanItem.isBAChecked()) {
                                datas.setCbsz("已检");
                            } else {
                                datas.setCbsz("");
                            }
                            if (xsjjhdatabeanItem.getDATE() == null) {
                                datas.setDjsj("");
                            } else {
                                datas.setDjsj(xsjjhdatabeanItem.getDATE());
                            }
                            datas.setZcmc((String) SPUtils.get(context, Contans.BZBH, ""));
                            datas.setCbr(username);
                            if (xsjjhdatabeanItem.getFxnr() == null) {
                                datas.setFxnr("");
                            } else {
                                datas.setFxnr(xsjjhdatabeanItem.getFxnr());
                            }
                            if (xsjjhdatabeanItem.getSmfs() != null) {
                                datas.setSmfx(xsjjhdatabeanItem.getSmfs());
                            } else {
                                datas.setSmfx("");
                            }
                            if (xsjjhdatabeanItem.getDjsj() == null) {
                                datas.setDjsj("");
                            } else {
                                datas.setDjsj(xsjjhdatabeanItem.getDjsj());
                            }
                            datalist.add(datas);
                        }
                    }
                    scxjjhbean.setData(datalist);
                }
                if (datalist.size() > 0) {
                    //上传数据
                    String json = GsonUtils.GsonString(scxjjhbean);
                    sCDataBA(json, zxid, scxjjhbean);
                }
            }
        }
    }

    //上传保安单条计划下的已检任务的数据
    private void sCDataBA(String json, String zxid, ScxjjhBean scxjjhbean) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.XSCB_PLAN_BA_UPLOAD, RequestMethod.POST);
        request.setDefineRequestBodyForJson(json);

        String tokenTemp = (String) SPUtils.get(this, Contans.LOGIN_TOKEN, "");
        if (!TextUtils.isEmpty(tokenTemp)) {
            String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);
            ;
            String credential = "Bearer " + token;
            request.addHeader("Authorization", credential);
            showLog(request.url());
            //showLog(credential);
            //showLog(new Gson().toJson(request.headers()));
        }

        queue.add(2, request, new OnResponseListener<String>() {
            @Override
            public void onStart(int what) {
            }

            @Override
            public void onSucceed(int what, Response<String> response) {
                String result = response.get();
                showLog(result);
                StatusInfo2 info = GsonUtils.GsonToBean(result, StatusInfo2.class);
                try {
                    if (what == 2) {
                        if (info.getState() == 1) { //成功
                            for (ScxjjhBean.data item : scxjjhbean.getData()) {
                                DataSupport.deleteAll(XSJJHXZDataBean.class, "zxid = ?  and username = ? and scid = ?", zxid, username, item.getScid());
                                //刷新计划下载界面
                                Intent intent = new Intent(Contans.ACTION_DELETE_REFRESHPLANDOWNLOAD);
                                //发送广播,刷新任务下载页面
                                LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                                updatePlanData();
                            }
                            //检查是否需要删除计划
                            checkNeedDeletePlan(zxid);
                        }
                    }
                } catch (Exception e) {
                    showLog(UiUtlis.getString(context, R.string.data_error));
                }
            }

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

            }

            @Override
            public void onFinish(int what) {

            }
        });
    }

    //检查是否需要删除计划
    private void checkNeedDeletePlan(String zxid) {
        List<XSJJHXZDataBean> qydDataBeen = DataSupport.where("zxid = ?  and username = ?", zxid, username).find(XSJJHXZDataBean.class);
        if (qydDataBeen != null && qydDataBeen.size() == 0) {
            DataSupport.deleteAll(Xjjh.class, "download = 1 and username = ? and zxid = ?", username, zxid);
        }
    }

    private String createJsonBA() {
        String idTemp = (String) SPUtils.get(context, Contans.REQUEST_ID, "");
        String id = RSAUtils.decryptBASE64StrLocal(idTemp);

        XsRequestInfo info = new XsRequestInfo();
        info.setAction("BA_XJGL_RWLB_GET");
        info.setId(id);
        String json = GsonUtils.GsonString(info);
        //Log.i("app", json);
        return json;
    }


    private void updatePlanData() {    //下载巡检数据

        Request<String> requestxs = NoHttp.createStringRequest(Contans.IP + Contans.BAXJ, RequestMethod.POST);
        requestxs.setDefineRequestBodyForJson(createJsonBA());
        NoProgresshttpUtils.getInstance().add(this, 0, requestxs, new HttpListener<String>() {

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

                String result = response.get();
                showLog("----------------");
                showLog(result);
                XjjhList list = GsonToBean(result, XjjhList.class);

                if (list != null) {
                    if (list.getState().equals("1")) {
                        List<Xjjh> xjjhs = list.getData();//服务器数据
                        if (xjjhs != null && xjjhs.size() > 0) {
                            for (int i = 0; i < list.getData().size(); i++) {
                                Xjjh xjjh = list.getData().get(i);
                                showLog(new Gson().toJson(xjjh));
                            }

                            //DataSupport.deleteAll(Xjjh.class, "download = 1 and username = ?", username);
                            for (Xjjh xjjh : xjjhs) {
                                List<Xjjh> dbxjjh = DataSupport.where("zxid = ? and download = ?  and username = ?", xjjh.getZxid(), "1", username).find(Xjjh.class);
                                if (dbxjjh.size() > 0) {
                                    ContentValues values = new ContentValues();
                                    values.put("jhds", xjjh.getJhds());
                                    DataSupport.updateAll(Xjjh.class, values, "zxid = ?", xjjh.getZxid());
                                }
                            }
                            //刷新计划下载界面
                            Intent intent = new Intent(Contans.ACTION_REFRESHPLANDOWNLOAD);
                            //发送广播,刷新任务下载页面
                            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                        }
                    }
                }
            }

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

            }
        });
    }

    private void deleteOldPlanData() {
        try {
            //格式化日期的对象(转化成习惯的时间格式)
            SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdFormatDay = new SimpleDateFormat("yyyy/MM/dd");

            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -3);
            //输出当前系统时间;
            //showLog(sdFormat.format(calendar.getTime()));

            List<Xjjh> dbxjjh = DataSupport.where("download = ? and username = ?", "1", username).find(Xjjh.class);
            if (dbxjjh.size() > 0) {
                for (Xjjh xjjh : dbxjjh) {
                    Date date = sdFormat.parse(xjjh.getSt());
                    Calendar calendarOne = Calendar.getInstance();
                    calendarOne.setTime(date);
                    if (calendarOne.before(calendar)) {
                        DataSupport.deleteAll(XSJJHXZDataBean.class, "zxid = ? and username = ?", xjjh.getZxid(), username);
                        DataSupport.deleteAll(Xjjh.class, "download = 1 and zxid = ? and username = ?", xjjh.getZxid(), username);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
