package com.gingersoft.gsa.cloud.bean.mvp.ui.widget;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gingersoft.gsa.cloud.base.common.bean.MemberInfo;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.bean.R;
import com.gingersoft.gsa.cloud.bean.mvp.ui.adapter.MemberInfoAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem;
import com.qmuiteam.qmui.QMUILog;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.rengwuxian.materialedittext.MaterialEditText;

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

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

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2019-12-10
 * 修订历史：2019-12-10
 * 描述：
 */
public class UseMemberDialog extends Dialog {

    private static final String TAG = "UseMemberDialog";

    private Context mContext;
    private UseMemberDialog mDialog;

    // 动画时长
    private final static int mAnimationDuration = 300;
    // 持有 ContentView，为了做动画
    private View mContentView;
    private boolean mIsAnimating = false;

    private QMUITopBar mTopBar;
    private RecyclerView.LayoutManager mLayoutManager;

    private RecyclerView recycler_member_info;
    private MaterialEditText ed_phone;
    private ImageView iv_no_data;
    private LinearLayout ll_bottom;
    private QMUIAlphaButton btn_query_memeber;
    private QMUIAlphaButton btn_scan;
    private QMUIAlphaButton btn_use_member;
    private QMUIAlphaButton btn_clear_member;

    private MemberInfoAdapter mMemberInfoAdapter;
    private List<SectionTextItem> mMemberInfoList;


    public UseMemberDialog(Context context) {
        super(context, R.style.QMUI_BottomSheet);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //noinspection ConstantConditions
        getWindow().getDecorView().setPadding(0, 0, 0, 0);

        // 在底部，宽度撑满
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER;

        int screenWidth = QMUIDisplayHelper.getScreenWidth(getContext());
        int screenHeight = QMUIDisplayHelper.getScreenHeight(getContext());
        params.width = screenWidth < screenHeight ? screenWidth : screenHeight;
        getWindow().setAttributes(params);
        setCanceledOnTouchOutside(true);
    }

    @Override
    public void setContentView(int layoutResID) {
        mContentView = LayoutInflater.from(getContext()).inflate(layoutResID, null);
        super.setContentView(mContentView);
    }

    @Override
    public void setContentView(@NonNull View view, ViewGroup.LayoutParams params) {
        mContentView = view;
        super.setContentView(view, params);
    }

    public View getContentView() {
        return mContentView;
    }

    @Override
    public void setContentView(@NonNull View view) {
        mContentView = view;
        super.setContentView(view);
    }

    /**
     * BottomSheet升起动画
     */
    private void animateUp() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        mContentView.startAnimation(set);
    }

    /**
     * BottomSheet降下动画
     */
    private void animateDown() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f
        );
        AlphaAnimation alpha = new AlphaAnimation(1, 0);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mIsAnimating = true;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsAnimating = false;
                /**
                 * Bugfix： Attempting to destroy the window while drawing!
                 */
                mContentView.post(new Runnable() {
                    @Override
                    public void run() {
                        // java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{22dbf5b V.E...... R......D 0,0-1080,1083} not attached to window manager
                        // 在dismiss的时候可能已经detach了，简单try-catch一下
                        try {
                            UseMemberDialog.super.dismiss();
                        } catch (Exception e) {
                            QMUILog.w(TAG, "dismiss error\n" + Log.getStackTraceString(e));
                        }
                    }
                });
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mContentView.startAnimation(set);
    }

    @Override
    public void show() {
        super.show();
        animateUp();
    }

    @Override
    public void dismiss() {
        if (mIsAnimating) {
            return;
        }
        animateDown();
    }

    public UseMemberDialog build() {
        if (mDialog != null) {
            return mDialog;
        }
        mDialog = new UseMemberDialog(mContext);
        View contentView = buildViews();
        mDialog.setContentView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (QMUIDisplayHelper.getScreenHeight(mContext) * 0.65)));
        updateMemberInfo(MyOrderManage.getInstance().getMemberInfo());
        return mDialog;
    }

    private View buildViews() {
        View view = View.inflate(mContext, getContentViewLayoutId(), null);
        mTopBar = view.findViewById(R.id.topbar);
        recycler_member_info = view.findViewById(R.id.recycler_memeber_info);
        ed_phone = view.findViewById(R.id.ed_phone);
        iv_no_data = view.findViewById(R.id.iv_no_data);
        btn_query_memeber = view.findViewById(R.id.btn_query_memeber);
        btn_scan = view.findViewById(R.id.btn_scan);
        ll_bottom = view.findViewById(R.id.ll_bottom);
        btn_use_member = view.findViewById(R.id.btn_use_member);
        btn_clear_member = view.findViewById(R.id.btn_clear_member);

        initTopbar();
        initRecyclerLayout();

        btn_query_memeber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(getTvPhone())) {
                    ed_phone.setError("請輸入會員手機號");
                    return;
                }
                if (onLayoutClickListener != null) {
                    onLayoutClickListener.onInputPhone(mDialog, getTvPhone());
                }
            }
        });
        btn_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onLayoutClickListener != null) {
                    onLayoutClickListener.onScanAction(mDialog);
                }
            }
        });
        btn_use_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onLayoutClickListener != null) {
                    onLayoutClickListener.onUseMember(mDialog);
                }
            }
        });
        btn_clear_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onLayoutClickListener != null) {
                    onLayoutClickListener.clearMemberInfo();
                    clearMemberInfo();
                }
            }
        });
        return view;
    }

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

            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mTopBar.setTitle("使用會員");
    }

    private void initRecyclerLayout() {
        mLayoutManager = createLayoutManager();
        recycler_member_info.setLayoutManager(mLayoutManager);
    }

    public void setAdapter(BaseQuickAdapter adapter) {
        recycler_member_info.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private RecyclerView.LayoutManager createLayoutManager() {
        return new LinearLayoutManager(mContext) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        };
    }

    public void updateMemberInfo(MemberInfo memberInfo) {
        if (memberInfo != null) {
            if (mMemberInfoList == null) {
                mMemberInfoList = new ArrayList<>();
            }
            if (mMemberInfoAdapter == null) {
                mMemberInfoAdapter = new MemberInfoAdapter(mMemberInfoList);
                recycler_member_info.setAdapter(mMemberInfoAdapter);
            }
            List<SectionTextItem> data = getMemberInfoItem(memberInfo);
            if (mMemberInfoList.size() > 0) {
                mMemberInfoList.clear();
            }
            mMemberInfoList.addAll(data);
            mMemberInfoAdapter.notifyDataSetChanged();

            showBottomLayoutVisibility(true);
        }
    }

    public void clearMemberInfo() {
        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;
    }

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

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

    protected int getContentViewLayoutId() {
        return R.layout.meal_dialog_use_member;
    }

    private OnLayoutClickListener onLayoutClickListener;

    public UseMemberDialog setOnLayoutClickListener(OnLayoutClickListener onLayoutClickListener) {
        this.onLayoutClickListener = onLayoutClickListener;
        return this;
    }

    public interface OnLayoutClickListener {

        void onInputPhone(UseMemberDialog dialog, String phone);

        void onScanAction(UseMemberDialog dialog);

        void onUseMember(UseMemberDialog dialog);

        void clearMemberInfo();
    }

}
