package com.sipai.jspatrol.Main.fragment.mainfragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.sipai.jspatrol.Alarm.AlarmListActivity;
import com.sipai.jspatrol.Base.BaseFragmentView;
import com.sipai.jspatrol.Bean.Biz;
import com.sipai.jspatrol.Bean.MainTab;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Bean.Message;
import com.sipai.jspatrol.Bean.Patrol;
import com.sipai.jspatrol.Bean.PatrolModel;
import com.sipai.jspatrol.Equ.EquSearchActivity;
import com.sipai.jspatrol.Fault.NewFaultActivity;
import com.sipai.jspatrol.Message.MessageAdapter;
import com.sipai.jspatrol.MonitorScreen.MonitorScreenListActivity;
import com.sipai.jspatrol.Patrol.ProPatrolTaskListActivity;
import com.sipai.jspatrol.PointAnalysis.SelPointListActivity;
import com.sipai.jspatrol.PointAnalysis.SolutionListActivity;
import com.sipai.jspatrol.ProMonitoring.MeasurePointsAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.Service.IPatrolService;
import com.sipai.jspatrol.Statement.StatementTypeActivity;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.Webv.GuideMenuActivity;
import com.sipai.jspatrol.URL.GuideMenuUrl;
import com.sipai.jspatrol.utils.BroadCastManager;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.SharedPreferencesData;
import com.sipai.jspatrol.utils.okHttpCookie.CookiesManager;
import com.sipai.ui.EmptyLayout;
import com.sipai.ui.bizPopWindow.CustomListPopupWindow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;
import static com.sipai.jspatrol.Service.IPatrolService.update_biz;

/**
 * created by lvliming on 2020/6/16
 * 主页
 */
public class MainFragment extends BaseFragmentView<MainFragmentPresenter, MainFragmentContract.View> implements View.OnClickListener, CustomListPopupWindow.ItemClickCallBack {
    private SharedPreferencesData sharedpre;
    private HashMap<String, String> map_key_msg = new HashMap<>();
    private HashMap<String, String> map_base = new HashMap<>();
    private String mServer;
    private String mUserid;
    private String ip_in_plant = "", ip_off_site = "";//厂内，厂外ip地址
    private SweetAlertDialog pDialog;
    private RelativeLayout rl_patrol,rl_equ_search;
    private BroadcastReceiver mReceiver,pointReceiver;
    private List<Patrol> patrols = new ArrayList<>();
    private TextView tv_duration, tv_task_name;
    private TextView tv_all, tv_unsub, tv_sub;
    private String all;
    private String unsub;
    private String sub;
    private List<Message> msgs = new ArrayList<>();
    private RecyclerView rc_msg;
    private MessageAdapter msgAdapter;
    private LinearLayoutManager manager;
    private RelativeLayout rl_file,rl_wz,rl_backlog,rl_alarm,rl_statement,rl_monitor_screen,rl_sel_point,rl_solution;
    private TextView tv_biz;
    CustomListPopupWindow mPopupWindow;
    private CustomListPopupWindow.ItemClickCallBack mCallBack;
    private String mCheckedUId="";
    private Context mContext;
    private String bizs;
    private List<Biz> bizList = new ArrayList<>();
    private String mBizName;
    private String mBizid;
    private NavigationTabStrip tab;
//    private List<String> tab_title = Arrays.asList(new String[]{"进水", "出水", "液位"});
    private String[] tab_title;
    private List<MainTab> mainTabs = new ArrayList<>();
    private List<Measuringpoint> points = new ArrayList<>();
    private MeasurePointsAdapter pointlistadapter;
    private EmptyLayout emptyLayout;
    private List<Patrol> daily_patrols = new ArrayList<>();
    private String patrolType;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        mCallBack=this;
        mContext=getActivity();
        init();
        initView(view);
        initBroadcast();
        getTab();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getPatrolTask();
    }

    private void getTab() {
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId",mBizid);
        OKHttpUtils.OKCall(map, mServer, MethodURL.GetMainTab_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                showDialog("标签获取失败，请重试");
                noPoint();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("code")&&res.contains("msg")&&res.contains("result")){
                    mainTabs = parseMainTab(res);
                    if (mainTabs.size()>0){
                        tab_title = new String[mainTabs.size()];
                        for (int i=0;i<mainTabs.size();i++){
                            tab_title[i] = mainTabs.get(i).getSname();
                        }
                        updateTab();
                    }else {
                        showDialog("请至平台配置首页标签");
                        noPoint();
                    }
                }else {
                    showDialog("标签获取失败，请重试");
                    noPoint();
                }
            }
        });
    }

    private void noPoint() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        rc_msg.setVisibility(View.GONE);
                        emptyLayout.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    private void updateTab() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tab.setTitles(tab_title);
                        if (tab_title.length>0){
                            tab.setTabIndex(0);
                            getTabPointList(mainTabs.get(0).getId());
                        }
                    }
                });
            }
        }
    }

    private List<MainTab> parseMainTab(String res) {
        List<MainTab> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(res);
            JSONArray array = jsonObject.getJSONArray("result");
            for (int i=0;i<array.length();i++){
                MainTab item = new MainTab();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setName(array.getJSONObject(i).optString("name"));
                item.setSname(array.getJSONObject(i).optString("sname"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void getMsgs() {
        HashMap<String,String> map = new HashMap<>();
        map.put("page","1");
        map.put("rows","50");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetMsgList_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
//                showError(a);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("rows")&&res.contains("total")){
                    msgs = parseMsgs(res);
                    updateMsgs();
                }
            }
        });
    }

    private void updateMsgs() {
        if (isAdded()) {
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (msgs.size() > 0) {
                            manager = new LinearLayoutManager(getActivity());
                            rc_msg.setLayoutManager(manager);
                            msgAdapter = new MessageAdapter(msgs);
                            rc_msg.setAdapter(msgAdapter);
                        }
                    }
                });
            }
        }
    }

    private List<Message> parseMsgs(String res) {
        List<Message> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(res);
            JSONArray array = jsonObject.getJSONArray("rows");
            if (array.length()>0){
                for (int i=0;i<array.length();i++){
                    Message item = new Message();
                    item.setId(array.getJSONObject(i).optString("id"));
                    item.setContent(array.getJSONObject(i).optString("content"));
                    item.setRedflag(array.getJSONObject(i).optString("redflag"));
                    item.setSdt(array.getJSONObject(i).optString("sdt"));
                    list.add(item);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void initBroadcast() {
        IntentFilter filter_nv = new IntentFilter();
        filter_nv.addAction(IPatrolService.update_newvalue);
        pointReceiver = new NewValueReceiver();
        BroadCastManager.getInstance().registerReceiver(getActivity(), pointReceiver, filter_nv);
        IntentFilter filter = new IntentFilter();
        filter.addAction(IPatrolService.update_task);
        mReceiver = new NowTaskReceiver();
        BroadCastManager.getInstance().registerReceiver(getActivity(), mReceiver, filter);
    }

    /**
     * 更新数据广播
     */
    class NewValueReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String nValue = intent.getStringExtra("newvalue");
                parsenValue(nValue);
            } catch (Exception e) {

            }
        }
    }

    private void parsenValue(String nValue) {
        int cou=0;
        try {
            JSONArray array = new JSONArray(nValue);
            for (int i=0;i<array.length();i++){
                for (int a=0;a<points.size();a++){
                    if (points.get(a).getSid().equals(array.getJSONObject(i).optString("id"))){
                        cou+=1;
                        points.get(a).setCvalue(array.getJSONObject(i).optString("parmvalue"));
                    }
                }
            }
            if (cou>0) {
                pointlistadapter.setData(points);
                updateNValue();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void updateNValue() {
        if (isAdded()&&!getActivity().isFinishing()){
            getActivity().runOnUiThread(()->{
                pointlistadapter.notifyDataSetChanged();
            });
        }
    }

    @Override
    public void callBack(Biz biz) {
        mCheckedUId=biz.getBizid();
        final String name = biz.getName();
        saveBizid(getActivity(),mCheckedUId,name);
        if (isAdded()) {
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_biz.setText(name);
                        mPopupWindow.dismiss();
                    }
                });
            }
        }
        getTab();
    }

    private void saveBizid(Context context,String bizid, String name) {
        //获取SharedPreferences对象
        SharedPreferences sharedPre=context.getSharedPreferences("config", MODE_PRIVATE);
        //获取Editor对象
        SharedPreferences.Editor editor=sharedPre.edit();
        //设置参数
        editor.putString("bizid", bizid);
        editor.putString("bizname",name);
        //提交
        editor.commit();
        mBizid=sharedPre.getString("bizid", "");
        mBizName = sharedPre.getString("bizname","");
        Intent intent = new Intent(update_biz);
        getActivity().sendBroadcast(intent);
    }

    class NowTaskReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                patrols = (List<Patrol>) intent.getSerializableExtra("tasks");
                all = intent.getStringExtra("all");
                unsub = intent.getStringExtra("unsub");
                sub = intent.getStringExtra("sub");
                updatePatrols();
            } catch (Exception e) {

            }
        }
    }

    private void updatePatrols() {
        if (isAdded()){
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_all.setText(all);
                        tv_unsub.setText(unsub);
                        tv_sub.setText(sub);
                        if (patrols.size() > 0) {
                            if (patrols.get(0).getStartTime().length()>15&&patrols.get(0).getEndTime().length()>15) {
                                tv_duration.setText("(" + patrols.get(0).getStartTime().substring(5, 16) + " -- " + patrols.get(0).getEndTime().substring(5, 16) + ")");
                            }
                            if (patrols.get(0).getName()!=null&&!patrols.get(0).getName().isEmpty()) {
                                tv_task_name.setText(patrols.get(0).getName());
                            }
                        } else {
                            tv_duration.setText("");
                            tv_duration.setText("暂无任务");
                        }
                    }
                });
            }
        }
    }

    private void initView(View view) {
        pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setCancelable(true);
        pDialog.setCanceledOnTouchOutside(true);
        tab = view.findViewById(R.id.moudle_fg_main_tab);
        tab.setOnTabStripSelectedIndexListener(new NavigationTabStrip.OnTabStripSelectedIndexListener() {
            @Override
            public void onStartTabSelected(String title, int index) {
                getTabPointList(mainTabs.get(index).getId());
            }

            @Override
            public void onEndTabSelected(String title, int index) {

            }
        });
        emptyLayout = view.findViewById(R.id.moudle_main_fg_ui_empty);
        emptyLayout.setOnClickListener(this);
        rl_sel_point = view.findViewById(R.id.moudle_main_fg_rl_sel_point);
        rl_sel_point.setOnClickListener(this);
        rl_solution = view.findViewById(R.id.moudle_main_fg_rl_solution);
        rl_solution.setOnClickListener(this);
        rl_alarm = view.findViewById(R.id.moudle_main_fg_rl_alarm);
        rl_alarm.setOnClickListener(this);
        rl_patrol = view.findViewById(R.id.moudle_fg_main_rl_patrol);
        rl_patrol.setOnClickListener(this);
        rl_equ_search = view.findViewById(R.id.moudle_main_fg_rl_equ_search);
        rl_equ_search.setOnClickListener(this);
        rl_statement = view.findViewById(R.id.moudle_main_fg_rl_statement);
        rl_statement.setOnClickListener(this);
        tv_duration = view.findViewById(R.id.moudle_fg_main_tv_duration);
        tv_task_name = view.findViewById(R.id.moudle_fg_main_tv_task_name);
        tv_all = view.findViewById(R.id.moudle_main_fg_task_all);
        tv_unsub = view.findViewById(R.id.moudle_main_fg_task_unsub);
        tv_sub = view.findViewById(R.id.moudle_main_fg_task_sub);
        rc_msg = view.findViewById(R.id.moudle_main_fg_rc_msg);
        manager = new LinearLayoutManager(getActivity());
        rc_msg.setLayoutManager(manager);
        rl_monitor_screen = view.findViewById(R.id.moudle_main_fg_rl_monitor_screen);
        rl_monitor_screen.setOnClickListener(this);
//        rl_file = view.findViewById(R.id.moudle_main_fg_rl_file);
//        rl_file.setOnClickListener(this);
        rl_backlog = view.findViewById(R.id.moudle_main_fg_rl_backlog);
        rl_backlog.setOnClickListener(this);
        tv_biz = view.findViewById(R.id.moudle_fg_main_tv_bizname);
        tv_biz.setText(mBizName);
        tv_biz.setOnClickListener(this);
    }

    private void getTabPointList(String id) {
        HashMap<String,String> map = new HashMap<>();
        map.put("page","1");
        map.put("rows","100");
        map.put("unitId",mBizid);
        map.put("pid",id);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetMainTabPointList_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
//                showError(a);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res!=null&&!res.isEmpty()&&!res.contains("html")){
                    points = parsePoints(res);
                    if (points.size()>0) {
                        updatePoints();
                    }else {
                        showDialog("请至平台配置关联测量点");
                        noPoint();
                    }
                }else {
                    showDialog("测量点获取失败，请重试");
                    noPoint();
                }
            }
        });
    }

    private void updatePoints() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        emptyLayout.setVisibility(View.GONE);
                        rc_msg.setVisibility(View.VISIBLE);
                        pointlistadapter = new MeasurePointsAdapter(getActivity(),points);
                        rc_msg.setAdapter(pointlistadapter);
                    }
                });
            }
        }
    }

    private List<Measuringpoint> parsePoints(String res) {
        List<Measuringpoint> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(res);
            for (int i=0;i<array.length();i++){
                Measuringpoint item = new Measuringpoint();
                JSONObject js = array.getJSONObject(i).getJSONObject("mPoint");
                item.setSid(js.optString("id"));
                item.setName(js.opt("parmname").toString());
                item.setUnit(js.opt("unit").toString());
                item.setCvalue(js.opt("parmvalue").toString());
                item.setType(js.optString("signaltype"));
                item.setScadacode(js.opt("id").toString());
                item.setAlarmmax(js.opt("alarmmax").toString());
                item.setAlarmmin(js.opt("alarmmin").toString());
                item.setUnitId(js.optString("bizid"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void init() {
        sharedpre = new SharedPreferencesData(getActivity());
        map_base = sharedpre.getAll();
        ip_in_plant = map_base.get("ip_in_plant");
        ip_off_site = map_base.get("ip_off_site");
        mServer = map_base.get("mServer");
        mUserid = map_base.get("mUserid");
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("config",MODE_PRIVATE);
        patrolType = sharedPreferences.getString("patrolTypeId","");
        bizs = sharedPreferences.getString("biz","");
        bizList = parseBiz(bizs);
        mBizid = sharedPreferences.getString("bizid","");
        mBizName = sharedPreferences.getString("bizname","");
    }

    private List<Biz> parseBiz(String result) {
        List<Biz> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(result);
            for (int i=0;i<array.length();i++){
                Biz item = new Biz();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setBizid(array.getJSONObject(i).optString("id"));
                item.setName(array.getJSONObject(i).optString("text"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return list;
        }
        return list;
    }

    private void showMsgFinish() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pDialog.hide();
            }
        });
    }

    private void showMsgDialog() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initDialog("数据获取中...");
                pDialog.show();
            }
        });
    }

    private void initDialog(String st) {
        pDialog.setTitleText(st);
    }

    @Override
    public MainFragmentContract.View getContract() {
        return new MainFragmentContract.View() {

        };
    }

    private void showDialog(final String st) {
        if (isAdded()){
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new SweetAlertDialog(getActivity(),SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("注意")
                                .setContentText(st)
                                .setConfirmText("确定")
                                .show();
                    }
                });
            }
        }
    }

    @Override
    public MainFragmentPresenter getPresenter() {
        return new MainFragmentPresenter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BroadCastManager.getInstance().unregisterReceiver(getActivity(),mReceiver);
        BroadCastManager.getInstance().unregisterReceiver(getActivity(),pointReceiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.moudle_main_fg_rl_sel_point:
                Intent intent = new Intent(getActivity(), SelPointListActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.moudle_main_fg_rl_solution:
                Intent intent_solution = new Intent(getActivity(), SolutionListActivity.class);
                getActivity().startActivity(intent_solution);
                break;
            case R.id.moudle_main_fg_rl_alarm:
                AlarmListActivity.actionStart(getActivity());
                break;
            case R.id.moudle_main_fg_ui_empty:
                if (mainTabs.size()>0){
                    getTabPointList(mainTabs.get(tab.getTabIndex()).getId());
                }else {
                    getTab();
                }
                break;
            case R.id.moudle_main_fg_rl_backlog:
                NewFaultActivity.actionStart(getActivity(),"","","");
//                GuideMenuActivity.actionStart(getActivity(), GuideMenuUrl.url_backlog, GuideMenuUrl.name_backlog);
//                GuideMenuActivity.actionStart(getActivity(), GuideMenuUrl.url_subfault+"unitId="+mBizid, GuideMenuUrl.name_subfault);
                break;
            case R.id.moudle_main_fg_rl_monitor_screen:
                Intent intent_ms = new Intent(getActivity(), MonitorScreenListActivity.class);
                startActivity(intent_ms);
                break;
//            case R.id.moudle_main_fg_rl_file:
//                GuideMenuActivity.actionStart(getActivity(), GuideMenuUrl.url_technical_file, GuideMenuUrl.name_technical_file);
//                break;
            case R.id.moudle_fg_main_rl_patrol:
                Intent intent_patrol = new Intent(getActivity(), ProPatrolTaskListActivity.class);
                startActivity(intent_patrol);
                break;
            case R.id.moudle_main_fg_rl_equ_search:
                EquSearchActivity.actionStart(getActivity());
                break;
            case R.id.moudle_fg_main_tv_bizname:
                mPopupWindow=new CustomListPopupWindow(mContext, bizList,mCheckedUId, mCallBack);
                mPopupWindow.showAsDropDown(tv_biz);
                break;
            case R.id.moudle_main_fg_rl_statement:
                Intent intent_statement = new Intent(getActivity(), StatementTypeActivity.class);
                startActivity(intent_statement);
                break;
        }
    }

    private void getPatrolTask() {
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId",mBizid);
        map.put("userIds",mUserid);
        map.put("bizid",mBizid);
        map.put("type","P");
        OKHttpUtils.OKCallGet(map, mServer, MethodURL.GetPatrolList_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (!res.contains("fail")&&res.contains("allNum")) {
                    daily_patrols = getDailyPatrols(res);
                    if (daily_patrols.size()>0){
                        List<Patrol> nowPatrols = checkPatrols(daily_patrols);
                        patrols = nowPatrols;
                        if (nowPatrols.size()==0){
                            Patrol patrol = new Patrol();
                            patrol.setContent("暂无任务");
                            patrol.setEndTime("");
                            patrol.setName("暂无任务");
                            patrol.setStartTime("");
                            nowPatrols.add(patrol);
                        }
                        updatePatrols();
                    }
                }
            }
        });
    }

    private List<Patrol> getDailyPatrols(String response) {
        List<Patrol> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            all = jsonObject.opt("allNum").toString();
            unsub = jsonObject.opt("inCompleteNum").toString();
            sub = jsonObject.opt("completeNum").toString();
            JSONArray arry = new JSONArray(jsonObject.optString("content1"));
            for (int i=0;i<arry.length();i++){
                Patrol patrol = new Patrol();
                patrol.setBizid(arry.getJSONObject(i).opt("bizId").toString());
                patrol.setContent(arry.getJSONObject(i).opt("content").toString());
                patrol.setEndTime(arry.getJSONObject(i).opt("endTime").toString());
                patrol.setSid(arry.getJSONObject(i).opt("id").toString());
                patrol.setName(arry.getJSONObject(i).opt("name").toString());
                patrol.setPatrolArea(arry.getJSONObject(i).opt("patrolArea").toString());
                patrol.setPatrolAreaId(arry.getJSONObject(i).opt("patrolAreaId").toString());
                patrol.setPatrolModelId(arry.getJSONObject(i).opt("patrolModelId").toString());
                patrol.setPatrolPlanId(arry.getJSONObject(i).opt("patrolPlanId").toString());
                patrol.setStartTime(arry.getJSONObject(i).opt("startTime").toString());
                patrol.setStatus(arry.getJSONObject(i).opt("status").toString());
                patrol.setType(arry.getJSONObject(i).opt("type").toString());
                patrol.setWorkResult(arry.getJSONObject(i).opt("workResult").toString());
                patrol.setWorker(arry.getJSONObject(i).opt("worker").toString());
                patrol.setWorkerId(arry.getJSONObject(i).opt("workerId").toString());
                patrol.setPatrolType(patrolType);
                PatrolModel patrolModel = new PatrolModel();
                if (arry.getJSONObject(i).opt("patrolModel")!=null&&!arry.getJSONObject(i).opt("patrolModel").toString().equals("null")) {
                    JSONObject js = new JSONObject(arry.getJSONObject(i).opt("patrolModel").toString());
                    patrolModel.setSid(js.opt("id").toString());
                    patrolModel.setActive(js.opt("active").toString());
                    patrolModel.setBizId(js.opt("bizId").toString());
                    patrolModel.setDefaultFlag(js.opt("defaultFlag").toString());
                    patrolModel.setName(js.opt("name").toString());
                    patrolModel.setType(js.opt("type").toString());
                    patrolModel.setWhere(js.opt("where").toString());
                    patrol.setPatrolModel(patrolModel);
                }else {
                    patrolModel.setSid("");
                    patrolModel.setActive("");
                    patrolModel.setBizId("");
                    patrolModel.setDefaultFlag("");
                    patrolModel.setName("");
                    patrolModel.setType("");
                    patrolModel.setWhere("");
                    patrol.setPatrolModel(patrolModel);
                }
                list.add(patrol);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private List<Patrol> checkPatrols(List<Patrol> daily_patrols) {
        List<Patrol> list = new ArrayList<>();
        for (int i=0;i<daily_patrols.size();i++){
            Patrol item = daily_patrols.get(i);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());
            Calendar cnow = Calendar.getInstance();
            Calendar cstart = Calendar.getInstance();
            Calendar cend = Calendar.getInstance();
            int result = 0;
            int result1 = 0;
            try {
                cnow.setTime(curDate);
                cstart.setTime(df.parse(item.getStartTime()));
                cend.setTime(df.parse(item.getEndTime()));
                result = cnow.compareTo(cstart);
                result1 = cnow.compareTo(cend);
                if (result>=0&&result1<=0){
                    list.add(item);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

}
