package com.joe.print.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.joe.print.R;
import com.joe.print.R2;
import com.joe.print.di.component.DaggerPrintListComponent;
import com.joe.print.mvp.contract.PrintListContract;
import com.gingersoft.gsa.cloud.base.common.bean.PrinterManger.PrinterManager;
import com.joe.print.mvp.presenter.PrintListPresenter;
import com.joe.print.mvp.ui.adapter.PrinterListAdapter;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.touch.OnItemStateChangedListener;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import java.util.Collections;
import java.util.List;

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

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/16/2020 10:24
 * <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 PrinterListActivity extends BaseActivity<PrintListPresenter> implements PrintListContract.View {

    @BindView(R2.id.rc_print_list)
    SwipeRecyclerView mRvPrintList;
    @BindView(R2.id.printer_home_bar)
    QMUITopBar topBar;

    private PrinterListAdapter printListAdapter;

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

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.printer_activity_list; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        mPresenter.getPrinterList(GsaCloudApplication.getRestaurantId(mContext));
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getPrinterList(GsaCloudApplication.getRestaurantId(mContext));
    }

    /**
     * 創建右側刪除按鈕
     */
    private SwipeMenuCreator mSwipeMenuCreator = (swipeLeftMenu, swipeRightMenu, position) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        // 添加右侧的按鈕。
        SwipeMenuItem deleteItem = new SwipeMenuItem(mContext).setBackground(
                R.color.theme_color)
//                        .setImage(R.drawable.ic_action_delete)
                .setText("刪除")
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。
    };

    /**
     * Item的拖拽/侧滑删除时，手指状态发生变化监听。
     */
    private OnItemStateChangedListener mOnItemStateChangedListener = (viewHolder, actionState) -> {
        if (actionState == OnItemStateChangedListener.ACTION_STATE_DRAG) {
//                mActionBar.setSubtitle("状态：拖拽");
//                // 拖拽的时候背景就透明了，这里我们可以添加一个特殊背景。
            viewHolder.itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_ccc));
        } else if (actionState == OnItemStateChangedListener.ACTION_STATE_SWIPE) {
//                mActionBar.setSubtitle("状态：滑动删除");
        } else if (actionState == OnItemStateChangedListener.ACTION_STATE_IDLE) {
//                mActionBar.setSubtitle("状态：手指松开");
            // 在手松开的时候还原背景。
            ViewCompat.setBackground(viewHolder.itemView,
                    ContextCompat.getDrawable(mContext, R.color.white));
        }
    };

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {
        topBar.setTitle("打印設置");
        topBar.setBackgroundColor(getResources().getColor(R.color.theme_color));
        topBar.addLeftImageButton(R.drawable.icon_white_back, R.id.iv_left_back).setOnClickListener(v -> finish());
        topBar.addRightImageButton(R.drawable.ic_add, R.id.printer_add).setOnClickListener(v -> startActivity(new Intent(mContext, PrinterAddActivity.class)));
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

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

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

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    public void loadPrinterList(List<PrinterDeviceBean> deviceBeans) {
        PrinterManager.getPrinterManager().setDeviceBeans(deviceBeans);
        if (printListAdapter == null) {
            printListAdapter = new PrinterListAdapter(deviceBeans, mContext);
            mRvPrintList.setLayoutManager(new LinearLayoutManager(this));
            //分割线
            mRvPrintList.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(this, R.color.line_color)));
            mRvPrintList.setOnItemClickListener((view, adapterPosition) -> {
                //打開打印機詳情
                Intent intent = new Intent(mContext, PrinterAddActivity.class);
                intent.putExtra("printerInfo", deviceBeans.get(adapterPosition));
                startActivity(intent);
            });
            //menu 右侧菜單點擊事件
            mRvPrintList.setOnItemMenuClickListener((menuBridge, position) -> {
                menuBridge.closeMenu();
                mPresenter.deletePrinter(deviceBeans.get(position).getId() + "");
                deviceBeans.remove(position);
                printListAdapter.notifyItemRemoved(position);
            }); // Item的Menu点击。

            mRvPrintList.setSwipeMenuCreator(mSwipeMenuCreator); // 菜单创建器。

            mRvPrintList.setOnItemStateChangedListener(mOnItemStateChangedListener); // 监听Item的手指状态，拖拽、侧滑、松开。
            mRvPrintList.setLongPressDragEnabled(true); // 长按拖拽，默认关闭。

            mRvPrintList.setOnItemMoveListener(new OnItemMoveListener() {
                @Override
                public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                    // 不同的ViewType不能拖拽换位置。
                    if (srcHolder.getItemViewType() != targetHolder.getItemViewType()) return false;
                    // 真实的Position：通过ViewHolder拿到的position都需要减掉HeadView的数量。
                    int fromPosition = srcHolder.getAdapterPosition() - mRvPrintList.getHeaderCount();
                    int toPosition = targetHolder.getAdapterPosition() - mRvPrintList.getHeaderCount();

                    if (fromPosition < toPosition) {
                        for (int i = fromPosition; i < toPosition; i++) {
                            Collections.swap(deviceBeans, i, i + 1);
                        }
                    } else {
                        for (int i = fromPosition; i > toPosition; i--) {
                            Collections.swap(deviceBeans, i, i - 1);
                        }
                    }
                    printListAdapter.notifyItemMoved(fromPosition, toPosition);
                    return true;// 返回true表示处理了，返回false表示你没有处理。
                }

                @Override
                public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
//                int adapterPosition = srcHolder.getAdapterPosition();
//                int position = adapterPosition - mRvPrintList.getHeaderCount();
                }
            });// 监听拖拽和侧滑删除，更新UI和数据源。
            mRvPrintList.setAdapter(printListAdapter);
        } else {
            printListAdapter.notifyData(deviceBeans);
        }
    }
}
