package com.qy.agv.activity;

import static com.qy.agv.comm.BaseApplication.mScanManager;
import static com.qy.agv.util.Constant.CACHE_BIND_CONTROL;
import static com.qy.agv.util.Constant.CACHE_LOGIN_KEY;
import static com.qy.agv.util.ToolUtils.getIp;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.qy.agv.R;
import com.qy.agv.activity.adapter.MainListViewAdapter;
import com.qy.agv.activity.dao.MainDao;
import com.qy.agv.activity.model.EventMessage;
import com.qy.agv.activity.model.RobotModel;
import com.qy.agv.activity.model.ShelfModel;
import com.qy.agv.activity.model.SiteModel;
import com.qy.agv.activity.model.TaskModel;
import com.qy.agv.activity.model.UserModel;
import com.qy.agv.comm.BaseActivity;
import com.qy.agv.comm.CacheService;
import com.qy.agv.comm.Res;
import com.qy.agv.databinding.ActivityMainBinding;
import com.qy.agv.update.UpdateManager;
import com.qy.agv.util.Constant;
import com.qy.agv.util.DateUtil;
import com.qy.agv.util.HttpsUtil;
import com.qy.agv.util.MD5Encryption;
import com.qy.agv.util.MyProgress;
import com.qy.agv.util.Permission;
import com.qy.agv.util.ProjectUtils;
import com.qy.agv.util.StringUtils;
import com.qy.agv.util.ToastUtils;
import com.qy.agv.util.ToolUtils;

import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class MainActivity extends BaseActivity {
    public static Logger mylog =Logger.getLogger(MainActivity.class);

    private ActivityMainBinding binding;
    private Context context;
    private MainListViewAdapter listViewAdapter;
    private ArrayList<TaskModel> mList;
    private UserModel user;
    private Button submit;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow1;
    private PopupWindow popupWindow2;
    private View popup_view;
    private String[] sendMsg = new String[4];
    TextView robot;
    TextView target;
    TextView shelf;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        ProjectUtils.init();
        registerReceiver();
        initCommonTop2();
        initLogin();
        initView();
        initData();
        Permission.checkPermission(this);
        EventBus.getDefault().register(this);
        reloadData();
        checkNet();
        update();
    }

    private void checkNet(){
        new Thread(()->{
            while (true){
                try {
                    boolean rs = ToolUtils.checkUrl(Constant.HTTP_URL);
                    if(!rs){
                        int times = ToolUtils.ping2("www.baidu.com", 1, 3000);
                        runOnUiThread(()->{
                            binding.showMsg.setVisibility(View.VISIBLE);
                            if(times < 0){
                                binding.showMsg.setText("网络连接异常");
                            }else{
                                binding.showMsg.setText("服务器连接异常");
                            }
                        });
                    }else{
                        runOnUiThread(()->{
                            binding.showMsg.setVisibility(View.GONE);
                        });
                    }
                    TimeUnit.SECONDS.sleep(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void reloadData(){
        new Handler().postDelayed(()->{
            if(Constant.user != null) {
                searchTask(1);
            }
            reloadData();
        }, 10000);
    }

    private void initLogin(){
        String userStr = CacheService.getInstance(context).getCache(CACHE_LOGIN_KEY, "user");
        if(!StringUtils.isEmpty(userStr)){
            user = new Gson().fromJson(userStr, UserModel.class);
            if(!StringUtils.isEmpty(user.getLoginPwd()) && !StringUtils.isEmpty(user.getLoginName())){
                checkToken(user.getLoginName(), user.getLoginPwd());
            }
        }
    }


    private void initData(){
        mList = new ArrayList<>();
        listViewAdapter = new MainListViewAdapter(mList, context);
        binding.swipeContainer.setAdapter(listViewAdapter);
        binding.swipeContainer.setVisibility(View.GONE);
        binding.tvEmpty.setVisibility(View.VISIBLE);
        binding.swipeContainer.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark);
        binding.swipeContainer.setProgressViewEndTarget(true, 200);
        binding.swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchTask(0);
            }
        });
        binding.swipeContainer.autoRefresh();
    }

    private void initView(){
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setImageDrawable(Res.getDrawable("list"));
        back.setOnClickListener(view -> {
            toActivity(ControlActivity.class);
        });

        submit = findViewById(R.id.c_iv_common_submit);
        submit.setBackgroundColor(Res.getColor("transparent"));
        submit.setTextColor(Res.getColor("white"));
        submit.setVisibility(View.VISIBLE);
        submit.setText("未登录");
        submit.setOnClickListener(view -> {
            if("未登录".contentEquals(submit.getText())) {
//                checkToken(getMac(), getMac());
                login();
            }else{
                toActivity(RobotInfoActivity.class);
            }
        });
        submit.setOnLongClickListener(v -> {
            toActivity(RobotInfoActivity.class);
            return false;
        });
    }

    private void registerReceiver() {
        if (mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            if(Constant.MODEL.contains("ET")) {
                filter.addAction(ET_SCAN_ACTION);
            }
            registerReceiver(mReceiver, filter);
        }
    }

    public void checkToken(String loginName, String loginPwd) {
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在登录");
        try {
            RequestParams params = httParams(Constant.LOG_IN);
            params.addBodyParameter("grant_type", "password");
            params.addBodyParameter("username", loginName);
            if (StringUtils.isEmpty(loginName)) {
                ToastUtils.showToast(context, "账号不能为空");
                return;
            }
            if (StringUtils.isEmpty(loginPwd)) {
                ToastUtils.showToast(context, "密码不能为空");
                return;
            }
            //      密码md5加密
            String pwdMd5 = MD5Encryption.encrypt(loginPwd);
            params.addBodyParameter("password", pwdMd5);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String arg0) {
                    mylog.debug(arg0);
                    try {
                        if (arg0.contains("error_description")) {
                            JSONObject object = new JSONObject(arg0);
                            ToastUtils.showToast(context, object.getString("error_description"));
                        } else {
                            user = new Gson().fromJson(arg0, UserModel.class);
                            user.setLoginName(loginName);
                            user.setLoginPwd(loginPwd);
                            Constant.ACCESS_TOKEN = user.getAccess_token();
                            Constant.REFRESH_TOKEN = user.getAccess_token();
                            arg0 = new Gson().toJson(user);
                            CacheService.getInstance(context).saveCache(CACHE_LOGIN_KEY, "user", arg0);
                            if (user.getUser_id() != null) {
                                if (popupWindow2 != null) {
                                    popupWindow2.dismiss();
                                }
                                Constant.user = user;
                                Object real_name_obj = user.getReal_name();
                                if (real_name_obj != null) {
                                    submit.setText(real_name_obj.toString());
                                }
                                searchTask(0);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mylog.error(e);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    HttpsUtil.parserError(MainActivity.this, ex);
                }

                @Override
                public void onFinished() {
                    progress.close();
                }

                @Override
                public void onCancelled(CancelledException arg0) {
                    mylog.error("onRead:", arg0);
                }
            });
        }catch (Exception e){
            ToastUtils.showToast(context, "登录失败");
            mylog.error(e);
        }
    }

    private void push(String qrcode, String title){
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在发送"+title+"请求任务");
        RequestParams params = httParams(Constant.PUSH_TASK);
        params.addBodyParameter("user_id", user.getUser_id().toString());
        params.addBodyParameter("qrcode", qrcode);
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs);
                try {
                    if (rs.getInt ("code")!= 200) {
                        ToastUtils.showToast(context, "请求失败");
                    } else {
                        if(rs.getBoolean("success")){
                            JSONObject data = rs.getJSONObject("data");
                            TaskModel taskModel = new Gson().fromJson(data.toString(), TaskModel.class);
                            mList.add(0, taskModel);
                            binding.swipeContainer.setVisibility(View.VISIBLE);
                            binding.tvEmpty.setVisibility(View.GONE);
                            listViewAdapter.notifyDataSetChanged();
                            ToastUtils.showToast(context, "请求发送成功");
                            sendMsg = new String[4];
                            popupWindow.dismiss();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(MainActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                progress.close();
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    @Override
    protected String getCommonTopTitle() {
        return Res.getString("app_name");
    }

    @Override
    protected int getCommonTopICO() {
        return 0;
    }

    @Override
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
        if(barcode.startsWith("05-")){
            String loginName = barcode.split("-")[1];
            String[] login_password = loginName.split(",");
            checkToken(login_password[0], login_password[1]);
            return;
        }
        if(user == null){
            ToastUtils.showToast(context, "该设备没有登录");
            return;
        }
        if(barcode.startsWith("01-")){
            sendMsg = new String[4];
            if(robot!=null)robot.setText("");
            if(target!=null)target.setText("");
            if(target!=null)shelf.setText("");
            barcode = barcode.split("-")[1];
        }
        else if(barcode.startsWith("02-")){
            sendMsg[1] = barcode.split("-")[1];
            if(robot!=null)robot.setText(sendMsg[1]);
            return;
        }
        else if(barcode.startsWith("03-")){
            sendMsg[2] = barcode.split("-")[1];
            if(target!=null)target.setText(sendMsg[2]);
            return;
        }
        else if(barcode.startsWith("04-")){
            sendMsg[3] = barcode.split("-")[1];
            if(shelf!=null)shelf.setText(sendMsg[3]);
            return;
        }else{
            ToastUtils.showToast(context, "无效码");
            return;
        }
        if(popupWindow!=null && popupWindow.isShowing()){
            popupWindow.dismiss();
            popupWindow = null;
        }
        int rs = checkBarcode(barcode);
        if(rs == 0){
            ToastUtils.showToast(context, "无效功能码");
        }else if(rs == 2) {
            showNavigateView();
        }else {
            pushTask();
        }
    }

    private void pushTask(){
        String title = sendMsg[0];
        String robot = sendMsg[1];
        String target = sendMsg[2];
        String shelf = sendMsg[3];
        if(StringUtils.isEmpty(title)){
            ToastUtils.showToast(context, "功能码不能为空");
            return;
        }
        if("0".equals(robot)){
            ToastUtils.showToast(context, "请指定机器人");
            return;
        }
        if("0".equals(target)){
            ToastUtils.showToast(context, "请指定目的地");
            return;
        }
        if("0".equals(shelf)){
            ToastUtils.showToast(context, "请指定货架");
            return;
        }
        if(robot==null)robot="";
        if(target==null)target="";
        if(shelf==null)shelf="";
        String qrcode = title+","+robot+","+target+","+shelf;
        SiteModel siteModel = null;
        if(!StringUtils.isEmpty(shelf)){
            siteModel = MainDao.getInstance().querySiteName(context, shelf);
        }else if(!StringUtils.isEmpty(target)){
            siteModel = MainDao.getInstance().querySiteName(context, target);
        }
        if(siteModel!=null) {
            AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("提示")
                    .setMessage("确定到"+siteModel.getSiteName()+"吗?")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {// 设置确定按钮
                                @Override
                                // 处理确定按钮点击事件
                                public void onClick(DialogInterface dialog, int which) {
                                    push(qrcode, title);
                                }
                            })
                    .setNegativeButton("取消", null)
                    .setCancelable(true).create();
            alert.show();
        }else{
            push(qrcode, title);
        }
    }

    private void showNavigateView(){
        View v = binding.getRoot().getRootView();
        popup_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_item,null);
        initViewText(popup_view);
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow = new PopupWindow(v, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow.setContentView(popup_view);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
        setBackgroundAlpha(0.5f);
        popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
    }

    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private void initViewText(View popup_view){
        TextView title = popup_view.findViewById(R.id.tv_msg);
        Button cancel = popup_view.findViewById(R.id.bt_cancel);
        Button ok = popup_view.findViewById(R.id.bt_ok);
        cancel.setOnClickListener(view->{
            popupWindow.dismiss();
        });
        ok.setOnClickListener(view->{
            pushTask();
        });

        String msg_title = sendMsg[0];
        title.setText(msg_title);
        parserRobot(popup_view, sendMsg[1]);
        parserTarget(popup_view, sendMsg[2]);
        parserShelf(popup_view, sendMsg[3]);
    }

    private void parserRobot(View popup_view, String msg_robot){
        robot = popup_view.findViewById(R.id.tv_robot);
        LinearLayout ll_robot = popup_view.findViewById(R.id.ll_robot);
        TextView sel_robot = popup_view.findViewById(R.id.tv_sel_robot);
        if(StringUtils.isEmpty(msg_robot)){
            ll_robot.setVisibility(View.GONE);
        }else if("0".equals(msg_robot)){
            sel_robot.setVisibility(View.VISIBLE);
            ll_robot.setVisibility(View.VISIBLE);
            sel_robot.setOnClickListener(view->{selParam(1);});
        }else{
            sel_robot.setVisibility(View.GONE);
            ll_robot.setVisibility(View.VISIBLE);
            robot.setText(msg_robot);
        }
    }
    private void parserTarget(View popup_view, String msg_target){
        target = popup_view.findViewById(R.id.tv_target);
        LinearLayout ll_target = popup_view.findViewById(R.id.ll_target);
        TextView sel_target = popup_view.findViewById(R.id.tv_sel_target);
        if(StringUtils.isEmpty(msg_target)){
            ll_target.setVisibility(View.GONE);
        }else if("0".equals(msg_target)){
            sel_target.setVisibility(View.VISIBLE);
            ll_target.setVisibility(View.VISIBLE);
            sel_target.setOnClickListener(view->{selParam(2);});
        }else{
            sel_target.setVisibility(View.GONE);
            ll_target.setVisibility(View.VISIBLE);
            target.setText(msg_target);
        }
    }

    private void parserShelf(View popup_view, String msg_shelf){
        shelf = popup_view.findViewById(R.id.tv_shelf);
        LinearLayout ll_shelf = popup_view.findViewById(R.id.ll_shelf);
        TextView sel_shelf = popup_view.findViewById(R.id.tv_sel_shelf);
        if(StringUtils.isEmpty(msg_shelf)){
            ll_shelf.setVisibility(View.GONE);
        }else if("0".equals(msg_shelf)){
            sel_shelf.setVisibility(View.VISIBLE);
            ll_shelf.setVisibility(View.VISIBLE);
            sel_shelf.setOnClickListener(view->{selParam(3);});
        }else{
            sel_shelf.setVisibility(View.GONE);
            ll_shelf.setVisibility(View.VISIBLE);
            shelf.setText(msg_shelf);
        }
    }

    private int checkBarcode(String barcode){
        if(StringUtils.isEmpty(barcode)){
            return 0;
        }
        String[] barInfo = barcode.split(",");
        if(barInfo.length > 0){
            sendMsg[0] = barInfo[0];
        }
        if(barInfo.length > 1){
            sendMsg[1] = barInfo[1];
        }
        if(barInfo.length > 2){
            sendMsg[2] = barInfo[2];
        }
        if(barInfo.length > 3){
            sendMsg[3] = barInfo[3];
        }
        String msg_robot = sendMsg[1];
        String msg_target = sendMsg[2];
        String msg_shelf = sendMsg[3];
        if("0".equals(msg_robot)
                ||"0".equals(msg_target)
                ||"0".equals(msg_shelf)){
            return 2;
        }
        return 1;
    }

    private void selParam(int sel){
        View view = binding.getRoot().getRootView();
        List<Map<String,String>> params = new ArrayList<>();
        if(sel == 1){
            List<RobotModel> robotModels = MainDao.getInstance().searchRobot(context);
            for (RobotModel robotModel : robotModels) {
                Map<String, String> map = new HashMap<>();
                map.put("name", robotModel.getRobotId());
                map.put("value", robotModel.getRobotId());
                params.add(map);
            }
        }
        if(sel == 2){
            List<SiteModel> shelfModels = MainDao.getInstance().searchSite(context);
            for (SiteModel siteModel : shelfModels) {
                Map<String, String> map = new HashMap<>();
                map.put("name", siteModel.getSiteCode());
                map.put("value", siteModel.getSiteCode());
                params.add(map);
            }
        }
        if(sel == 3){
            List<ShelfModel> shelfModels = MainDao.getInstance().searchShelf(context);
            for (ShelfModel shelfModel : shelfModels) {
                Map<String, String> map = new HashMap<>();
                map.put("name", shelfModel.getShelfLpn());
                map.put("value", shelfModel.getShelfLpn());
                params.add(map);
            }
        }
        if(params.size() == 0){
            return;
        }
        View popup_list_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_list_view,null);
        ListView mListView = popup_list_view.findViewById(R.id.lv_data);
        Button itemCancel = popup_list_view.findViewById(R.id.bt_item_cancel);
        itemCancel.setOnClickListener(v -> {
            if(popupWindow1!=null && popupWindow1.isShowing()){
                popup_view.setVisibility(View.VISIBLE);
                popupWindow1.dismiss();
            }
        });
        mListView.setBackgroundResource(R.color.white);
        SimpleAdapter simplead = new SimpleAdapter(this, params,
                R.layout.popupwindow_list_item, new String[] { "name"},
                new int[] {R.id.tv_msg});
        mListView.setAdapter(simplead);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                try {
                    String value = params.get(position).get("value");
                    String name = params.get(position).get("name");
                    if("-".equals(value)){
                        popupWindow1.dismiss();
                        return;
                    }
                    if(popupWindow!=null && popupWindow.isShowing()) {
                        if(sel == 1 && robot!=null){
                            sendMsg[1] = value;
                            robot.setText(name);
                        }
                        if(sel == 2 && target!=null){
                            sendMsg[2] = value;
                            target.setText(name);
                        }
                        if(sel == 3 && shelf!=null){
                            sendMsg[3] = value;
                            shelf.setText(name);
                        }
                        popup_view.setVisibility(View.VISIBLE);
                    }
                    popupWindow1.dismiss();
                }catch (Exception ex){
                    mylog.error("选择参数异常", ex);
                }
            }
        });
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow1 = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow1.setContentView(popup_list_view);
        popupWindow1.setOutsideTouchable(false);
        popupWindow1.setFocusable(false);
        popupWindow1.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        setBackgroundAlpha(0.5f);
        popup_view.setVisibility(View.GONE);
        popupWindow1.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    private void searchTask(int from) {
        MyProgress myProgress = MyProgress.getInstance();
        if(from == 0) {
            myProgress.show(context, "提示", "正在加载");
        }
        RequestParams params = httParams(Constant.TASK_LIST);
        params.addBodyParameter("requester", Constant.user.getUser_id().toString());
        params.addBodyParameter("current", "1");
        params.addBodyParameter("size", "100");
        params.addBodyParameter("descs", "distribution_time");
//        params.addBodyParameter("distributionTime", DateUtil.getCurrDate(Constant.DATE_FORMATE));
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") != 200) {
                        ToastUtils.showToast(context, "请求失败");
                    } else {
                        if (rs.getBoolean("success")) {
                            System.out.println(rs.get("data"));
                            Type rds = new TypeToken<Map<String, JsonElement>>() {
                            }.getType();
                            Map<String, JsonElement> records = new Gson().fromJson(rs.get("data").toString(), rds);
                            int pages = rs.getJSONObject("data").getInt("pages");
                            System.out.println(records.get("records"));
                            Type lt = new TypeToken<ArrayList<TaskModel>>() {}.getType();
                            Object recodes_obj = records.get("records");
                            if(recodes_obj!=null) {
                                if(from == 0) {
                                    mList.clear();
                                    List<TaskModel> taskModelList = new Gson().fromJson(recodes_obj.toString(), lt);
                                    mList.addAll(taskModelList);
                                    if(mList.size() > 0) {
                                        binding.swipeContainer.setVisibility(View.VISIBLE);
                                        binding.tvEmpty.setVisibility(View.GONE);
                                    }else{
                                        binding.swipeContainer.setVisibility(View.GONE);
                                        binding.tvEmpty.setVisibility(View.VISIBLE);
                                    }
                                    listViewAdapter.notifyDataSetChanged();
                                    binding.swipeContainer.setRefreshing(false);
                                    binding.swipeContainer.setLoading(false);
                                }
                                if(from == 1){
                                    List<TaskModel> taskModelList = new Gson().fromJson(recodes_obj.toString(), lt);
                                    updateList(taskModelList);
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(MainActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    public void updateList(List<TaskModel> n_list){
        for (TaskModel taskModel:mList){
            String id = taskModel.getId();
            for (TaskModel nTaskModel:n_list){
                if(id.equals(nTaskModel.getId())){
                    taskModel.setRequestStatus(nTaskModel.getRequestStatus());
                }
            }
        }
        listViewAdapter.notifyDataSetChanged();
    }

    private void logout(){
        Constant.user = null;
        CacheService.getInstance(context).clear(CACHE_BIND_CONTROL);
        CacheService.getInstance(context).clear(CACHE_LOGIN_KEY);
        Constant.ACCESS_TOKEN = null;
        Constant.REFRESH_TOKEN = null;
        mList.clear();
        listViewAdapter.notifyDataSetChanged();
        binding.swipeContainer.setVisibility(View.GONE);
        binding.tvEmpty.setVisibility(View.VISIBLE);
        submit.setText("未登录");
    }

    private void login(){
        View view = binding.getRoot().getRootView();
        View popup_login_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_login,null);
        EditText loginName = popup_login_view.findViewById(R.id.tv_login_name);
        EditText loginPassword = popup_login_view.findViewById(R.id.tv_login_password);
        String userStr = CacheService.getInstance(context).getCache(CACHE_LOGIN_KEY, "user");
        if(!StringUtils.isEmpty(userStr)){
            user = new Gson().fromJson(userStr, UserModel.class);
            loginName.setText(user.getLoginName());
            loginPassword.setText(user.getLoginPwd());
        }
        Button cancel = popup_login_view.findViewById(R.id.bt_cancel);
        Button ok = popup_login_view.findViewById(R.id.bt_ok);
        cancel.setOnClickListener(v -> {
            popupWindow2.dismiss();
        });
        ok.setOnClickListener(v -> {
            String lName = loginName.getText().toString();
            String lPassword = loginPassword.getText().toString();
            checkToken(lName, lPassword);
        });
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow2 = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow2.setContentView(popup_login_view);
        popupWindow2.setOutsideTouchable(true);
        popupWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow2.setFocusable(true);
        popupWindow2.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow2.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
        setBackgroundAlpha(0.5f);
        popupWindow2.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    public void update(){
        UpdateManager updateManager = new UpdateManager(context);
        try {
            updateManager.checkUpdate();
        }catch (Exception ex){
            ex.printStackTrace();
            mylog.error("更新检测异常", ex);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void onReceiveMsg(EventMessage message){
        if(message.getType() == 1){
            logout();
        }
    }
}