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

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sipai.jspatrol.Base.BaseFragmentView;
import com.sipai.jspatrol.Bean.Biz;
import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.Fault;
import com.sipai.jspatrol.Bean.ProcessSection;
import com.sipai.jspatrol.Fault.NewFaultActivity;
import com.sipai.jspatrol.Fault.NewFaultDetailActivity;
import com.sipai.jspatrol.Fault.adapter.DoingFaultAdapter;
import com.sipai.jspatrol.Fault.adapter.DoneFaultAdapter;
import com.sipai.jspatrol.Fault.adapter.NewFaultAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.GuideMenuUrl;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.Webv.GuideMenuActivity;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.ProgressForAll;
import com.sipai.jspatrol.utils.okHttpCookie.CookiesManager;
import com.sipai.ui.EmptyLayout;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.superrecycleview.superlibrary.utils.SuperDivider;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * created by lvliming on 2019/9/16
 */
public class FaultFragment extends BaseFragmentView<FaultFragmentPresenter, FaultFragmentContract.View> implements View.OnClickListener{
    private EditText edt_search;
    private TextView tv_sub;
    private TextView tv_all,tv_subed,tv_doing,tv_com;
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid, mBizName;
    private List<Fault> faults = new ArrayList<>();
    private NewFaultAdapter newAdapter;
    private DoingFaultAdapter doingFaultAdapter;
    private DoneFaultAdapter doneFaultAdapter;
    private LinearLayoutManager manager;
    private SuperRecyclerView rc_view;
    private SwipeRefreshLayout refresh;
    private EmptyLayout emptyLayout;
    private String type = "2";
    private int page = 1;

    //待办所用控件
    private String url;
    private String name;
    private WebView webView;
    private String cookies;
    private String fileabspath = "";
    private ProgressDialog progressDialog;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> uploadMessage; // 用于5.0以上
    final static int FILE_SELECTED = 4;
    public static final int REQUEST_SELECT_FILE = 100;
    private TextView tv_backlog,tv_faultlist,tv_wwlist;


    @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_fault,container,false);
        init();
        initView(view);
        return view;
    }

    private void init() {
        SharedPreferences sharedPre = getActivity().getSharedPreferences("config", 0);
        mServer = sharedPre.getString("server", "");
        mUsername = sharedPre.getString("username", "");
        mPassword = sharedPre.getString("password", "");
        mUserid = sharedPre.getString("userid", "");
        mCaption = sharedPre.getString("caption", "");
        mBizid = sharedPre.getString("bizid", "");
        mBizName = sharedPre.getString("bizname", "");
        url = GuideMenuUrl.url_backlog;
    }

    private void initView(View view) {
        //异常模块控件
        edt_search = view.findViewById(R.id.moudle_fg_fault_edt_search);
        tv_sub = view.findViewById(R.id.moudle_fg_fault_tv_sub);
        tv_sub.setOnClickListener(this);
        tv_all = view.findViewById(R.id.moudle_fg_fault_tv_all);
        tv_all.setOnClickListener(this);
        tv_subed = view.findViewById(R.id.moudle_fg_fault_tv_subed);
        tv_subed.setOnClickListener(this);
        tv_doing = view.findViewById(R.id.moudle_fg_fault_tv_doing);
        tv_doing.setOnClickListener(this);
        tv_com = view.findViewById(R.id.moudle_fg_fault_tv_com);
        tv_com.setOnClickListener(this);
        emptyLayout = view.findViewById(R.id.moudle_fg_fault_ui_empty);
        refresh = view.findViewById(R.id.moudle_fg_fault_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getFaultList(type);
            }
        });
        rc_view = view.findViewById(R.id.moudle_fg_fault_rc);
        manager = new LinearLayoutManager(getActivity());
        rc_view.setLayoutManager(manager);
        rc_view.setRefreshEnabled(false);
        rc_view.setLoadMoreEnabled(true);
        rc_view.setLoadingListener(new SuperRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                page = page+1;
                getFaultList(type);
            }
        });
        rc_view.addItemDecoration(SuperDivider.newBitmapDivider());
        edt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                getFaultList(type);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //待办模块控件
        tv_backlog = view.findViewById(R.id.moudle_fault_tv_backlog);
        tv_backlog.setOnClickListener(this);
        tv_faultlist = view.findViewById(R.id.moudle_fault_tv_fault_list);
        tv_faultlist.setOnClickListener(this);
        tv_wwlist = view.findViewById(R.id.moudle_fault_tv_ww_list);
        tv_wwlist.setOnClickListener(this);
        webView = (WebView) view.findViewById(R.id.moudle_backlog_webview);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setDomStorageEnabled(true);
        //设置自适应屏幕，两者合用
        webView.getSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
        webView.getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webView.getSettings().setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webView.getSettings().setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webView.getSettings().setDisplayZoomControls(false); //隐藏原生的缩放控件
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                return super.shouldOverrideUrlLoading(webView, s);
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                showMsgDialog();
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                showMsgFinish();
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                if (mUploadMessage!=null) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    getActivity().startActivityForResult(
                            Intent.createChooser(intent, "open"),
                            FILE_SELECTED);
                }
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = valueCallback;
                if (uploadMessage!=null) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    getActivity().startActivityForResult(
                            Intent.createChooser(intent, "open"),
                            REQUEST_SELECT_FILE);
                }
                return true;
            }
        });
        cookies = CookiesManager.getCookieText(getActivity());
        synCookies(mServer, cookies);
        webView.loadUrl(mServer + MethodURL.PJ_Base + url);
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimeType, final long contentLength) {
                if (!getActivity().isFinishing()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE)
                                    .setTitleText("下载附件?")
                                    .setConfirmText("确定")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            long caca = contentLength;
                                            Uri uri = Uri.parse(url);
                                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                            startActivity(intent);

//                                        downloadBySystem(url, contentDisposition, mimeType);
                                            sweetAlertDialog.dismissWithAnimation();
                                        }
                                    })
                                    .setCancelText("取消")
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                        }
                                    })
                                    .show();
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        getFaultList(type);
    }

    private void showMsgFinish() {
        if (isAdded()) {
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ProgressForAll.cancelProgress();
                    }
                });
            }
        }
    }

    private void showMsgDialog() {
        if (!getActivity().isFinishing()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ProgressForAll.showProgress(getActivity(),"","页面加载中...");
                }
            });
        }
    }

    public void synCookies(String url, String cookies) {
        CookieSyncManager.createInstance(getActivity().getApplicationContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, cookies);
        CookieSyncManager.getInstance().sync();
    }


    @Override
    public FaultFragmentContract.View getContract() {
        return null;
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.moudle_fault_tv_backlog:
                webView.loadUrl(mServer + MethodURL.PJ_Base + GuideMenuUrl.url_backlog);
                changeColor(tv_backlog);
                break;
            case R.id.moudle_fault_tv_fault_list:
                webView.loadUrl(mServer + MethodURL.PJ_Base + GuideMenuUrl.url_faultlist+"unitId="+mBizid);
                changeColor(tv_faultlist);
                break;
            case R.id.moudle_fault_tv_ww_list:
                webView.loadUrl(mServer + MethodURL.PJ_Base + GuideMenuUrl.url_wwlist+"unitId="+mBizid);
                changeColor(tv_wwlist);
                break;
            case R.id.moudle_fg_fault_tv_sub:
//                NewFaultActivity.actionStart(getActivity(),"","","");
                GuideMenuActivity.actionStart(getActivity(), GuideMenuUrl.url_subfault+"unitId="+mBizid, GuideMenuUrl.name_subfault);
                break;
            case R.id.moudle_fg_fault_tv_all:
                changeColor(tv_all);
                break;
            case R.id.moudle_fg_fault_tv_subed:
                changeColor(tv_subed);
                type = "2";
                getFaultList(type);
                break;
            case R.id.moudle_fg_fault_tv_doing:
                changeColor(tv_doing);
                type = "0";
                getFaultList(type);
                break;
            case R.id.moudle_fg_fault_tv_com:
                changeColor(tv_com);
                type = "1";
                getFaultList(type);
                break;
        }
    }

    private void getFaultList(String type) {
        isShowRefresh();
        String search_content = "";
        if (edt_search.getText()!=null&&!edt_search.getText().toString().isEmpty()){
            search_content = edt_search.getText().toString();
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("type",type);
        map.put("page",String.valueOf(page));
        map.put("rows","15");
        map.put("bizid",mBizid);
        map.put("userid",mUserid);
        map.put("day","120");
        map.put("search_name",search_content);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetFaultList_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 (page==1) {
                    faults = parseFault(res, type);
                    ifShowTheEmpty();
                    setAdapter(type);
                }else {
                    List<Fault> list = parseFault(res, type);
                    if (list.size()>0) {
                        faults.addAll(list);
                        updateLoadMore();
                    }else {
                        noMore();
                    }
                }

            }
        });
    }

    private void updateLoadMore() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        rc_view.completeLoadMore();
                        if (type.equals("2")){
                            newAdapter.notifyDataSetChanged();
                        }else if (type.equals("0")){
                            doingFaultAdapter.notifyDataSetChanged();
                        }else if (type.equals("1")){
                            doneFaultAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }
    }

    private void noMore() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "这次是真没有了~", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    private void isShowRefresh() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (page==1) {
                            if (!refresh.isRefreshing()) {
                                refresh.setRefreshing(true);
                            }
                        }
                    }
                });
            }
        }
    }

    private void showError(String a) {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refresh.setRefreshing(false);
                        Toast.makeText(getActivity(), ""+a, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    /*
	是否显示暂无数据布局
	 */
    private void ifShowTheEmpty() {
        if (isAdded()){
            if (!getActivity().isFinishing()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (faults.size() == 0) {
                            emptyLayout.setVisibility(View.VISIBLE);
                            rc_view.setVisibility(View.GONE);
                        } else {
                            emptyLayout.setVisibility(View.GONE);
                            rc_view.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }
    }

    private void setAdapter(String type) {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refresh.setRefreshing(false);
                        if (type.equals("2")){
                            newAdapter = new NewFaultAdapter(getActivity(), faults);
                            newAdapter.setOnDelListener(new NewFaultAdapter.onSwipeListener() {
                                @Override
                                public void onFault(int pos) {
                                    if (pos >= 0 && pos < faults.size()) {
                                        NewFaultDetailActivity.actionStart(getActivity(),faults.get(pos),"yes");
                                    }
                                }
                                @Override
                                public void onDel(int pos) {
                                    if (pos >= 0 && pos < faults.size()) {
//                                    DelNewFault(faults.get(pos).getId());
                                    }
                                }
                            });
                            rc_view.setAdapter(newAdapter);
                            manager = new LinearLayoutManager(getActivity());
                            rc_view.setLayoutManager(manager);

                        }else if (type.equals("0")){
                            doingFaultAdapter = new DoingFaultAdapter(getActivity(),faults);
                            doingFaultAdapter.setOnDelListener(new DoingFaultAdapter.onSwipeListener() {
                                @Override
                                public void onFault(int pos) {
                                    if (pos >= 0 && pos < faults.size()) {
                                        Toast.makeText(getActivity(), "执行" + faults.get(pos).getProblemcontent(), Toast.LENGTH_SHORT).show();
                                    }
                                }

                                @Override
                                public void onDel(int pos) {
                                    if (pos >= 0 && pos < faults.size()) {
                                        Toast.makeText(getActivity(), "删除" + pos, Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                            rc_view.setAdapter(doingFaultAdapter);
                            manager = new LinearLayoutManager(getActivity());
                            rc_view.setLayoutManager(manager);
                        }else if (type.equals("1")){
                            doneFaultAdapter = new DoneFaultAdapter(getActivity(),faults);
                            rc_view.setAdapter(doneFaultAdapter);
                            manager = new LinearLayoutManager(getActivity());
                            rc_view.setLayoutManager(manager);
                        }
                    }
                });
            }
        }
    }

    private List<Fault> parseFault(String response, String type) {
        List<Fault> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (type.equals("2")){
                JSONArray news = new JSONArray(jsonObject.optString("content1"));
                for (int i=0;i<news.length();i++){
                    Fault new_fault = new Fault();
                    new_fault.setId(news.getJSONObject(i).opt("id").toString());
                    new_fault.setAbnormityDescription(news.getJSONObject(i).opt("abnormityDescription").toString());
                    if (news.getJSONObject(i).opt("company")!=null&&!news.getJSONObject(i).opt("company").toString().equals("null")&&news.getJSONObject(i).opt("company").toString().length()>0) {
                        JSONObject comp = new JSONObject(news.getJSONObject(i).opt("company").toString());
                        Biz biz = new Biz();
                        biz.setId(comp.optString("id"));
                        biz.setName(comp.optString("name"));
                        new_fault.setBiz(biz);
                    }else {
                        Biz biz = new Biz();
                        biz.setId("");
                        biz.setName("");
                        new_fault.setBiz(biz);
                    }
                    if (news.getJSONObject(i).opt("processSection")!=null&&!news.getJSONObject(i).opt("processSection").toString().equals("null")&&news.getJSONObject(i).opt("processSection").toString().length()>0) {
                        JSONObject area = new JSONObject(news.getJSONObject(i).opt("processSection").toString());
                        ProcessSection proc = new ProcessSection();
                        proc.setSid(area.optString("id"));
                        proc.setName(area.optString("name"));
                        new_fault.setProcessSection(proc);
                    }else {
                        ProcessSection proc = new ProcessSection();
                        proc.setSid("");
                        proc.setName("");
                        new_fault.setProcessSection(proc);
                    }
                    new_fault.setRemark(news.getJSONObject(i).opt("remark").toString());
                    new_fault.setInsdt(news.getJSONObject(i).opt("insdt").toString());
                    if (news.getJSONObject(i).opt("insertUser")!=null&&!news.getJSONObject(i).opt("insertUser").toString().equals("null")&&news.getJSONObject(i).opt("insertUser").toString().length()>0) {
                        JSONObject capt = new JSONObject(news.getJSONObject(i).opt("insertUser").toString());
                        new_fault.setInsuser(capt.optString("caption"));
                    }else {
                        new_fault.setInsuser("");
                    }
                    new_fault.setEquipmentIds(news.getJSONObject(i).opt("equipmentIds").toString());
                    new_fault.setEquipmentNames(news.getJSONObject(i).opt("equipmentNames").toString());
                    list.add(new_fault);
                }
            }else if (type.equals("0")) {
                JSONArray doings = new JSONArray(jsonObject.getString("content1"));
                for (int i=0;i<doings.length();i++){
                    Fault doing_fault = new Fault();
                    doing_fault.setId(doings.getJSONObject(i).opt("id").toString());
                    if (doings.getJSONObject(i).opt("processSection")!=null&&!doings.getJSONObject(i).opt("processSection").toString().equals("null")&&doings.getJSONObject(i).opt("processSection").toString().length()>0) {
                        JSONObject area = new JSONObject(doings.getJSONObject(i).opt("processSection").toString());
                        ProcessSection proc = new ProcessSection();
                        proc.setSid(area.optString("id"));
                        proc.setName(area.optString("name"));
                        doing_fault.setProcessSection(proc);
                    }else {
                        ProcessSection proc = new ProcessSection();
                        proc.setSid("");
                        proc.setName("");
                        doing_fault.setProcessSection(proc);
                    }
                    doing_fault.setProblemTypeNames(doings.getJSONObject(i).opt("problemTypeNames").toString());
                    doing_fault.setProblemcontent(doings.getJSONObject(i).opt("problemcontent").toString());
                    doing_fault.setPlanMoney(doings.getJSONObject(i).opt("planMoney").toString());
                    if (doings.getJSONObject(i).opt("equipmentCard")!=null&&doings.getJSONObject(i).opt("equipmentCard").toString().length()>0&&!doings.getJSONObject(i).opt("equipmentCard").toString().equals("null")) {
                        EquList card = new EquList();
                        JSONObject equ = new JSONObject(doings.getJSONObject(i).opt("equipmentCard").toString());
                        card.setEquipmentname(equ.opt("equipmentname").toString());
                        card.setEquipmentcardid(equ.opt("equipmentcardid").toString());
                        card.setId(equ.optString("id"));
                        doing_fault.setEquipmentCard(card);
                    }else {
                        EquList card = new EquList();
                        card.setId("");
                        card.setEquipmentname("");
                        card.setEquipmentcardid("");
                        doing_fault.setEquipmentCard(card);
                    }
                    if (doings.getJSONObject(i).opt("insertUser")!=null&&!doings.getJSONObject(i).opt("insertUser").toString().equals("null")&&doings.getJSONObject(i).opt("insertUser").toString().length()>0) {
                        JSONObject capt = new JSONObject(doings.getJSONObject(i).opt("insertUser").toString());
                        doing_fault.setInsuser(capt.getString("caption"));
                    }else {
                        doing_fault.setInsuser("");
                    }
                    if (doings.getJSONObject(i).opt("todoTask")!=null&&!doings.getJSONObject(i).opt("todoTask").toString().equals("null")&&doings.getJSONObject(i).opt("todoTask").toString().length()>0) {
                        JSONArray todos = new JSONArray(doings.getJSONObject(i).opt("todoTask").toString());
                        JSONObject capt = new JSONObject(todos.get(0).toString());
                        JSONObject todo = new JSONObject(capt.opt("task").toString());
                        if (todo.opt("status")!=null&&todo.opt("status").toString().length()>0){
                            if (todo.opt("status").toString().contains("handle")){
                                if (todo.optString("name").contains("验收")){
                                    doing_fault.setTaskId(todo.opt("id").toString());
                                    doing_fault.setTodoTask("验收中");
                                }else {
                                    if (capt.opt("assigneeUser")!=null&&!capt.opt("assigneeUser").toString().equals("null")&&capt.opt("assigneeUser").toString().length()>0) {
                                        doing_fault.setTaskId(todo.opt("id").toString());
                                        doing_fault.setTodoTask("执行中");
                                    }else {
                                        doing_fault.setTaskId(todo.opt("id").toString());
                                        doing_fault.setTodoTask("待签收");
                                    }
                                }
                            }else if (todo.opt("status").toString().contains("audit")){
                                doing_fault.setTaskId(todo.optString("id"));
                                doing_fault.setTodoTask(todo.optString("name"));
                            }
                        }
                        JSONObject pine = new JSONObject(capt.opt("processInstance").toString());
                        doing_fault.setProcessInstanceId(pine.opt("id").toString());
                    }
                    doing_fault.setInsdt(doings.getJSONObject(i).opt("insdt").toString());
                    doing_fault.setPlannedenddt(doings.getJSONObject(i).opt("plannedenddt").toString());
                    list.add(doing_fault);
                }
            }else if (type.equals("1")) {
                JSONArray dones = new JSONArray(jsonObject.getString("content1"));
                for (int i=0;i<dones.length();i++){
                    Fault done_fault = new Fault();
                    done_fault.setId(dones.getJSONObject(i).opt("id").toString());
                    if (dones.getJSONObject(i).opt("processSection")!=null&&!dones.getJSONObject(i).opt("processSection").toString().equals("null")&&dones.getJSONObject(i).opt("processSection").toString().length()>0) {
                        JSONObject area = new JSONObject(dones.getJSONObject(i).opt("processSection").toString());
                        ProcessSection proc = new ProcessSection();
                        proc.setSid(area.optString("id"));
                        proc.setName(area.optString("name"));
                        done_fault.setProcessSection(proc);
                    }else {
                        ProcessSection proc = new ProcessSection();
                        proc.setSid("");
                        proc.setName("");
                        done_fault.setProcessSection(proc);
                    }
                    done_fault.setProblemTypeNames(dones.getJSONObject(i).opt("problemTypeNames").toString());
                    done_fault.setProblemcontent(dones.getJSONObject(i).opt("problemcontent").toString());
                    done_fault.setPlanMoney(dones.getJSONObject(i).opt("planMoney").toString());
                    if (dones.getJSONObject(i).opt("equipmentCard")!=null&&dones.getJSONObject(i).opt("equipmentCard").toString().length()>0&&!dones.getJSONObject(i).opt("equipmentCard").toString().equals("null")) {
                        EquList card = new EquList();
                        JSONObject equ = new JSONObject(dones.getJSONObject(i).opt("equipmentCard").toString());
                        card.setEquipmentname(equ.opt("equipmentname").toString());
                        card.setEquipmentcardid(equ.opt("equipmentcardid").toString());
                        done_fault.setEquipmentCard(card);
                    }else {
                        EquList card = new EquList();
                        card.setEquipmentname("");
                        card.setEquipmentcardid("");
                        done_fault.setEquipmentCard(card);
                    }
                    if (dones.getJSONObject(i).opt("insertUser")!=null&&!dones.getJSONObject(i).optString("insertUser").equals("null")&&dones.getJSONObject(i).optString("insertUser").length()>0) {
                        JSONObject capt = new JSONObject(dones.getJSONObject(i).optString("insertUser"));
                        done_fault.setInsuser(capt.optString("caption"));
                    }else {
                        done_fault.setInsuser("");
                    }
                    done_fault.setTodoTask("任务完成");
                    done_fault.setInsdt(dones.getJSONObject(i).optString("insdt"));
                    done_fault.setEquipmentOpinion(dones.getJSONObject(i).optString("equipmentOpinion"));
                    done_fault.setPlanMoney(dones.getJSONObject(i).optString("planMoney"));
                    done_fault.setPlannedenddt(dones.getJSONObject(i).optString("plannedenddt"));
                    done_fault.setMaterialOpinion(dones.getJSONObject(i).optString("materialOpinion"));
                    done_fault.setQualityOpinion(dones.getJSONObject(i).optString("qualityOpinion"));
                    list.add(done_fault);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void changeColor(TextView tv) {
        tv_backlog.setTextColor(getResources().getColor(R.color.gray03));
        tv_faultlist.setTextColor(getResources().getColor(R.color.gray03));
        tv_wwlist.setTextColor(getResources().getColor(R.color.gray03));
        tv.setTextColor(getResources().getColor(R.color.text_blue));
    }
}
