package com.gingersoft.gsa.cloud.manager.mvp.ui.fragment;

import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.manager.R2;
import com.gingersoft.gsa.cloud.base.common.bean.TableArea;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.AreaRequest;
import com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity;
import com.gingersoft.gsa.cloud.manager.mvp.ui.adapter.AreaManageAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.recylcler.event.OnRecyclerItemClickListener;
import com.gingersoft.gsa.cloud.ui.recylcler.event.RecyItemTouchHelperCallback;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.gingersoft.gsa.cloud.manager.di.component.DaggerAreaListComponent;
import com.gingersoft.gsa.cloud.manager.mvp.contract.AreaListContract;
import com.gingersoft.gsa.cloud.manager.mvp.presenter.AreaListPresenter;

import com.gingersoft.gsa.cloud.manager.R;
import com.jess.arms.utils.KeyboardChangeHelper;
import com.qmuiteam.qmui.alpha.QMUIAlphaFrameLayout;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/19/2020 12:26
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class AreaListFragment extends BaseFragment<AreaListPresenter> implements AreaListContract.View {

    @BindView(R2.id.topbar)
    QMUITopBarLayout mTopBar;
    @BindView(R2.id.recycler_area)
    RecyclerView recycler_area;
    @BindView(R2.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;

    @BindView(R2.id.fl_add_area)
    QMUIAlphaFrameLayout fl_add_area;
    @BindView(R2.id.ll_add_area_layout)
    LinearLayout ll_add_area_layout;
    @BindView(R2.id.ll_bottom_operat)
    LinearLayout ll_bottom_operat;

    @BindView(R2.id.ed_area_name)
    EditText ed_area_name;
    @BindView(R2.id.cb_all_select)
    CheckBox cb_all_select;

    private TableManageActivity mActivity;

    private AreaManageAdapter mAreaManageAdapter;
    private List<TableArea> mTableAreaList = new ArrayList<>();

    private Button rightButton;

    private boolean isSave = false;
    private boolean isRadioEdit;

    public static AreaListFragment newInstance() {
        AreaListFragment fragment = new AreaListFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerAreaListComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mActivity = (TableManageActivity) _mActivity;

        initTopbar();
        initAdapter();
        initRefreshLayout();
        mActivity.queryAreas(null);

        cb_all_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (int i = 0; i < mTableAreaList.size(); i++) {
                    mTableAreaList.get(i).setChecked(isChecked);
                }
                mAreaManageAdapter.notifyDataSetChanged();
            }
        });
        setKeyboardChange();
    }

    private void setKeyboardChange() {
        View view = getView();
        if (view != null) {
            KeyboardChangeHelper changeHelper = new KeyboardChangeHelper(view);
            changeHelper.addListener();
            changeHelper.addOnKeyboardShowListener(new KeyboardChangeHelper.OnKeyboardShowListener() {
                @Override
                public void onKeyboardShow() {
//                    fl_add_area.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onKeyboardHide() {
//                    fl_add_area.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    private void initTopbar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> killMyself());
        mTopBar.setBackgroundResource(R.color.theme_color);
        mTopBar.setTitle("區域").setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));
        rightButton = mTopBar.addRightTextButton("編輯", R.id.qmui_dialog_edit_right_icon);
        rightButton.setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));
        rightButton.setOnClickListener(v -> {
            clickEdit(rightButton);
        });
    }

    private void clickEdit(Button rightButton) {
        isRadioEdit = !isRadioEdit;
        if (isRadioEdit) {
            fl_add_area.setVisibility(View.INVISIBLE);
            initCheckedStatus();
            rightButton.setText("取消");
        } else {
            fl_add_area.setVisibility(View.VISIBLE);
            rightButton.setText("編輯");
        }
        showRadioEdit();
        mAreaManageAdapter.setRadioEdit(isRadioEdit);
        mAreaManageAdapter.notifyDataSetChanged();
    }

    private void initRefreshLayout() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mActivity.queryAreas(refreshLayout);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {

            }
        });

        RecyItemTouchHelperCallback itemTouchHelperCallback = new RecyItemTouchHelperCallback(mAreaManageAdapter);
        final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);
        itemTouchHelper.attachToRecyclerView(recycler_area);

        recycler_area.addOnItemTouchListener(new OnRecyclerItemClickListener(recycler_area) {

            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder) {
            }

            @Override
            public void onLongClick(RecyclerView.ViewHolder viewHolder) {
//                AreaManageAdapter.TopTableAreaItemHolder viewHolder1 = (AreaManageAdapter.TopTableAreaItemHolder) viewHolder;
//                Toast.makeText(mActivity, "長按：" + viewHolder1.getAdapterPosition(), Toast.LENGTH_SHORT).show();
//                if (viewHolder.getLayoutPosition() != 0) {
//                    itemTouchHelper.startDrag(viewHolder);
//                }
            }
        });
        itemTouchHelperCallback.setOnMoveListener(new RecyItemTouchHelperCallback.onMoveListener() {

            @Override
            public void onMoveFinish(String ids) {
                mActivity.changeAreaSort(ids);
            }
        });
    }

    private void initAdapter() {
        mAreaManageAdapter = new AreaManageAdapter(mContext, mTableAreaList);
        recycler_area.setAdapter(mAreaManageAdapter);
        recycler_area.addItemDecoration(new DividerItemDecoration(_mActivity, LinearLayoutManager.VERTICAL));
        mAreaManageAdapter.setOnItemClickListener(new DefaultAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {
            }
        });
        mAreaManageAdapter.addTextChangedListener(new AreaManageAdapter.OnTextChangedListener() {

            @Override
            public void afterTextChanged(TableArea datasBean, String name) {
                mActivity.updateArea(createUpateAreaRequest(datasBean.getId(), name));
            }
        });
    }

    public void updateAreaData(List<TableArea> tableAreaList) {
        if (mTableAreaList.size() > 0) {
            mTableAreaList.clear();
        }
        mTableAreaList.addAll(tableAreaList);
        mAreaManageAdapter.notifyDataSetChanged();

        mEmptyView.hide();
        recycler_area.setVisibility(View.VISIBLE);
    }

    public void addSuccess() {
        ed_area_name.setText("");
    }

    public void deleteSuccess() {
        clickEdit(rightButton);
    }

    @Override
    public void setData(@Nullable Object data) {
    }

    private void initCheckedStatus() {
        for (int i = 0; i < mTableAreaList.size(); i++) {
            mTableAreaList.get(i).setChecked(false);
        }
        mAreaManageAdapter.notifyDataSetChanged();
    }

    @OnClick(R2.id.fl_add_area)
    void onClickAddArea() {
        if (ll_add_area_layout.getVisibility() == View.GONE) {
            ll_add_area_layout.setVisibility(View.VISIBLE);
        } else {
            ll_add_area_layout.setVisibility(View.GONE);
        }
    }

    @OnClick(R2.id.btn_save_area)
    void onClickSaveArea() {
        if (addCondition()) {
            mActivity.addArea(createAddAreaRequest());
        }
    }

//    @OnClick(R2.id.btn_save)
//    void onClickSaveModify() {
//        mActivity.updateArea(createUpateAreaRequest(datasBean.getId(), name));
//    }

    @OnClick(R2.id.btn_sure)
    void onClickSure() {
        String ids = getDeleteIds();
        if (TextUtils.isEmpty(ids)) {
            showMessage("請選擇區域");
            return;
        }
        Class[] parameterTypes = {String.class};
        Object[] parameters = {ids};
        CommonTipDialog.showSurpisedDialog(mActivity, "是否刪除所選區域", TableManageActivity.class, mActivity, "deleteArea", parameterTypes, parameters);
    }

    private String getDeleteIds() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < mTableAreaList.size(); i++) {
            TableArea tableArea = mTableAreaList.get(i);
            if (tableArea.isChecked()) {
                builder.append(tableArea.getId());
                builder.append(",");
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(mContext, message, true);
        else
            LoadingDialog.showDialogForLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(mContext, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        _mActivity.onBackPressed();
    }

    private View.OnClickListener onRetryClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //重新加載
            mActivity.queryAreas(null);
        }
    };

    @Override
    public void showEmptyView(boolean isSuccess, int size, Throwable t) {
        if (t != null) {
            if (t instanceof UnknownHostException) {
                //沒有網絡
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof SocketTimeoutException) {
                //請求超時
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
                //數據解析錯誤
                mEmptyView.show(false, getResources().getString(R.string.response_error_data_parsing_error), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else {
                //其他error
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            }
            recycler_area.setVisibility(View.INVISIBLE);
            return;
        }
        if (!isSuccess) {
            mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            recycler_area.setVisibility(View.INVISIBLE);
            return;
        }
        if (size == 0) {
            mEmptyView.show(getResources().getString(R.string.emptyView_mode_desc_double), null);
            recycler_area.setVisibility(View.INVISIBLE);
            return;
        }
        mEmptyView.hide();
        recycler_area.setVisibility(View.VISIBLE);
    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {
        recycler_area.setAdapter(adapter);
    }

    public boolean addCondition() {
        if (TextUtils.isEmpty(ed_area_name.getText().toString())) {
            showMessage("請輸入區域名稱");
            return false;
        }
        for (int i = 0; i < mTableAreaList.size(); i++) {
            TableArea tableArea = mTableAreaList.get(i);
            if (tableArea.getRegionName().equals(ed_area_name.getText().toString())) {
                showMessage("已有相同區域!");
                return false;
            }
        }
        return true;
    }

    public AreaRequest.Add createAddAreaRequest() {
        int restaurantId = GsaCloudApplication.getRestaurantId(mContext);
        AreaRequest.Add areaRequest = new AreaRequest.Add();
        areaRequest.setRestaurantId(restaurantId);
        areaRequest.setRegionName(ed_area_name.getText().toString());
//        areaRequest.setSort(Integer.parseInt(ed_area_sort.getText().toString()));
        return areaRequest;
    }

    public AreaRequest.Update createUpateAreaRequest(int id, String name) {
        AreaRequest.Update areaRequest = new AreaRequest.Update();
        areaRequest.setId(id);
        areaRequest.setRegionName(name);
//        areaRequest.setSort(Integer.parseInt(ed_area_sort.getText().toString()));
        return areaRequest;
    }

    private void showRadioEdit() {
        if (isRadioEdit) {
            fl_add_area.setVisibility(View.GONE);
            ll_bottom_operat.setVisibility(View.VISIBLE);
        } else {
            fl_add_area.setVisibility(View.VISIBLE);
            ll_bottom_operat.setVisibility(View.GONE);
        }
    }

    public boolean isRadioEdit() {
        return isRadioEdit;
    }
}
