package com.sipai.jspatrol.Equ.Equfrgment;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

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

import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.Fault;
import com.sipai.jspatrol.Bean.ProcessSection;
import com.sipai.jspatrol.Equ.EquCardActivity;
import com.sipai.jspatrol.Fault.adapter.DoneFaultAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.DateFormatUtils;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.SharedPreferencesData;
import com.sipai.ui.EmptyLayout;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
//import com.superrecycleview.superlibrary.utils.SuperDivider;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * created by lvliming on 2020/10/22
 */
public class EquFaultListFragment extends Fragment {
    private SharedPreferencesData sharedpre;
    private HashMap<String, String> map_base = new HashMap<>();
    private String mServer;
    private String mBizid;
    private EquList equ;
    private EditText tvstartdate,tvenddate;
    private int year,month,day,hour,minute,lastday,lastmonth;
    private int page = 1;
    private List<Fault> faults = new ArrayList<>();
    private DoneFaultAdapter doneFaultAdapter;
    private LinearLayoutManager manager;
    private SuperRecyclerView rc_view;
    private SwipeRefreshLayout refresh;
    private EmptyLayout emptyLayout;

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_equ_fault_list,container,false);
        initView(view);
        getFaultList();
        return view;
    }

    private void initView(View view) {
        tvstartdate=(EditText)view.findViewById(R.id.moudle_equ_fault_list_edt_sd);
        tvstartdate.setCursorVisible(false);
        tvstartdate.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //创建DatePickerDialog对象
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    MyDatePickerDialog dpd = new MyDatePickerDialog(getActivity(), Datelistener, year, month, day);
                    dpd.show();//显示DatePickerDialog组件
                }
                return false;
            }
        });
        tvenddate=(EditText)view.findViewById(R.id.moudle_equ_fault_list_edt_ed);
        tvenddate.setCursorVisible(false);
        tvenddate.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //创建DatePickerDialog对象
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    MyDatePickerDialog dpd = new MyDatePickerDialog(getActivity(), Datelistener, year, month, day);
                    dpd.show();//显示DatePickerDialog组件
                }
                return false;
            }
        });
        if (day==1){
            if (month!=0) {
                Calendar calendar = Calendar.getInstance(Locale.CHINA);
                calendar.set(Calendar.MONTH, month - 1);
                int tday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                tvstartdate.setText(DateFormatUtils.DateFormatMinString(year + "-" + (month) + "-" + lastday + " " + hour + ":" + minute));
            }else{
                Calendar calendar = Calendar.getInstance(Locale.CHINA);
                calendar.set(Calendar.MONTH, 11);
                int tday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                tvstartdate.setText(DateFormatUtils.DateFormatMinString((year-1)  + "-" + 12 + "-" + lastday + " " + hour + ":" + minute));
            }
        }else {
            tvstartdate.setText(DateFormatUtils.DateFormatMinString(year + "-" + (lastmonth + 1) + "-" + lastday + " " + hour + ":" + minute));
        }
        tvenddate.setText(DateFormatUtils.DateFormatMinString(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute));
        rc_view = view.findViewById(R.id.moudle_equ_fault_list_rc);
        emptyLayout = view.findViewById(R.id.moudle_equ_fault_list_ui_empty);
        refresh = view.findViewById(R.id.moudle_equ_fault_list_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getFaultList();
            }
        });
        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();
            }
        });
//        rc_view.addItemDecoration(SuperDivider.newBitmapDivider());
    }


    private void init() {
        EquCardActivity equcard = (EquCardActivity) getActivity();
        equ = equcard.getEquList();
        sharedpre = new SharedPreferencesData(getActivity());
        map_base = sharedpre.getAll();
        mServer = map_base.get("mServer");
        SharedPreferences sharedPre = getActivity().getSharedPreferences("config", 0);
        mBizid = sharedPre.getString("bizid", "");
        //初始化Calendar日历对象
        Calendar mycalendar=Calendar.getInstance(Locale.CHINA);
        Date mydate=new Date(); //获取当前日期Date对象
        mycalendar.setTime(mydate);////为Calendar对象设置时间为当前日期
        year=mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
        month=mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
        day=mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
        lastday=getBeforeDay(mycalendar).get(Calendar.DAY_OF_MONTH);
        lastmonth=getBeforeDay(mycalendar).get(Calendar.MONTH);
        hour=mycalendar.get(Calendar.HOUR_OF_DAY);//获取这个月的第几天
        minute=mycalendar.get(Calendar.MINUTE);//获取这个月的第几天
    }

    private void getFaultList() {
        isShowRefresh();
        HashMap<String,String> map = new HashMap<>();
        map.put("type", GlobalVal.Fault_Type);
        map.put("rows","20");
        map.put("page",String.valueOf(page));
        map.put("search_code",mBizid);
        map.put("processSectionId",equ.getProcesssectionid());
        map.put("equipmentId",equ.getId());
        map.put("status", GlobalVal.Fault_Status_Finish);
        map.put("beginTimeStore",tvstartdate.getText().toString());
        map.put("endTimeStore",tvenddate.getText().toString());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETEquFaults_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);
                    ifShowTheEmpty();
                    setAdapter();
                }else {
                    List<Fault> list = parseFault(res);
                    if (list.size()>0) {
                        faults.addAll(list);
                        updateLoadMore();
                    }else {
                        noMore();
                    }
                }
            }
        });
    }

    private void isShowRefresh() {
        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 (!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 (!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 updateLoadMore() {
        if (!getActivity().isFinishing()){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    rc_view.completeLoadMore();
                    doneFaultAdapter.notifyDataSetChanged();
                }
            });
        }
    }

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

    private List<Fault> parseFault(String response) {
        List<Fault> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            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 setAdapter() {
        if (!getActivity().isFinishing()){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh.setRefreshing(false);
                    doneFaultAdapter = new DoneFaultAdapter(getActivity(),faults);
                    rc_view.setAdapter(doneFaultAdapter);
                    manager = new LinearLayoutManager(getActivity());
                    rc_view.setLayoutManager(manager);
                }
            });
        }
    }

    public class MyDatePickerDialog extends DatePickerDialog {

        public MyDatePickerDialog(Context context, OnDateSetListener callBack,
                                  int year, int month, int day) {
            super(context, callBack, year, month, day);
            // TODO Auto-generated constructor stub
        }
        @Override
        protected void onStop() {
            //super.onStop();//防止onDateSet执行两次

        }
    }

    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            year=myyear;
            month=monthOfYear;
            day=dayOfMonth;
            //更新日期
            updateDate();
        }
        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate()
        {
            //在TextView上显示日期
            TimePickerDialog dpd=new TimePickerDialog(getActivity(),Timelistener,hour,minute,true);
            dpd.show();//显示DatePickerDialog组件
        }
    };

    private TimePickerDialog.OnTimeSetListener Timelistener=new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hours, int minutes) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            hour=hours;
            minute=minutes;
            //更新日期
            updateDate();
        }
        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate()
        {
            //在TextView上显示日期
            if(tvstartdate.isFocused()){
                tvstartdate.setText(DateFormatUtils.DateFormatMinString(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute));
            }else if(tvenddate.isFocused()){
                tvenddate.setText(DateFormatUtils.DateFormatMinString(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute));
            }
            getFaultList();
        }
    };

    /**
     * 获取当前时间的前一周
     * @param cl
     * @return
     */
    private static Calendar getBeforeDay(Calendar cl){
        //使用roll方法进行向前回滚
        //cl.roll(Calendar.DATE, -1);
        //使用set方法直接进行设置
        int day = cl.get(Calendar.DATE);
        cl.set(Calendar.DATE, day-7);
        return cl;
    }
}
