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

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
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.mgq.base.utils.toast.ToastUtil;
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.base.C;
import com.tofly.ghrq_route.module.dasData.domain.DasData;
import com.tofly.ghrq_route.module.dasData.ui.adapter.DasDataAdapter;
import com.tofly.ghrq_route.module.sqlite.KmlUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;

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

import butterknife.BindView;
import butterknife.ButterKnife;

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

public class BottomSheetDasDataSelect extends LinearLayout {
    @BindView(R.id.bottom_sheet_detail_header)
    RelativeLayout bottomSheetDetailHeader;
    @BindView(R.id.btn_clear)
    TextView btnClear;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.layout_device_list_module)
    LinearLayout layoutDeviceModule;
    @BindView(R.id.layout_recycler_view)
    LinearLayout layoutRecyclerView;
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;
    @BindView(R.id.layout_select_file_hint)
    LinearLayout layoutSelectFileHint;
    @BindView(R.id.main_hint_text)
    TextView textMainHint;
    @BindView(R.id.layout_select_file)
    LinearLayout layoutSelectFile;

    private Context mContext;

    private List<DasData> mParsedDataList;

    private DasDataAdapter dasDataAdapter;

    private PhotoHelper photoHelper;

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

    private View.OnClickListener deviceClearListener;

    private OnDeviceAddListener deviceAddListener;

    public interface OnDeviceAddListener {
        void onDeviceAdded();
    }

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

    public int expand_state = BottomSheetBehavior.STATE_COLLAPSED;

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

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

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

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

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

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

    public void onDeviceAdded(OnDeviceAddListener deviceAddListener) {
        this.deviceAddListener = deviceAddListener;
    }

    public void setOnDeviceClearListener(OnClickListener listener) {
        this.deviceClearListener = listener;
    }

    public void onItemClicked(DasDataAdapter.OnItemClickListener onItemClickListener) {
        if (dasDataAdapter != null)
            dasDataAdapter.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_das_data_select, this);
        ButterKnife.bind(this);

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

    private void initListener() {
        layoutSelectFile.setOnClickListener(view -> {
            String kmlDocPath = C.dir.base;
            photoHelper.requestDocumentFile(kmlDocPath, (success, errStr, document) -> {
                if (success) {
                    String filePath = document.getPath();
                    readKmlFileData(filePath);
                }
            });
        });

        btnClear.setOnClickListener(view -> {
            clearDasData();
            if (deviceClearListener != null) {
                deviceClearListener.onClick(view);
            }
        });
    }

    public void clearDasData() {
        dasDataAdapter.clear();
        btnClear.setVisibility(GONE);
        layoutRecyclerView.setVisibility(View.GONE);
        layoutSelectFileHint.setVisibility(VISIBLE);
    }

    public void readKmlFileData(String kmlFile) {
        boolean isOk = parseKmlFile(kmlFile);
        if (isOk) {
            initBottomSheetDetail(mParsedDataList, true);
            if (deviceAddListener != null) {
                deviceAddListener.onDeviceAdded();
            }
        }else {
            ToastUtil.showToast(mContext, "未读取到管点设备信息");
        }
    }

    private boolean parseKmlFile(String kmlFile) {
        mParsedDataList = new ArrayList<>();
        KmlUtil.parseKml(kmlFile, mParsedDataList);
        return mParsedDataList.size() > 0;
    }

    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() {
                    BottomSheetDasDataSelect.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(PhotoHelper photoHelper) {
        this.photoHelper = photoHelper;
        initBottomSheetDetail(null, true);
    }

    public void initBottomSheetDetail(List<DasData> dataList, 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);
                                    expand_state = 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);
                                    expand_state = 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);
                                    expand_state = 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);
                    expand_state = BottomSheetBehavior.STATE_HALF_EXPANDED;
                }
            });
        }

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

        if ((dataList == null || dataList.isEmpty())) {
            layoutSelectFileHint.setVisibility(VISIBLE);
            btnClear.setVisibility(GONE);
        }else {
            layoutSelectFileHint.setVisibility(GONE);
            btnClear.setVisibility(VISIBLE);
        }

        setDasDataAdapter(dataList, selectable);
    }

    private void setDasDataAdapter(List<DasData> dataList, boolean selectable) {
        if (dataList == null || dataList.isEmpty()){
            layoutRecyclerView.setVisibility(View.GONE);
            return;
        }

        if (dasDataAdapter == null) {
            dasDataAdapter = new DasDataAdapter(dataList, mContext, selectable);
        }else {
            dasDataAdapter.setData(dataList);
        }
        recyclerView.setTotal(dataList.size());
        recyclerView.setAdapter(dasDataAdapter);
        layoutDeviceModule.setVisibility(View.VISIBLE);
        layoutRecyclerView.setVisibility(View.VISIBLE);
    }

    public List<DasData> getSelectedDasData() {
        List<DasData> dataList = new ArrayList<>();
        if (dasDataAdapter != null) {
            dataList = dasDataAdapter.getSelectedItems();
        }
        return dataList;
    }

    public List<DasData> getDasData() {
        List<DasData> dataList = new ArrayList<>();
        if (dasDataAdapter != null) {
            dataList = dasDataAdapter.getAllItem();
        }
        return dataList;
    }
}
