package com.handset.serialportsensor.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handset.serialportsensor.R;
import com.handset.serialportsensor.bean.Sensor;
import com.handset.serialportsensor.bean.TestRecordsTotal;
import com.handset.serialportsensor.bean.ThresholdBean;
import com.handset.serialportsensor.constant.Constant;
import com.handset.serialportsensor.utils.DateUtils;
import com.handset.serialportsensor.utils.SPUtils;
import com.handset.serialportsensor.utils.SpUtil;
import com.handset.serialportsensor.utils.Utils;
import com.handset.serialportsensor.view.AutoLoadMoreListView;

import org.kymjs.kjframe.KJDB;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.handset.serialportsensor.utils.DateStyle.YYYY_MM_DD;
import static com.handset.serialportsensor.utils.DateStyle.YYYY_MM_DD_HH_MM_SS;

/**
 * Created by zy on 2019/2/24.
 */
public class HistoryDetailActivity extends AppCompatActivity {
    private static final String logTag = "HANDSET-JE002-EX";

    private final static int ZERO = 0;
    private final static boolean FALSE = false;
    private final static boolean TRUE = true;
    private final static int REQUEST_START_TIME = 100;
    private final static int REQUEST_END_TIME = 101;
    private final static int PAGE_SIZE = 8;  //每页显示的数据条数

    private boolean delStatus = false;
    private TextView tvStartTime;
    private TextView tvEndTime;

    private Sensor mSensor;
    private LinearLayout llDeleteContent;
    private AutoLoadMoreListView mRecyclerView;
    private MyAdapter myAdapter;
    private int currentPagedIndex = 0;//当前页码

    private TextView etCurPage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_detail);
        int id = getIntent().getIntExtra(Constant.SENSOR_ID, ZERO);
        mSensor = KJDB.getDefaultInstance().findById(id, Sensor.class);
        if (mSensor == null) {
            finish();
        }
        initView();
        initData();
    }

    void initView() {
        tvStartTime = findViewById(R.id.tv_his_detail_start_time);
        tvStartTime.setOnClickListener((View v) -> pickData(REQUEST_START_TIME));
        tvStartTime.setEnabled(true);
        tvEndTime = findViewById(R.id.tv_his_detail_end_time);
        tvEndTime.setOnClickListener((View v) -> pickData(REQUEST_END_TIME));
        etCurPage = findViewById(R.id.et_curr_page);
        TextView tvTitle = findViewById(R.id.title_text);
        ImageView ivBack = findViewById(R.id.title_back);
        tvTitle.setText(Utils.getSensorNoShow(String.valueOf(mSensor.sensor_id)));
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener((View v) -> HistoryDetailActivity.this.finish());

        mRecyclerView = findViewById(R.id.recycle_view);
        mRecyclerView.setShowLoadMore(true);
        mRecyclerView.setLoadMoreListener((AutoLoadMoreListView listView) -> {
            Log.d(logTag, "onLoadMoreBegin  [listView]:");
            if (!loadAll) {
                search((true));
            }
        });
        Button btnSelAll = findViewById(R.id.btn_select_all);
        btnSelAll.setOnClickListener((View v) -> myAdapter.selAll());
        Button btnDelete = findViewById(R.id.btn_delete);
        btnDelete.setOnClickListener((View v) -> {
            delStatus = false;
            llDeleteContent.setVisibility(View.GONE);
            myAdapter.delSelected();
        });
        Button btnCancel = findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener((View v) -> {
            llDeleteContent.setVisibility(View.GONE);
            myAdapter.setDeleteStatus(false);
            delStatus = false;
        });
        llDeleteContent = findViewById(R.id.ll_delete_content);
        llDeleteContent.setVisibility(View.GONE);
    }

    void initData() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), ZERO, ZERO, ZERO);
        long t = calendar.getTimeInMillis();
        start_time = t - 31536000000L;
        start_time = SPUtils.getInstance(this).get("search_history_start_time", start_time);
        calendar.set(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        end_time = calendar.getTimeInMillis();
        Log.i(logTag, ("initData, start_time: " + start_time + ", end_time: " + end_time));
        end_time = SPUtils.getInstance(this).get("search_history_end_time", end_time);
        loadAll = false;
        search((false));
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvPreIn20;
        private TextView tvHumidity20;
        private TextView tvTemperature;
        private TextView tvHumidity;
        private TextView tvPreIn;
        private TextView tvPreOut;
        private TextView tvProId;
        private TextView tvBotLv;
        LinearLayout llTemperature;
        LinearLayout llHumidity;
        LinearLayout llPreIn;
        LinearLayout llPreOut;
        TextView tvPressureDiff;

        TextView tvStartTime;
        TextView tvEndTime;
        TextView tvItemIndex;

        LinearLayout llItem;
        ImageView ivSelectStatus;

        private ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvPreIn20 = itemView.findViewById(R.id.tv_in_pre_20);
            tvHumidity20 = itemView.findViewById(R.id.tv_shidu20);
            tvTemperature = itemView.findViewById(R.id.tv_temp);
            tvHumidity = itemView.findViewById(R.id.tv_shidu);
            tvPreIn = itemView.findViewById(R.id.tv_pre_in);
            tvPreOut = itemView.findViewById(R.id.tv_pre_out);
            llTemperature = itemView.findViewById(R.id.ll_temp);
            llHumidity = itemView.findViewById(R.id.ll_shidu);
            llPreIn = itemView.findViewById(R.id.ll_pre_in);
            llPreOut = itemView.findViewById(R.id.ll_pre_out);
            tvPressureDiff = itemView.findViewById(R.id.tv_yacha);
            tvStartTime = itemView.findViewById(R.id.tv_start_time);
            tvEndTime = itemView.findViewById(R.id.tv_end_time);
            tvItemIndex = itemView.findViewById(R.id.tv_item_index);
            tvProId = itemView.findViewById(R.id.tv_pro_id);
            tvBotLv = itemView.findViewById(R.id.tv_botelv);
            llItem = itemView.findViewById(R.id.ll_item);
            ivSelectStatus = itemView.findViewById(R.id.iv_select_status);
        }
    }

    public static class MyAdapter extends BaseAdapter {
        private Context mContext;
        private ThresholdBean bean;
        private boolean delStatus = false;
        private List<TestRecordsTotal> mDataList;
        private View.OnLongClickListener mOnLongClickListener;

        private void setDataList(List<TestRecordsTotal> mList) {
            if (mDataList == null) {
                mDataList = new ArrayList<>();
            }
            mDataList.clear();
            mDataList.addAll(mList);
            notifyDataSetChanged();
        }

        private void delSelected() {
            for (int i = mDataList.size() - 1; i >= 0; i--) {
                TestRecordsTotal t = mDataList.get(i);
                if (t.tagBackup == 1) {
                    KJDB.getDefaultInstance().deleteById(TestRecordsTotal.class, t.id);
                    mDataList.remove(i);
                }
            }
            this.delStatus = false;
            notifyDataSetChanged();
        }

        private void selAll() {
            for (TestRecordsTotal testRecordsTotal : mDataList) {
                testRecordsTotal.tagBackup = 1;
            }
            notifyDataSetChanged();
        }

        private void setDeleteStatus(boolean status) {
            this.delStatus = status;
            notifyDataSetChanged();
        }

        private void appendDataList(List<TestRecordsTotal> mList) {
            if (mDataList == null) {
                mDataList = new ArrayList<>();
            }
            mDataList.addAll(mList);
            notifyDataSetChanged();
        }

        private MyAdapter(Context context, List<TestRecordsTotal> mList, View.OnLongClickListener longClickListener) {
            this.mDataList = new ArrayList<>();
            mDataList.addAll(mList);
            mContext = context;

            bean = new ThresholdBean();
            bean.setTemperatureFloor("-40");
            bean.setTemperatureCeiling("65");
            bean.setHumidityFloor("0");
            bean.setHumidityCeiling("100");
            bean.setInnerPressureFloor("80");
            bean.setInnerPressureCeiling("150");
            bean.setOuterPressureFloor("80");
            bean.setOuterPressureCeiling("150");
            bean.setDiffPressureFloor("-20");
            bean.setDiffPressureCeiling("30");
            String bean2 = (String) SpUtil.get(context, Constant.THRESHOLD_KEY, "");
            if (!TextUtils.isEmpty(bean2)) {
                bean = new Gson().fromJson(bean2, ThresholdBean.class);
            }
            this.mOnLongClickListener = longClickListener;
        }

        private void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
            final TestRecordsTotal sensor = mDataList.get(i);
            DecimalFormat df = new DecimalFormat("0.00");
            viewHolder.tvHumidity20.setText(df.format(sensor.Hum20));
            viewHolder.tvPreIn20.setText(df.format(sensor.pressurein20));
            viewHolder.tvTemperature.setText(df.format(sensor.temp));
            viewHolder.tvHumidity.setText(df.format(sensor.Hum));
            viewHolder.tvPreIn.setText(df.format(sensor.pressurein));
            viewHolder.tvPreOut.setText(df.format(sensor.pressureout));
            viewHolder.tvPressureDiff.setText(df.format(sensor.pressure_yacha));

            String ids = String.valueOf(sensor.sensor_id);
            viewHolder.tvProId.setText(ids.length() < 5 ? "" : ids.substring(4, 5));
            viewHolder.tvBotLv.setText(sensor.botelv);
            viewHolder.tvStartTime.setVisibility(View.GONE);
            viewHolder.tvEndTime.setText(DateUtils.formatMilliesTimestamp(sensor.end_time, YYYY_MM_DD_HH_MM_SS));
            if (bean != null) {
                viewHolder.tvTemperature.setTextColor(Color.parseColor(sensor.temp > Float.parseFloat(bean.getTemperatureFloor()) && sensor.temp < Float.parseFloat(bean.getTemperatureCeiling()) ? "#333333" : "#F02323"));
                viewHolder.tvHumidity.setTextColor(Color.parseColor(sensor.Hum > Float.parseFloat(bean.getHumidityFloor()) && sensor.Hum < Float.parseFloat(bean.getHumidityCeiling()) ? "#333333" : "#F02323"));
                viewHolder.tvPreIn.setTextColor(Color.parseColor(sensor.pressurein > Float.parseFloat(bean.getInnerPressureFloor()) && sensor.pressurein < Float.parseFloat(bean.getInnerPressureCeiling()) ? "#333333" : "#F02323"));
                viewHolder.tvPreOut.setTextColor(Color.parseColor(sensor.pressureout > Float.parseFloat(bean.getOuterPressureFloor()) && sensor.pressureout < Float.parseFloat(bean.getOuterPressureCeiling()) ? "#333333" : "#F02323"));
                viewHolder.tvPressureDiff.setTextColor(Color.parseColor(sensor.pressure_yacha > Float.parseFloat(bean.getDiffPressureFloor()) && sensor.pressure_yacha < Float.parseFloat(bean.getDiffPressureCeiling()) ? "#333333" : "#F02323"));
            }
            viewHolder.llItem.setOnLongClickListener((View v) -> {
                if (mOnLongClickListener != null) {
                    mOnLongClickListener.onLongClick(v);
                }
                return false;
            });

            viewHolder.ivSelectStatus.setVisibility(this.delStatus ? View.VISIBLE : View.GONE);
            if (this.delStatus) {
                viewHolder.ivSelectStatus.setImageResource(sensor.tagBackup == 1 ? R.mipmap.ic_selected : R.mipmap.ic_default);
                viewHolder.llItem.setOnClickListener((View v) -> {
                    sensor.tagBackup = sensor.tagBackup == 0 ? 1 : 0;
                    notifyDataSetChanged();
                });
            } else {
                viewHolder.llItem.setOnClickListener(null);
            }
        }

        private int getItemCount() {
            return mDataList == null ? 0 : mDataList.size();
        }

        @Override
        public int getCount() {
            return getItemCount();
        }

        @Override
        public Object getItem(int position) {
            return mDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_history_detail_item, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            onBindViewHolder(viewHolder, position);
            return convertView;
        }

    }

    private void pickData(final int requestCode) {
        Calendar calendar2 = Calendar.getInstance();
        Log.e(logTag, ("startTime: " + start_time + ", end_time: " + end_time));
        calendar2.setTimeInMillis(requestCode == REQUEST_START_TIME ? start_time : end_time);

        new DatePickerDialog(this, (DatePicker view, int year, int month, int dayOfMonth) -> {
            Calendar calendar = Calendar.getInstance();
            long t = calendar.getTimeInMillis();
            if (requestCode == REQUEST_END_TIME) {
                calendar.set(year, month, dayOfMonth, 23, 59, 59);
                if (t == 0) {
                    Toast.makeText(HistoryDetailActivity.this, "请选择结束时间", Toast.LENGTH_SHORT).show();
                } else {
                    t = calendar.getTimeInMillis();
                    end_time = t;
                    SPUtils.getInstance(HistoryDetailActivity.this).put("search_history_end_time", end_time);
                }
                loadAll = false;

                search(false);
            } else if (requestCode == REQUEST_START_TIME) {
                calendar.set(year, month, dayOfMonth, 0, 0, 0);
                if (t == 0) {
                    Toast.makeText(HistoryDetailActivity.this, "请选择开始时间", Toast.LENGTH_SHORT).show();
                } else {
                    t = calendar.getTimeInMillis();
                    start_time = t;
                    SPUtils.getInstance(HistoryDetailActivity.this).put("search_history_start_time", start_time);
                }

                loadAll = false;
                search(false);
            }
        }, calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH), calendar2.get(Calendar.DAY_OF_MONTH)).show();
    }

    long start_time = 0;
    long end_time = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Log.d(logTag, ("result ok"));
        }
    }

    public long findStartId(long start_time, long end_time) {//查找perPageItems条
        if (start_time > end_time) return 0;

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(end_time);
        long startDatT = calendar.get(Calendar.DAY_OF_YEAR) + calendar.get(Calendar.YEAR) * 1000;
        List<TestRecordsTotal> t = KJDB.getDefaultInstance().findAllByWhere(TestRecordsTotal.class, "day_t = " + startDatT + " And sensor_id = " + mSensor.sensor_id, "end_time desc");
        long curId;
        if (t != null && t.size() > 0) {
            curId = t.get(0).id;
            for (int i = 1; i < t.size(); i++) {
                long tempId = t.get(i).id;
                if (curId < tempId) {
                    curId = tempId;
                }
            }

            return curId;
        }
        return findStartId(start_time, end_time - 24 * 3600000);
    }

    public TestRecordsTotal findNextItem(long start_time, long end_time) {
        if (startId <= 0) {
            return null;
        }
        TestRecordsTotal t = KJDB.getDefaultInstance().findById(startId, TestRecordsTotal.class);
        startId--;
        if (t != null) {
            if (t.end_time >= start_time && t.end_time <= end_time) {
                if (t.sensor_id != mSensor.sensor_id) {
                    return findNextItem(start_time, end_time);
                }
                return t;
            }
        } else {
            return findNextItem(start_time, end_time);
        }
        return null;
    }

    long startId = 0;
    boolean loadAll = false;

    private void search(boolean append) {
        if (!append) {
            startId = 0;
        }
        if (start_time >= end_time) {
            return;
        }
        tvStartTime.setText(DateUtils.formatMilliesTimestamp(start_time, YYYY_MM_DD));
        tvEndTime.setText(DateUtils.formatMilliesTimestamp(end_time, YYYY_MM_DD));
        if (startId == 0) {
            startId = findStartId(start_time, end_time);
        }
        List<TestRecordsTotal> testRecordsTotals = new ArrayList<>();
        boolean tagLoadMore = true;
        if (startId != 0) {
            for (int i = 0; i < PAGE_SIZE; i++) {
                TestRecordsTotal t = findNextItem(start_time, end_time);
                if (t != null) {
                    testRecordsTotals.add(t);
                }
            }
        }

        if (testRecordsTotals.size() < PAGE_SIZE) {
            tagLoadMore = false;
        }
        String curPageIndex = String.valueOf(currentPagedIndex + 1);
        etCurPage.setText(curPageIndex);
        mRecyclerView.setShowLoadMore(tagLoadMore);
        updateListView(testRecordsTotals, append);
        mRecyclerView.loadMoreComplete();
    }

    void updateListView(List<TestRecordsTotal> list, boolean append) {
        if (myAdapter == null) {
            myAdapter = new MyAdapter((this), list, (View v) -> {
                if (delStatus) {
                    return true;
                }

                delStatus = true;
                myAdapter.setDeleteStatus(true);
                llDeleteContent.setVisibility(View.VISIBLE);
                return false;

            });
            mRecyclerView.setAdapter(myAdapter);
        } else {
            if (append) {
                myAdapter.appendDataList(list);
            } else {
                myAdapter.setDataList(list);
            }
        }
    }
}

