package com.tofly.ghrq_route.module.trouble.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.module.trouble.domain.AttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.DeviceAttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.PipeAttributesBean;
import com.tofly.ghrq_route.module.trouble.ui.adapter.TroubleAnalyzeDeviceAdapter;
import com.tofly.ghrq_route.module.trouble.ui.adapter.TroubleAnalyzePiepAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Amu on 2017/2/21.
 */

public class BottomSheetTroubleDeviceSelect extends LinearLayout {
    @BindView(R.id.bottom_sheet_detail_header)
    RelativeLayout bottomSheetDetailHeader;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.layout_device_list_module)
    LinearLayout layoutDeviceModule;
    @BindView(R.id.layout_pipe_recycler_view)
    LinearLayout layoutPipeRecyclerView;
    @BindView(R.id.recycler_view_pipe)
    ARecycleView recyclerViewPipe;
    @BindView(R.id.edit_pipe_note)
    EditText editPipeNote;
    @BindView(R.id.layout_device_recycler_view)
    LinearLayout layoutDeviceRecyclerView;
    @BindView(R.id.recycler_view_device)
    ARecycleView recyclerViewDevice;
    @BindView(R.id.edit_device_note)
    EditText editDeviceNote;
    @BindView(R.id.main_hint_text)
    TextView textMainHint;

    private Context mContext;

    private TroubleAnalyzePiepAdapter pipeResultAdapter;

    private TroubleAnalyzeDeviceAdapter deviceResultAdapter;

    private BottomSheetBehavior bottomSheetBehavior = null;
    private boolean isBottomSheetDetailShow = false;
    private boolean isDialogMode = false;

    final int BOTTOM_SHEET_BOTTOM = BaseApp.dip2px(56);
    final int BOTTOM_SHEET_MIDDLE = BaseApp.dip2px(350);
    int BOTTOM_SHEET_TOP = ViewGroup.LayoutParams.MATCH_PARENT;

    public BottomSheetTroubleDeviceSelect(Context context) {
        this(context, null);
    }

    public BottomSheetTroubleDeviceSelect(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomSheetTroubleDeviceSelect(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;
        BOTTOM_SHEET_TOP = BaseUi.getDialogHeight(mContext) - BaseApp.dip2px(60);
        initAttrs(attrs);
        initView();
        initListener();
    }

    public void setEditable(boolean editable) {
        btnConfirm.setVisibility(editable ? VISIBLE : GONE);
    }

    public void onDeviceSelectConfirm(OnClickListener onClickListener) {
        btnConfirm.setOnClickListener(onClickListener);
    }

    public void onDeviceItemClicked(TroubleAnalyzeDeviceAdapter.OnItemClickListener onItemClickListener) {
        if (deviceResultAdapter != null)
            deviceResultAdapter.setOnItemClickListener(onItemClickListener);
    }

    public void onPipeItemClicked(TroubleAnalyzePiepAdapter.OnItemClickListener onItemClickListener) {
        if (pipeResultAdapter != null)
            pipeResultAdapter.setOnItemClickListener(onItemClickListener);
    }

    public boolean isBottomSheetDetailShowing() {
        return isBottomSheetDetailShow;
    }


    private void initAttrs(AttributeSet attrs){
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BottomSheetRepairDetail);
        try {
            isDialogMode = typedArray.getBoolean(R.styleable.BottomSheetRepairDetail_DialogMode, false);
        }finally {
            typedArray.recycle();
        }
    }

    private void initView() {
        inflate(mContext, R.layout.layout_bottom_sheet_trouble_device_select, this);
        ButterKnife.bind(this);

        RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerViewPipe.setLayoutManager(linearLayoutManager);
        recyclerViewPipe.setItemAnimator(new DefaultItemAnimator());

        linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerViewDevice.setLayoutManager(linearLayoutManager);
        recyclerViewDevice.setItemAnimator(new DefaultItemAnimator());
    }

    private void initListener() {

    }

    public void hideSelf() {
        isBottomSheetDetailShow = false;
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) this.getLayoutParams();
        if (layoutParams.height == BOTTOM_SHEET_TOP) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            this.postDelayed(new Runnable() {
                @Override
                public void run() {
                    BottomSheetTroubleDeviceSelect.this.setVisibility(View.INVISIBLE);
                }
            }, 50);
        } else {
            this.setVisibility(View.INVISIBLE);
        }
    }

    public void setBottomDetailState(@BottomSheetBehavior.State int state) {
        if (bottomSheetBehavior != null) {
            if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED
                    && state == BottomSheetBehavior.STATE_COLLAPSED) {
                bottomSheetBehavior.setState(state);
            } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED
                    && state == BottomSheetBehavior.STATE_EXPANDED) {
                bottomSheetBehavior.setState(state);
            }
        }
    }

    public void initBottomSheetDetail(List<PipeAttributesBean> pipeFeatures, List<DeviceAttributesBean> deviceFeatures) {
        initBottomSheetDetail(pipeFeatures, null, deviceFeatures, null, true);
    }

    public void initBottomSheetDetail(List<PipeAttributesBean> pipeFeatures, String pipeDesc,
                                      List<DeviceAttributesBean> deviceFeatures, String deviceDesc, boolean selectable) {
        isBottomSheetDetailShow = true;

        if (isDialogMode) {
            bottomSheetDetailHeader.setOnClickListener(null);
        }

        if (!isDialogMode) {
            CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) this.getLayoutParams();
            layoutParams.height = BOTTOM_SHEET_MIDDLE;
            setLayoutParams(layoutParams);
            bottomSheetBehavior = BottomSheetBehavior.from(this);

            bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);

            final float[] offset = {0};
            bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                @Override
                public void onStateChanged(@NonNull View bottomSheet, int newState) {
                    CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomSheet.getLayoutParams();
                    switch (newState) {
                        case BottomSheetBehavior.STATE_DRAGGING:
                            layoutParams.height = BOTTOM_SHEET_TOP;
                            bottomSheet.setLayoutParams(layoutParams);
                            break;
                        case BottomSheetBehavior.STATE_COLLAPSED:
                            break;
                        case BottomSheetBehavior.STATE_SETTLING:
                            if (offset[0] >= 0 && offset[0] <= 1) {
                                if (offset[0] > 0.7 && offset[0] < 1) {
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
                                    layoutParams.height = BOTTOM_SHEET_TOP;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                                } else if (offset[0] > 0.35 && offset[0] < 0.7) {
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
                                    layoutParams.height = BOTTOM_SHEET_MIDDLE;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HALF_EXPANDED);
                                } else if (offset[0] != 0) {
                                    bottomSheetBehavior.setPeekHeight(BOTTOM_SHEET_BOTTOM);
                                    layoutParams.height = BOTTOM_SHEET_MIDDLE;
                                    bottomSheet.setLayoutParams(layoutParams);
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                                }
                            }
                            break;
                        case BottomSheetBehavior.STATE_EXPANDED:
                            break;
                    }
                }

                @Override
                public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                    offset[0] = slideOffset;
                }
            });

            bottomSheetDetailHeader.setOnClickListener(view -> {
                if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
            });
        }

        if (pipeResultAdapter != null) {
            pipeResultAdapter.cancelSelected();
            pipeResultAdapter.clear();
        }

        editPipeNote.setText("");
        if (pipeDesc != null && !pipeDesc.isEmpty()) {
            editPipeNote.setText(pipeDesc);
        }
        if (!selectable && editPipeNote.getText().toString().isEmpty()) {
            editPipeNote.setHint("");
        }
        editPipeNote.setEnabled(selectable);


        if (deviceResultAdapter != null) {
            deviceResultAdapter.cancelSelected();
            deviceResultAdapter.clear();
        }
        editDeviceNote.setText("");
        if (deviceDesc != null && !deviceDesc.isEmpty()) {
            editDeviceNote.setText(deviceDesc);
        }
        if (!selectable && editDeviceNote.getText().toString().isEmpty()) {
            editDeviceNote.setHint("");
        }
        editDeviceNote.setEnabled(selectable);

        if ((pipeFeatures == null || pipeFeatures.isEmpty())
                && (deviceFeatures == null || deviceFeatures.isEmpty())) {
            textMainHint.setVisibility(VISIBLE);
        }else {
            textMainHint.setVisibility(GONE);
        }

        setPipeAnalyzeResultAdapter(pipeFeatures, selectable);
        setDeviceAnalyzeResultAdapter(deviceFeatures, selectable);
    }

    public void setPipeDesc(String pipeDesc) {
        editPipeNote.setText(pipeDesc);
    }

    public void setDeviceDesc(String deviceDesc) {
        editDeviceNote.setText(deviceDesc);
    }

    private void setPipeAnalyzeResultAdapter(List<PipeAttributesBean> features, boolean selectable) {
        if (features == null || features.isEmpty()){
            layoutPipeRecyclerView.setVisibility(View.GONE);
            return;
        }

        if (pipeResultAdapter == null) {
            pipeResultAdapter = new TroubleAnalyzePiepAdapter(features, mContext, selectable);
        }else {
            pipeResultAdapter.setData(features);
        }
        recyclerViewPipe.setTotal(features.size());
        recyclerViewPipe.setAdapter(pipeResultAdapter);
        layoutDeviceModule.setVisibility(View.VISIBLE);
        layoutPipeRecyclerView.setVisibility(View.VISIBLE);
    }

    private void setDeviceAnalyzeResultAdapter(List<DeviceAttributesBean> features, boolean selectable) {
        if (features == null || features.isEmpty()){
            layoutDeviceRecyclerView.setVisibility(View.GONE);
            return;
        }

        if (deviceResultAdapter == null) {
            deviceResultAdapter = new TroubleAnalyzeDeviceAdapter(features, mContext, selectable);
        }else {
            deviceResultAdapter.setData(features);
        }
        recyclerViewDevice.setTotal(features.size());
        recyclerViewDevice.setAdapter(deviceResultAdapter);
        layoutDeviceModule.setVisibility(View.VISIBLE);
        layoutDeviceRecyclerView.setVisibility(View.VISIBLE);
    }

    public List<PipeAttributesBean> getSelectedPipeFeatures() {
        List<PipeAttributesBean> pipeFeatures = new ArrayList<>();
        if (pipeResultAdapter != null) {
            List<AttributesBean> features = pipeResultAdapter.getSelectedItems();
            for (AttributesBean feature : features) {
                PipeAttributesBean attributesBean = (PipeAttributesBean) feature;
                pipeFeatures.add(attributesBean);
            }
        }
        return pipeFeatures;
    }

    public List<DeviceAttributesBean> getSelectedDeviceFeatures() {
        List<DeviceAttributesBean> deviceFeatures = new ArrayList<>();
        if (deviceResultAdapter != null) {
            List<AttributesBean> features = deviceResultAdapter.getSelectedItems();
            for (AttributesBean feature : features) {
                DeviceAttributesBean attributesBean = (DeviceAttributesBean) feature;
                deviceFeatures.add(attributesBean);
            }
        }
        return deviceFeatures;
    }

    public String getPipeNote() {
        return editPipeNote.getText().toString();
    }

    public String getDeviceNote() {
        return editDeviceNote.getText().toString();
    }
}
