package com.gingersoft.supply_chain.mvp.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.gingersoft.gsa.cloud.common.utils.XPermissionUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.qrcode.core.BarcodeType;
import me.yokeyword.fragmentation.SupportHelper;

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/3/18
 * Time: 17:23
 * Use: 掃描sn碼
 */
public class ScanSnView extends FrameLayout {

    private List<String> snCodes;
    private ScanSnPopup.OnScanResultListener onScanResultListener;

    @BindView(R2.id.rv_sn_code)
    RecyclerView rvSnCode;
    @BindView(R2.id.btn_confirm_sn)
    QMUIAlphaButton btnFoodIngredientsConfirm;
    @BindView(R2.id.btn_cancel_sn)
    QMUIAlphaButton btnFoodIngredientsCancel;
    @BindView(R2.id.ed_input_sn)
    EditText edInputSn;
    @BindView(R2.id.iv_scan_sn)
    QMUIAlphaImageButton btnScanSn;
    @BindView(R2.id.tv_submit_sn)
    QMUIAlphaTextView tvSubmitSn;
    private Fragment fragment;

    private OnCancelListener onCancelListener;
    private OnSingerResultListener onSingerResultListener;

    public ScanSnView(Fragment fragment, List<String> snCodes, OnSingerResultListener onSingerResultListener, ScanSnPopup.OnScanResultListener onScanResultListener) {
        super(fragment.requireContext());
        this.snCodes = snCodes;
        this.onScanResultListener = onScanResultListener;
        this.fragment = fragment;
        this.onSingerResultListener = onSingerResultListener;
        init();
    }

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

    public ScanSnView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public ScanSnView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.layout_scan_sn, this, false);
        ButterKnife.bind(this, rootView);

//初始化adapter
        SnCodeAdapter adapter = new SnCodeAdapter(R.layout.item_sn_code, snCodes);
        rvSnCode.setAdapter(adapter);
        //掃描sn媽
        btnScanSn.setOnClickListener(v ->
                XPermissionUtils.launchCamera(fragment, (allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        //去掃碼頁面
                        CC.obtainBuilder(ComponentName.COMPONENT_SCAN)
                                .setActionName("openScanActivity")
                                .addParam("scanMode", BarcodeType.ONE_DIMENSION)
                                .build()
                                .callAsyncCallbackOnMainThread((cc, result) -> {
                                    Object qrCodeResult = result.getDataItem("qrCodeResult");
                                    if (qrCodeResult != null) {
                                        String snCode = String.valueOf(qrCodeResult);
                                        if (adapter.getData().contains(snCode)) {
                                            ToastUtils.show(getContext(), "商品已存在，不能重複添加");
                                        } else {
                                            adapter.addData(snCode);
                                            onSingerResultListener.onScanValue(true, snCode, adapter.getItemCount());
                                        }
                                    }
                                });
                    }
                })
        );
        edInputSn.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                //響應回車按鈕
                //隐藏软键盘
                SupportHelper.hideSoftInput(v);
                commitSnCode(adapter);
            }
            return false;
        });
        //提交按鈕
        tvSubmitSn.setOnClickListener(v -> {
            //提交輸入框中的sn碼
            commitSnCode(adapter);
        });

        btnFoodIngredientsConfirm.setOnClickListener(v -> {
            //保存本次掃描的所有sn碼
            onScanResultListener.onScanResult(adapter.getData());
        });

        btnFoodIngredientsCancel.setOnClickListener(v -> {
            if (adapter.getData().size() > 0) {
                AppDialog.getInstance().showWaringDialog(getContext(), "關閉後不會保存SN碼記錄", (view, dialog) -> {
                    dialog.dismiss();
                    onCancelListener.onCancel();
                });
            } else if (onCancelListener != null) {
                onCancelListener.onCancel();
            }
        });
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if (view.getId() == R.id.iv_sn_code_delete) {
                onSingerResultListener.onScanValue(false, adapter.getItem(position), adapter.getItemCount());
                adapter1.removeAt(position);
            }
        });
        addView(rootView);
    }

    private void commitSnCode(SnCodeAdapter adapter) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(edInputSn)) {
            if (adapter.getData().contains(edInputSn.getText().toString())) {
                ToastUtils.show(getContext(), "商品已存在，不能重複添加");
            } else {
                String snCode = edInputSn.getText().toString();
                adapter.addData(snCode);
                edInputSn.setText("");
                onSingerResultListener.onScanValue(true, snCode, adapter.getItemCount());
            }
        } else {
            ToastUtils.show(getContext(), "請輸入SN碼");
        }
    }

    public ScanSnView setOnCancelListener(OnCancelListener onCancelListener) {
        this.onCancelListener = onCancelListener;
        return this;
    }

    public interface OnSingerResultListener {
        /**
         * @param isAdd               true為新增，false為刪除
         * @param snCode              sn碼
         * @param currentSnCodeNumber 當前有多少個sn碼
         */
        void onScanValue(boolean isAdd, String snCode, int currentSnCodeNumber);
    }

    public interface OnCancelListener {
        void onCancel();
    }

    private static class SnCodeAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public SnCodeAdapter(int layoutResId, @org.jetbrains.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            addChildClickViewIds(R.id.iv_sn_code_delete);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder viewHolder, String s) {
            viewHolder.setText(R.id.tv_sn_code, s);
            viewHolder.setTextColor(R.id.tv_sn_code, ContextCompat.getColor(getContext(), R.color.color_3c));
            viewHolder.setTextColor(R.id.tv_serial_number, ContextCompat.getColor(getContext(), R.color.color_3c));
            viewHolder.setGone(R.id.iv_sn_code_delete, false);
            viewHolder.setGone(R.id.it_sn_code_operating, true);
            viewHolder.setText(R.id.tv_serial_number, String.valueOf(viewHolder.getAdapterPosition() + 1));
            if (viewHolder.getAdapterPosition() % 2 == 0) {
                viewHolder.setBackgroundColor(R.id.layout_sn_code, ContextCompat.getColor(getContext(), R.color.color_f9));
            } else {
                viewHolder.setBackgroundColor(R.id.layout_sn_code, ContextCompat.getColor(getContext(), R.color.white));
            }
        }
    }
}
