package com.gingersoft.gsa.cloud.table.mvp.ui.fragment.mealstand;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerRiceponMemberDialogComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.RiceponMemberDialogContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.mealstand.RiceponMemberDialogPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.MemberInfoAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.UseMemberDialog;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseDialogFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.utils.PermissionUtil;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/24/2021 16: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 RiceponMemberDialogFragment extends BaseDialogFragment<RiceponMemberDialogPresenter> implements RiceponMemberDialogContract.View {

    @Inject
    RxErrorHandler mErrorHandler;

    @BindView(R2.id.topbar)
    QMUITopBar topbar;
    @BindView(R2.id.ed_phone)
    MaterialEditText edPhone;
    @BindView(R2.id.btn_query_memeber)
    QMUIAlphaButton btnQueryMemeber;
    @BindView(R2.id.ll_input_phone)
    LinearLayout llInputPhone;
    @BindView(R2.id.recycler_memeber_info)
    RecyclerView recyclerMemeberInfo;
    @BindView(R2.id.iv_no_data)
    ImageView ivNoData;
    @BindView(R2.id.btn_scan)
    QMUIAlphaButton btnScan;
    @BindView(R2.id.btn_use_member)
    QMUIAlphaButton btnUseMember;
    @BindView(R2.id.btn_clear_member)
    QMUIAlphaButton btnClearMember;
    @BindView(R2.id.ll_bottom)
    LinearLayout llBottom;

    @Inject
    MemberInfoAdapter mMemberInfoAdapter;
    @Inject
    List<SectionTextItem> mMemberInfoList;

    private TableBean.DataBean mCurrTableBean;
    private MemberInfo mMemberInfo;

    public static RiceponMemberDialogFragment newInstance(TableBean.DataBean currTableBean) {
        RiceponMemberDialogFragment fragment = new RiceponMemberDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("currTableBean", currTableBean);
        fragment.setArguments(bundle);
        return fragment;
    }

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

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        mCurrTableBean = arguments.getParcelable("currTableBean");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initTopbar();
        initAdapter();
    }

    private void initAdapter() {
        if (mMemberInfoAdapter != null) {
            recyclerMemeberInfo.setAdapter(mMemberInfoAdapter);
        }
    }

    private void initTopbar() {
        topbar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.theme_color));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                killMyself();
            }
        });
        topbar.setTitle("使用會員");
    }

    protected void toScanActivity() {
        PermissionUtil.launchCamera(new PermissionUtil.RequestPermission() {

            @Override
            public void onRequestPermissionSuccess() {
                String title = null;
                if (_mActivity instanceof MealStandActivity) {
                    title = "掃描會員碼";
                } else if (_mActivity instanceof OrderContentActivity) {
                    title = "掃描優惠券碼";
                }
                CC.obtainBuilder(ComponentName.COMPONENT_SCAN)
                        .setActionName("openScanActivity")
                        .addParam("title", title)
                        .build()
                        .callAsyncCallbackOnMainThread((cc, result) -> {
                        });
            }

            @Override
            public void onRequestPermissionFailure(List<String> permissions) {
                DeviceUtils.startSetting(mContext);
                showMessage(LanguageUtils.get_language_system(mContext, "please.open.camera.permissions", "請前往設置開放照相機權限"));
            }

            @Override
            public void onRequestPermissionFailureWithAskNeverAgain(List<String> permissions) {
                DeviceUtils.startSetting(mContext);
                showMessage(LanguageUtils.get_language_system(mContext, "please.open.camera.permissions", "請前往設置開放照相機權限"));
            }
        }, new RxPermissions(_mActivity), mErrorHandler);
    }

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

    }

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

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

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

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

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

    @OnClick({R2.id.btn_query_memeber, R2.id.btn_scan, R2.id.btn_use_member, R2.id.btn_clear_member})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_query_memeber) {
            String phone = getTvPhone();
            if (TextUtils.isEmpty(phone)) {
                edPhone.setError("請輸入會員手機號");
                return;
            }
            mPresenter.queryMember(2, phone, RestaurantInfoManager.newInstance().getGsPosShopId(), mCurrTableBean.getId(), mCurrTableBean.getTableNumber());
        } else if (id == R.id.btn_scan) {
            toScanActivity();
        } else if (id == R.id.btn_use_member) {
            if (onUseMemberListener != null) {
                onUseMemberListener.onUseMember(mMemberInfo);
            }
        } else if (id == R.id.btn_clear_member) {
            clearMemberInfo();
        }
    }

    public void showBottomLayoutVisibility(boolean show) {
        llBottom.setVisibility(show ? View.VISIBLE : View.GONE);
        btnScan.setVisibility(!show ? View.VISIBLE : View.GONE);
    }

    private String getTvPhone() {
        return edPhone.getText().toString();
    }

    @Override
    public void returnMemberInfo(MemberInfo memberInfo) {
        this.mMemberInfo = memberInfo;
        final List<SectionTextItem> memberInfoItems = getMemberInfoItem(memberInfo);
        if (mMemberInfoList.size() > 0) {
            mMemberInfoList.clear();
        }
        mMemberInfoList.addAll(memberInfoItems);
        mMemberInfoAdapter.notifyDataSetChanged();
        showBottomLayoutVisibility(true);
    }

    public void clearMemberInfo() {
        this.mMemberInfo = null;
        if (onUseMemberListener != null) {
            onUseMemberListener.onUseMember(null);
        }
        if (mMemberInfoList.size() > 0) {
            mMemberInfoList.clear();
        }
        mMemberInfoAdapter.notifyDataSetChanged();
        showBottomLayoutVisibility(false);
    }

    private List<SectionTextItem> getMemberInfoItem(MemberInfo memberInfo) {
        List<SectionTextItem> textItems = new ArrayList<>();
        textItems.add(new SectionTextItem("會員號碼: " + memberInfo.getMemberNo()));
        textItems.add(new SectionTextItem("會員電話: " + memberInfo.getPhone()));
        textItems.add(new SectionTextItem("會員名稱: " + memberInfo.getMemberName()));
        textItems.add(new SectionTextItem("會員等級: " + memberInfo.getLevelName()));
        textItems.add(new SectionTextItem("積分: " + memberInfo.getMemberPoint()));
        return textItems;
    }

    private OnUseMemberListener onUseMemberListener;

    public void setOnUseMemberListener(OnUseMemberListener onUseMemberListener) {
        this.onUseMemberListener = onUseMemberListener;
    }

    public interface OnUseMemberListener {

        void onUseMember(MemberInfo memberInfo);

    }
}
