package com.sipai.jspatrol.Alarm;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.sipai.jspatrol.Bean.Alarm;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.DateFormatUtils;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.SharedPreferencesData;
import com.sipai.ui.EmptyLayout;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

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;

public class AlarmListActivity extends AppCompatActivity implements View.OnClickListener {
    private SharedPreferencesData sharedpre;
    private HashMap<String, String> map_base = new HashMap<>();
    private String mServer;
    private String mBizid;
    private EditText tvstartdate,tvenddate;
    private int year,month,day,hour,minute,lastday,lastmonth;
    private int page = 1;
    private LinearLayoutManager manager;
    private SuperRecyclerView rc_view;
    private SwipeRefreshLayout refresh;
    private EmptyLayout emptyLayout;
    private ImageView iv_back;
    private EditText edt_name;
    private TextView tv_search;
    private String name = "";
    private List<Alarm> alarms = new ArrayList<>();
    private AlarmAdapter adapter;

    public static void actionStart(Context context){
        Intent intent = new Intent(context,AlarmListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_list);
        init();
        initView();
        getAlarmMsgs();
    }

    private void initView() {
        iv_back = findViewById(R.id.moudle_alarm_list_iv_back);
        iv_back.setOnClickListener(this);
        edt_name = findViewById(R.id.moudle_alarm_list_edt_equname);
        tv_search = findViewById(R.id.moudle_alarm_list_tv_search);
        tv_search.setOnClickListener(this);
        tvstartdate=(EditText)findViewById(R.id.moudle_alarm_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(AlarmListActivity.this, Datelistener, year, month, day);
                    dpd.show();//显示DatePickerDialog组件
                }
                return false;
            }
        });
        tvenddate=(EditText)findViewById(R.id.moudle_alarm_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(AlarmListActivity.this, Datelistener, year, month, day);
                    dpd.show();//显示DatePickerDialog组件
                }
                return false;
            }
        });
        if (day<8){
            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 + "-" + (month + 1) + "-" + lastday + " " + hour + ":" + minute));
        }
        tvenddate.setText(DateFormatUtils.DateFormatMinString(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute));
        rc_view = findViewById(R.id.moudle_alarm_list_rc);
        emptyLayout = findViewById(R.id.moudle_alarm_list_ui_empty);
        refresh = findViewById(R.id.moudle_alarm_list_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getAlarmMsgs();
            }
        });
        manager = new LinearLayoutManager(this);
        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;
                getAlarmMsgs();
            }
        });
    }

    private void init() {
        sharedpre = new SharedPreferencesData(this);
        map_base = sharedpre.getAll();
        mServer = map_base.get("mServer");
        SharedPreferences sharedPreferences = getSharedPreferences("config",MODE_PRIVATE);
        mBizid = sharedPreferences.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);//获取这个月的第几天
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.moudle_alarm_list_iv_back:
                finish();
                break;
            case R.id.moudle_alarm_list_tv_search:
                startSearch();
                break;
        }
    }

    private void startSearch() {
        if (edt_name.getText()!=null&&!edt_name.getText().toString().isEmpty()){
            name = edt_name.getText().toString();
        }
        getAlarmMsgs();
    }

    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(AlarmListActivity.this,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));
            }
            getAlarmMsgs();
        }
    };

    /**
     * 获取当前时间的前一周
     * @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;
    }

    private void getAlarmMsgs() {
        HashMap<String,String> map = new HashMap<>();
        map.put("companyId",mBizid);
        map.put("search_name",name);
        map.put("alarmlevel","");
        map.put("status","");
        map.put("page",String.valueOf(page));
        map.put("sdt",tvstartdate.getText().toString());
        map.put("edt",tvenddate.getText().toString());
        map.put("rows","50");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetAlarmList_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
//                showError(a);
                updateList();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("describe")&&res.contains("id")){
                    alarms = parseAlarmList(res);
                }else {
                    alarms = new ArrayList<>();
                }
                updateList();
            }
        });
    }

    private void updateList() {
        if (!AlarmListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh.setRefreshing(false);
                    if (alarms.size()>0){
                        emptyLayout.setVisibility(View.GONE);
                        rc_view.setVisibility(View.VISIBLE);
                        adapter = new AlarmAdapter(AlarmListActivity.this,alarms);
                        rc_view.setAdapter(adapter);
                    }else {
                        rc_view.setVisibility(View.GONE);
                        emptyLayout.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    private List<Alarm> parseAlarmList(String res) {
        List<Alarm> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(res);
            for (int i=0;i<array.length();i++){
                Alarm item = new Alarm();
                item.setId(array.getJSONObject(i).optString("id"));
                if (array.getJSONObject(i).optString("alarmTime").length()>16){
                    item.setAlarmtime(array.getJSONObject(i).optString("alarmTime").substring(0,16));
                }else {
                    item.setAlarmtime(array.getJSONObject(i).optString("alarmTime"));
                }
                item.setPointCode(array.getJSONObject(i).optString("pointCode"));
                item.setPointName(array.getJSONObject(i).optString("pointName"));
                item.setAlarmTypeName(array.getJSONObject(i).optString("alarmTypeName"));
                item.setStatus(array.getJSONObject(i).optString("status"));
                item.setAlarmtype(array.getJSONObject(i).optString("alarmType"));
                item.setDescribe(array.getJSONObject(i).optString("describe"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}
