package com.example.administrator.zhapp.activity;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import com.azhon.appupdate.listener.OnButtonClickListener;
import com.azhon.appupdate.listener.OnDownloadListener;
import com.example.administrator.zhapp.DBModel.AjhScInfo;
import com.example.administrator.zhapp.DBModel.Ajhjh;
import com.example.administrator.zhapp.DBModel.Ajhxcjs;
import com.example.administrator.zhapp.DBModel.Ajhxzrwqy;
import com.example.administrator.zhapp.DBModel.Djjh;
import com.example.administrator.zhapp.DBModel.DjjhRwQy;
import com.example.administrator.zhapp.DBModel.LyXcjsInfo;
import com.example.administrator.zhapp.DBModel.LyYhpcInfo;
import com.example.administrator.zhapp.DBModel.LyxcXm;
import com.example.administrator.zhapp.DBModel.LyxcXmJg;
import com.example.administrator.zhapp.DBModel.Lyxcrwqy;
import com.example.administrator.zhapp.DBModel.QxgdInfo;
import com.example.administrator.zhapp.DBModel.XcjsInfo;
import com.example.administrator.zhapp.DBModel.XfBaxcRwqy;
import com.example.administrator.zhapp.DBModel.XfDjjh;
import com.example.administrator.zhapp.DBModel.XfDjjhRwqy;
import com.example.administrator.zhapp.DBModel.XfXcjsInfo;
import com.example.administrator.zhapp.DBModel.XfXcmhqc;
import com.example.administrator.zhapp.DBModel.XfXcxm;
import com.example.administrator.zhapp.DBModel.XfXcxmjg;
import com.example.administrator.zhapp.DBModel.XwaqgcJh;
import com.example.administrator.zhapp.DBModel.XwaqgcJs;
import com.example.administrator.zhapp.DBModel.XwaqgcSc;
import com.example.administrator.zhapp.DBModel.YhpcInfo;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.ajhxcgl.AjhxcglActivity;
import com.example.administrator.zhapp.activity.dqgzgl.dqgzglActivity;
import com.example.administrator.zhapp.activity.sbxdjgl.SbxdjglActivity;
import com.example.administrator.zhapp.activity.sbxdjgl.XwangcMainActivity;
import com.example.administrator.zhapp.activity.xfbwxcgl.XfbwxcglActivity;
import com.example.administrator.zhapp.activity.xscbgl.XscbglActivity;
import com.example.administrator.zhapp.activity.ydckgl.YdckglActivity;
import com.example.administrator.zhapp.adapter.GridViewAdapter;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.ApkUpdateBean;
import com.example.administrator.zhapp.entity.BasicDataBean;
import com.example.administrator.zhapp.entity.BasicDataBean2;
import com.example.administrator.zhapp.entity.GridViewBean;
import com.example.administrator.zhapp.entity.PushInfo;
import com.example.administrator.zhapp.entity.XsRequestInfo;
import com.example.administrator.zhapp.service.PushService;
import com.example.administrator.zhapp.service.UploadDataService;
import com.example.administrator.zhapp.utils.ControllerActivity;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.HttpUtils;
import com.example.administrator.zhapp.utils.NetworkAvailableUtils;
import com.example.administrator.zhapp.utils.NohttpUtils;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.AuditDialog;
import com.example.administrator.zhapp.weight.ListDialog;
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.util.ArrayList;
import java.util.List;

import retrofit2.Call;


public class MainActivity extends BaseActivity {

    GridView gv;
    ImageView tv_login;
    private List<GridViewBean> beanList = new ArrayList<>();
    private GridViewAdapter adapter;
    private PushInfo.Push push;
    private MsgReceiver msgReceiver;
    private List<BasicDataBean.DataBean> zys;
    private List<BasicDataBean2.DataBean> zys2;
    private List<String> dialogDatas;
    private List<String> dialogDatas2;
    private long downloadId;
    private boolean isTask = false;//是否有任务
    private long exitTime = 0;
    private String[] str = {"设备巡点检", "移动仓库", "安健环巡查", "综合巡查", "行为安全观察", "工单录入", "巡视抄表", "定期工作"};
    private int[] imageId = {R.mipmap.icon8,
            R.mipmap.icon9,
            R.mipmap.icon10,
            R.mipmap.icon12,
            R.mipmap.icon14,
            R.mipmap.icon13,
            R.mipmap.icon6, R.mipmap.dingqi
    };
    private int[] colors = {R.drawable.radius_a1, R.drawable.radius_a2,
            R.drawable.radius_a3, R.drawable.radius_a4,
            R.drawable.radius_d3, R.drawable.radius_c5, R.drawable.radius_e3, R.drawable.radius_a1};
    private List<Integer> item;

    AuditDialog dialog;

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

    protected void initView() {

        gv = findViewById(R.id.gv);
        tv_login = findViewById(R.id.tv_login);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        //动态注册广播接收器
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.administrator.zhapp.RECEIVER");
        registerReceiver(msgReceiver, intentFilter);

        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示");
                builder.setMessage("你确定要重新登录?");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ControllerActivity.getAppManager().finishAllActivity();
                        NohttpUtils.getInstance().cancelAll();
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });

    }


    //后台上传数据
    private void upLoadData() {
        //如果有网络，就上传数据
        if (NetworkAvailableUtils.isNetworkAvailable(this)) {
            Intent intent = new Intent(this, UploadDataService.class);
            startService(intent);
        }
    }

    public void initData() {

        checkUpdateApk();


        zys = new ArrayList<>();
        zys2 = new ArrayList<>();

        dialogDatas = new ArrayList<>();
        dialogDatas2 = new ArrayList<>();

        mToolbar.setBackgroundColor(Color.parseColor("#00000000"));

        title.setText("设备设施巡查");

        setExitZx();

        item = new ArrayList<>();

        item.addAll(PermissionsResult());

        //检查是否有任务推送
        checkPush();
        //上传数据
        upLoadData();

        try {
            deleteOverdueJH();
        } catch (Exception e) {
            e.printStackTrace();
        }

        beanList.addAll(getGridViewData(isTask));

        gv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridViewAdapter(this, beanList, item, false);
        gv.setAdapter(adapter);


        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent;
                switch (position) {
                    case 0:
                        intent = new Intent(MainActivity.this, SbxdjglActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                        intent = new Intent(MainActivity.this, YdckglActivity.class);
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(MainActivity.this, AjhxcglActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(MainActivity.this, XfbwxcglActivity.class);
                        startActivity(intent);
                        break;
                    case 4:
                        intent = new Intent(MainActivity.this, XwangcMainActivity.class);
                        startActivity(intent);
                        break;
                    case 5:
                        intent = new Intent(MainActivity.this, GdActivity.class);
                        startActivity(intent);
                        break;
                    case 6:
                        if (dialogDatas.size() == 0) {
                            intent = new Intent(MainActivity.this, XscbglActivity.class);
                            startActivity(intent);
                        } else {
                            ListDialog dialog2 = new ListDialog(context, dialogDatas, new ListDialog.ListDialogListener() {
                                @Override
                                public void selectText(String str, int position) {

                                    Contans.YXCB_ZY_ID = zys.get(position).getId();
                                    Contans.YXCB_ZY_NAME = str;
                                    Intent intent = new Intent(MainActivity.this, XscbglActivity.class);
                                    startActivity(intent);
                                }
                            });
                            dialog2.show();
                        }
                        break;
                    case 7:
                        ListDialog dialog = new ListDialog(context, dialogDatas2, new ListDialog.ListDialogListener() {
                            @Override
                            public void selectText(String str, int position) {

                                Contans.YXCB_ZY_ID = zys2.get(position).getId();
                                Contans.YXCB_ZY_NAME = str;
                                Intent intent = new Intent(MainActivity.this, dqgzglActivity.class);
                                startActivity(intent);
                            }
                        });
                        dialog.show();
                        break;
                }
            }
        });

        requestZyDatas();
        requestZyDatas2();
    }


    /**
     * @param isTask 是否有行为安全观察任务
     * @return
     */
    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;
    }

    //检查系统是否有任务推送
    private void checkPush() {

        int[] whats = new int[]{-1, -1, -1, -1, -1};
        int[] test = {0, 1, 2, 3, 4};
        for (int i = 0; i < item.size(); i++) {

            if (item.get(i) == 0) {
                //点检
                whats[0] = 1;
            } else if (item.get(i) == 2) {
                //安健环
                whats[1] = 2;
                whats[2] = 3;
            } else if (item.get(i) == 3) {
                //消防
                whats[4] = 0;
            }
        }

        Intent intent = new Intent(this, PushService.class);
        Bundle bundle = new Bundle();
        bundle.putIntArray("what", whats);
        intent.putExtras(bundle);
        startService(intent);
    }


    //推送任务
    private void shownotification() {

        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingIntent;
        Intent intent = new Intent(this, SbxdjglActivity.class);
        Notification notify;

        intent.putExtra(Contans.KEY_NOTIF, "one");

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }

        notify = new Notification.Builder(this)
                .setTicker(System.currentTimeMillis() + "")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker(push.getDbid())
                .setContentTitle(push.getDbtitle())
                .setContentText(push.getDbname())
                .setContentIntent(pendingIntent).build(); // 需要注意build()是在API
        notify.defaults = Notification.DEFAULT_SOUND;
        // level16及之后增加的，API11可以使用getNotificatin()来替代
        notify.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时，通知将被清除。
        manager.notify(0, notify);
    }


    private List<Integer> PermissionsResult() {
        List<Integer> item = new ArrayList<>();

        item.add(0);
        try {
            String result = (String) SPUtils.get(context, Contans.PERMISSIONSRESULT, "");

            if (!result.isEmpty()) {
                String[] results = result.split(";");

                for (String name : results) {
                    if (name.equals("AppDeviceCheck")) {
                        item.add(0);
                        item.add(5);
                    } else if (name.equals("AppMobileHouse")) {
                        item.add(1);
                    } else if (name.equals("AppSafetyCheck")) {
                        item.add(2);
                        item.add(4);
                        item.add(5);
                    } else if (name.equals("AppFireCheck")) {
                        item.add(3);
                    } else if (name.equals("AppDefineCheck")) {

                    } else if (name.equals("AppMeterReading")) {
                        item.add(6);
                    } else if (name.equals("AppXSCB")) {
                        item.add(6);
                    } else if (name.equals("AppDQGZ")) {
                        item.add(7);

                    }
                }
            }
        } catch (Exception e) {
        }
        return item;
    }

    //删除过期计划
    private void deleteOverdueJH() {

        List<String> djjhs = new ArrayList<>();
        List<String> xfDjjhs = new ArrayList<>();
        List<String> ajhjhs = new ArrayList<>();
        List<String> xwaqgcJhs = new ArrayList<>();

        List<Djjh> djjh = DataSupport.findAll(Djjh.class);
        for (Djjh jh : djjh) {
            if (UiUtlis.isdelete(jh.getDQSJ())) {
                djjhs.add(jh.getJHID());
            }
        }
        List<Ajhjh> ajhjh = DataSupport.findAll(Ajhjh.class);
        for (Ajhjh jh : ajhjh) {
            if (UiUtlis.isdelete(jh.getDQSJ())) {
                ajhjhs.add(jh.getJHID());
            }
        }
        List<XfDjjh> xfDjjh = DataSupport.findAll(XfDjjh.class);
        for (XfDjjh jh : xfDjjh) {
            if (UiUtlis.isdelete(jh.getNexttime())) {
                xfDjjhs.add(jh.getJhid());
            }
        }

        List<XwaqgcJh> xwaqgcJh = DataSupport.findAll(XwaqgcJh.class);

        for (XwaqgcJh jh : xwaqgcJh) {
            if (UiUtlis.isdelete(jh.getDQSJ())) {
                xwaqgcJhs.add(jh.getJHID());
            }
        }
        //删除点检数据
        for (String jhid : djjhs) {
            DataSupport.deleteAll(Djjh.class, "jhid = ?", jhid);
            DataSupport.deleteAll(DjjhRwQy.class, "jhid = ?", jhid);
            List<XcjsInfo> infos = DataSupport.where("jhid = ?", jhid).find(XcjsInfo.class);
            for (XcjsInfo info : infos) {
                File file = new File(info.getFilename());
                if (file.isFile()) {
                    file.delete();
                }
            }
            DataSupport.deleteAll(XcjsInfo.class, "jhid = ?", jhid);
            DataSupport.deleteAll(QxgdInfo.class);
        }

        //删除安健环数据
        for (String jhid : ajhjhs) {
            List<Ajhxcjs> ajhxcjses = DataSupport.findAll(Ajhxcjs.class);
            for (Ajhxcjs js : ajhxcjses) {
                File file = new File(js.getFile());
                if (file.isFile()) {
                    file.delete();
                }
            }
            DataSupport.deleteAll(Ajhxcjs.class, "jhid = ?", jhid);
            DataSupport.deleteAll(Ajhjh.class, "jhid = ?", jhid);
            DataSupport.deleteAll(Ajhxzrwqy.class, "jhid = ?", jhid);
            DataSupport.deleteAll(AjhScInfo.class, "jhid = ?", jhid);
            DataSupport.deleteAll(YhpcInfo.class);
        }

        //删除消防数据
        for (String jhid : xfDjjhs) {

            List<XfXcjsInfo> infos = DataSupport.where("jhid = ?", jhid).find(XfXcjsInfo.class);
            for (XfXcjsInfo info : infos) {
                File file = new File(info.getPath());
                if (file.isFile()) {
                    file.delete();
                }
            }

            List<LyXcjsInfo> lyjs = DataSupport.where("jhid = ?", jhid).find(LyXcjsInfo.class);
            for (LyXcjsInfo info : lyjs) {
                File file = new File(info.getPath());
                if (file.isFile()) {
                    file.delete();
                }
            }
            DataSupport.deleteAll(XfDjjh.class, "jhid = ?", jhid);
            DataSupport.deleteAll(XfDjjhRwqy.class, "jhid = ?", jhid);
            DataSupport.deleteAll(XfXcjsInfo.class, "jhid = ?", jhid);
            DataSupport.deleteAll(XfXcxmjg.class, "jhid = ?", jhid);
            DataSupport.deleteAll(XfXcmhqc.class, "jhid = ?", jhid);
            DataSupport.deleteAll(XfBaxcRwqy.class, "jhid = ?", jhid);
            DataSupport.deleteAll(XfXcxm.class, "jhid = ?", jhid);
            DataSupport.deleteAll(Lyxcrwqy.class, "jhid = ?", jhid);
            DataSupport.deleteAll(LyxcXm.class, "jhid = ?", jhid);
            DataSupport.deleteAll(LyXcjsInfo.class, "jhid = ?", jhid);
            DataSupport.deleteAll(LyxcXmJg.class, "jhid = ?", jhid);
            DataSupport.deleteAll(LyYhpcInfo.class);
        }

        for (String jh : xwaqgcJhs) {
            DataSupport.deleteAll(XwaqgcJh.class, "jhid = ?", jh);
            DataSupport.deleteAll(XwaqgcSc.class, "jhid = ?", jh);
            DataSupport.deleteAll(XwaqgcJs.class, "jhid = ?", jh);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    // 按两次返回键退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                ControllerActivity.getAppManager().finishAllActivity();
                finish();
                System.exit(0);
                NohttpUtils.getInstance().cancelAll();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setExitZx() {
        mToolbar.setNavigationIcon(R.mipmap.back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示");
                builder.setMessage("你确定要退出程序?");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ControllerActivity.getAppManager().finishAllActivity();
                        finish();
                        System.exit(0);
                        NohttpUtils.getInstance().cancelAll();
                        dialog.dismiss();
                    }
                });
                builder.create().show();

            }
        });

        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.zx:
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setTitle("提示");
                        builder.setMessage("你确定要重新登录?");
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ControllerActivity.getAppManager().finishAllActivity();
                                NohttpUtils.getInstance().cancelAll();
                                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                                startActivity(intent);
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                        break;
                }
                return true;
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        int size = DataSupport.findAll(XwaqgcJh.class).size();
        isTask = size != 0;
        beanList.clear();
        beanList.addAll(getGridViewData(isTask));
        adapter.notifyDataSetChanged();
    }

    /**
     * 广播接收器
     */
    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            isTask = intent.getBooleanExtra("isTask", false);
            beanList.clear();
            beanList.addAll(getGridViewData(isTask));
            adapter.notifyDataSetChanged();
        }
    }

    private void requestZyDatas() {


        final Request<String> requset = NoHttp.createStringRequest(Contans.IP + Contans.XS_JCSJ, RequestMethod.POST);

        requset.setDefineRequestBodyForJson(createZyJson());

        NohttpUtils.getInstance().add(this, 0, requset, new HttpListener<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {

                try {
                    BasicDataBean bean = GsonUtils.GsonToBean(response.get(), BasicDataBean.class);
                    if (bean != null) {
                        if (bean.getState() == 1) {
                            if (bean.getData().size() != 0) {
                                zys.clear();
                                zys.addAll(bean.getData());
                                initDialogDatas();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

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

            }
        });
    }

    private void requestZyDatas2() {


        final Request<String> requset = NoHttp.createStringRequest(Contans.IP + Contans.XS_JCSJ, RequestMethod.POST);

        requset.setDefineRequestBodyForJson(createZyJson2());

        NohttpUtils.getInstance().add(this, 0, requset, new HttpListener<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {

                try {
                    BasicDataBean2 bean = GsonUtils.GsonToBean(response.get(), BasicDataBean2.class);
                    if (bean != null) {
                        if (bean.getState() == 1) {
                            if (bean.getData().size() != 0) {
                                zys2.clear();
                                zys2.addAll(bean.getData());
                                initDialogDatas2();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

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

            }
        });
    }


    private void checkUpdateApk() {

        final Request<String> requset = NoHttp.createStringRequest(Contans.IP + Contans.UPDATEURL, RequestMethod.POST);

        requset.setDefineRequestBodyForJson(createZyJson());

        NohttpUtils.getInstance().add(this, 0, requset, new HttpListener<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {

                try {
                    String result = response.get();
                    showLog(result);
                    ApkUpdateBean appUploadInfo = GsonUtils.GsonToBean(result, ApkUpdateBean.class);

                    if (appUploadInfo != null) {
                        if (appUploadInfo.getTotal().equals("1")) {
                            showLog(result);
                            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(Contans.IP == Contans.IP_INTRANET){
                                appURL = appUploadInfo.getRows().get(0).getApkurl2();
                            }


                            if (!appversionname.equals(getVersionName())) {
                                if(TextUtils.isEmpty(appdesc)){
                                    appdesc = "1.登录接口调整。\n2.所有接口增加token认证";
                                }
                                DownloadAndInstall(appURL, appversionname, appdesc, versioncode);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

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

            }
        });


    }

    private void DownloadAndInstall(String downloadURL, String versionName, String description, String versionCode) {
        new com.azhon.appupdate.manager.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;
    }

    private void initDialogDatas() {

        for (BasicDataBean.DataBean bean : zys) {
            dialogDatas.add(bean.getName());
        }
    }


    private void initDialogDatas2() {

        for (BasicDataBean2.DataBean bean : zys2) {
            dialogDatas2.add(bean.getName());
        }
    }

    private String createZyJson() {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("GGJK_JCSJ_GET");
        info.setModuletype("Set_ZYMC");
        String json = GsonUtils.GsonString(info);
        return json;
    }


    private String createZyJson2() {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("GGJK_JCSJ_GET");
        info.setModuletype("Set_DQJZ");
        String json = GsonUtils.GsonString(info);
        return json;
    }


//    private String getVersionName() {
//        //1,包管理者对象packageManager
//        PackageManager pm = getPackageManager();
//        //2,从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号),传0代表获取基本信息
//        try {
//            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
//            //3,获取版本名称
//            return packageInfo.versionName;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.dismiss();
        }
    }

}


