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

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;

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.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.qrcode.core.BarcodeType;

/**
 * @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;

    public ScanSnView(Fragment fragment, List<String> snCodes, ScanSnPopup.OnScanResultListener onScanResultListener) {
        super(fragment.requireContext());
        this.snCodes = snCodes;
        this.onScanResultListener = onScanResultListener;
        this.fragment = fragment;
        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(String.valueOf(qrCodeResult));
                                        }
                                    }
                                });
                    }
                })
        );
        //提交按鈕
        tvSubmitSN.setOnClickListener(v -> {
            //提交輸入框中的sn碼
            if (TextUtil.isNotEmptyOrNullOrUndefined(edInputSn)) {
                adapter.addData(edInputSn.getText().toString());
                edInputSn.setText("");
            }
        });

        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) {
                adapter1.removeAt(position);
            }
        });
        addView(rootView);
    }

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

    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));
            }
        }
    }
}
