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

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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 com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
import com.joe.print.mvp.print.PrinterManger.PrinterManager;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.database.utils.PrinterDeviceDaoUtils;
import com.gingersoft.gsa.cloud.common.ui.utils.AppDialog;
import com.jess.arms.base.BaseFragment;
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.DaggerIpPrintListActivityComponent;
import com.joe.print.di.module.IpPrintListActivityModule;
import com.joe.print.mvp.contract.IpPrintListActivityContract;
import com.joe.print.mvp.presenter.IpPrintListActivityPresenter;
import com.joe.print.mvp.ui.activity.PrinterAddActivity;
import com.joe.print.mvp.ui.adapter.PrinterListAdapter;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.touch.OnItemStateChangedListener;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

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


public class IpPrintListActivityFragment extends BaseFragment<IpPrintListActivityPresenter> implements IpPrintListActivityContract.View, View.OnClickListener {

    @BindView(R2.id.rc_ip_print)
    SwipeRecyclerView mRvPrintList;
    private PrinterListAdapter printListAdapter;
    @BindView(R2.id.btn_default)
    QMUIAlphaButton mTvAddPrint;

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

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mTvAddPrint.setText("+添加打印機");
        mPresenter.getModelList(ResturantInfoManager.newInstance().getRestaurantId());
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getPrinterList(ResturantInfoManager.newInstance().getRestaurantId());
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {#setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {#setData(Object)} 方法时 {还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link (Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 { #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @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() {

    }

    /**
     * 創建右側刪除按鈕
     */
    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));
        }
    };


    private List<PrinterDeviceBean> devicess;

    @Override
    public void loadPrinterList(List<PrinterDeviceBean> deviceBeans) {
        PrinterDeviceDaoUtils printerDeviceDaoUtils = new PrinterDeviceDaoUtils(_mActivity);
        printerDeviceDaoUtils.deleteAll();
        if (deviceBeans != null) {
            printerDeviceDaoUtils.insertMultPrinterDeviceBean(deviceBeans);
        }

        mRvPrintList.setVisibility(View.VISIBLE);
        mTvAddPrint.setVisibility(View.GONE);

        PrinterManager.getPrinterManager().setDeviceBeans(deviceBeans);
        devicess = deviceBeans;

        if (printListAdapter == null) {
            mRvPrintList.setOnItemClickListener((view, adapterPosition) -> {
                //item點擊事件 打開打印機詳情
                startToEditPrint(adapterPosition);
            });
            //Menu 右侧菜單點擊事件
//            mRvPrintList.setOnItemMenuClickListener((menuBridge, position) -> {
//                //刪除按鈕點擊事件
//                menuBridge.closeMenu();
//                //調用刪除接口
//                mPresenter.deletePrinter(devicess.get(position).getId() + "");
//                if (printListAdapter.getSelectPosition() == position) {
//                    //如果刪除的是當前選中的默認打印機，那麼移除默認打印機
//                    SPUtils.remove(mContext, PrintConstans.DEFAULT_PRINT_IP);
//                    SPUtils.remove(mContext, PrintConstans.DEFAULT_PRINT_PORT);
//                    SPUtils.remove(mContext, PrintConstans.DEFAULT_PRINT_PAPER);
//                    printListAdapter.setSelectPosition(-1);
//                }
//                devicess.remove(position);
//                printListAdapter.notifyItemRemoved(position);
//            });
            // Item的Menu点击。
            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(devicess, i, i + 1);
                        }
                    } else {
                        for (int i = fromPosition; i > toPosition; i--) {
                            Collections.swap(devicess, 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和数据源。
            printListAdapter = new PrinterListAdapter(devicess, mContext);
            printListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.layout_delete) {
                    new AppDialog().showWaringDialog(mContext, "是否刪除打印機", (view1, dialog) -> {
                        //調用刪除接口
                        mPresenter.deletePrinter(devicess.get(position).getId() + "");
                        devicess.remove(position);
                        printListAdapter.notifyItemRemoved(position);
                        dialog.dismiss();
                        if (devicess == null || devicess.size() == 0) {
                            mTvAddPrint.setVisibility(View.VISIBLE);
                        } else {
                            mTvAddPrint.setVisibility(View.GONE);
                        }
                    });
                }
            });
            mRvPrintList.setLayoutManager(new LinearLayoutManager(mContext));
            //分割线
            mRvPrintList.setSwipeMenuCreator(mSwipeMenuCreator); // 菜单创建器。
            mRvPrintList.setAdapter(printListAdapter);
        } else {
            printListAdapter.notifyData(devicess);
        }
    }

    public void startToEditPrint(int adapterPosition) {
        Intent intent = new Intent(mContext, PrinterAddActivity.class);
        intent.putExtra("printer_position", adapterPosition);
        intent.putExtra("printList", (Serializable) devicess);
        if (mPresenter.getPrintModelBeans() != null) {
            intent.putExtra("printModelList", (Serializable) mPresenter.getPrintModelBeans());
        }
        startActivity(intent);
    }

    @Override
    public void loadFile() {
        mRvPrintList.setVisibility(View.GONE);
        mTvAddPrint.setVisibility(View.VISIBLE);
    }

    @OnClick(R2.id.btn_default)
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_default) {
            startToEditPrint(-1);
        }
    }
}
