package com.bigfish.salecenter.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.badoo.mobile.util.WeakHandler;
import com.bigfish.salecenter.R;
import com.bigfish.salecenter.api.SaleService;
import com.bigfish.salecenter.databinding.FragmentSaleInstructionBinding;
import com.bigfish.salecenter.model.ProductDetailBean;
import com.bigfish.salecenter.ui.activity.PosterShareActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dayu.base.api.Api;
import com.dayu.base.api.protocol.AddShareRecordData;
import com.dayu.base.api.protocol.CommentBean;
import com.dayu.base.api.protocol.CommentPostData;
import com.dayu.base.api.protocol.CommentReplyData;
import com.dayu.base.ui.adapter.CommentAdapter;
import com.bigfish.salecenter.adapter.TaskAdapter;
import com.dayu.base.ui.fragment.BaseFragment;
import com.dayu.base.ui.presenter.SImplePresenter;
import com.dayu.common.Constants;
import com.dayu.event.UserInfo;
import com.dayu.provider.router.RouterPath;
import com.dayu.utils.CommonUtils;
import com.dayu.utils.GlideImageLoader;
import com.dayu.utils.ProgressUtil;
import com.dayu.utils.UserManager;
import com.dayu.widgets.KeyboardStateObserver;
import com.dayu.widgets.WechatShareDialog;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.umeng.socialize.bean.SHARE_MEDIA;

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

/**
 * Created by mReturn
 * on 2020/2/13
 **/
public class SaleInstructionFragment extends BaseFragment<SImplePresenter, FragmentSaleInstructionBinding> {

    List<String> sceneList = new ArrayList<>();
    List<String> pointList = new ArrayList<>();
    ProductDetailBean mDetail;

    private UserInfo userInfo;
    private CommentBean selectedItem;
    private int page = 1;
    private int pageSize = 20;
    private CommentAdapter mCommentAdapter;
    private TaskAdapter taskAdapter;
    private List<CommentBean> commentList = new ArrayList<>();
    private WeakHandler weakHandler = new WeakHandler();

    public static SaleInstructionFragment newInstance(ProductDetailBean detail) {
        Bundle args = new Bundle();
        args.putSerializable("data", detail);
        SaleInstructionFragment fragment = new SaleInstructionFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setPresenter() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_sale_instruction;
    }

    @Override
    public void initView() {
        initUser();
        userInfo = mUserInfo;
        GlideImageLoader.load(mActivity, mBind.ivAvatar, userInfo.getHeaderImg(), R.drawable.icon_user_default);
        if (getArguments() != null) {
            mDetail = (ProductDetailBean) getArguments().getSerializable("data");
        }

        initCommentAdapter();
        initTaskAdapter();
        if (mDetail != null) {
            initDataView();
            initCommentListener();
        }
        showDialog();
        getCommentData();
        initRefreshView();
        mBind.btnShare.setOnClickListener(v -> onShareClick());
        mBind.getAward.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.URL, mDetail.getBdFormUrl() + "&accountId=" + UserManager.getInstance().getUser().getAccountId() + "&token=" + UserManager.getInstance().getUser().getToken());
                    bundle.putString("title", "贡献商机有奖");
                    ARouter.getInstance().build(RouterPath.PATH_WEBVIEW).withBundle(Constants.BUNDLE, bundle).navigation();
                }

        );
        setVideoView();
        mBind.infoDownload.setOnClickListener(v -> {
            Uri uri = Uri.parse( mDetail.materialUrl);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            mActivity.startActivity(intent);
        });
    }

    private void setVideoView() {
//        String url = "http://dl.kf.ai/online/ka/spu/serviceDetailVideo/09ee6818825f705cf106b3c497d40af9.mp4";
        String url = mDetail.trainVideo;
        if (TextUtils.isEmpty(url)) {
            mBind.llVideo.setVisibility(View.GONE);
        } else {
            mBind.llVideo.setVisibility(View.VISIBLE);
            mBind.jzVideo.setUp(url, "");
            CommonUtils.setVideoThumb(mActivity, mBind.jzVideo, url);
        }
    }

    //点击分享按钮
    public void onShareClick() {
//        Api.getService(SaleService.class).canShare(mDetail.getId(), mUserId).compose(Api.applySchedulers())
//                .subscribe(mPresenter.baseObserver(success -> {
//                            ToastUtils.showShortToast("canShare: " + success);
//                        })
//
//                );
        if (mDetail != null) {
            WechatShareDialog.getInstance().showBottomDialog(mActivity, pos -> {
                if (pos == 0) {
                    CommonUtils.shareProgram(mActivity, mDetail.getFirstUrl(), mDetail.getGoodsModel(),
                            mDetail.getBrief(), mUserId, mDetail.getId(), SHARE_MEDIA.WEIXIN, null);
                    AddShareRecordData data = new AddShareRecordData(mUserId, mUserInfo.getAccountName(),
                            "微信", mDetail.getId(), 2);
                    addShareRecord(data);
                } else {
                    PosterShareActivity.launch(mActivity, mDetail.getId(), mDetail.getGoodsModel()
                            , mDetail.getFirstUrl(), "pdetail", mDetail.getActualPrice(), mDetail.getMarketPrice());
                }
            });

//            MobclickAgent.onEvent(mActivity, "share_goods");
        }
    }

    //下拉刷新
    private void initRefreshView() {
        mBind.refreshLayout.setEnableLoadMore(false);
        mBind.refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            getCommentData();
        });
        mBind.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            getCommentData();
        });
    }

    //设置基本信息
    private void initDataView() {
        mBind.tvBonus.setText(CommonUtils.getIntMoneyStr(mActivity, mDetail.getSalesPrice()) + "/台");
        mBind.bdPrice.setText(CommonUtils.getIntMoneyStr(mActivity, mDetail.getBdPrice()));
        mBind.tvFace.setText(mDetail.getCustomerPortrait());
        for (int i = 0; i < mDetail.getGoodsCategorys().size(); i++) {
            sceneList.add(mDetail.getGoodsCategorys().get(i).getCategoryName());
        }
        fillPointList(mDetail.getSellingPoint1());
        fillPointList(mDetail.getSellingPoint2());
        fillPointList(mDetail.getSellingPoint3());

        setSceneAdapter();
        setPointAdapter();
    }

    //填充卖点数据
    private void fillPointList(String pointStr) {
        if (!TextUtils.isEmpty(pointStr))
            pointList.add(pointStr);

    }

    //适用场景
    private void setSceneAdapter() {
        BaseQuickAdapter<String, BaseViewHolder> sceneAdapter =
                new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_product_scene, sceneList) {
                    @Override
                    protected void convert(BaseViewHolder helper, String item) {
                        CheckBox cbScene = helper.getView(R.id.cb_scene);
                        cbScene.setText(item);
                        ViewGroup.LayoutParams lp = cbScene.getLayoutParams();
                        if (lp instanceof FlexboxLayoutManager.LayoutParams) {
                            FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
                            flexboxLp.setFlexGrow(1.0f);
                            flexboxLp.setAlignSelf(AlignItems.FLEX_END);
                        }
                    }
                };

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(mActivity);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_END);
//        mBind.rvScene.setLayoutManager(new GridLayoutManager(mActivity, 3));
        mBind.rvScene.setLayoutManager(layoutManager);
        mBind.rvScene.setAdapter(sceneAdapter);
    }

    //主打卖点
    private void setPointAdapter() {
        BaseQuickAdapter<String, BaseViewHolder> pointdapter =
                new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_sale_point, pointList) {
                    @Override
                    protected void convert(BaseViewHolder helper, String item) {
                        helper.setText(R.id.tv_point_item, item);
                    }
                };

        mBind.rvSellPoint.setLayoutManager(new GridLayoutManager(mActivity, 3));
        mBind.rvSellPoint.setAdapter(pointdapter);
    }

    private void initCommentAdapter() {
        mCommentAdapter = new CommentAdapter(false);
        mCommentAdapter.setData(commentList);
        mBind.rvComponent.setLayoutManager(new LinearLayoutManager(mActivity));
        mBind.rvComponent.setAdapter(mCommentAdapter);
        mCommentAdapter.setLoadMore(true);
        mBind.rvComponent.setNestedScrollingEnabled(false);
    }

    private void initTaskAdapter() {
        taskAdapter = new TaskAdapter(false);
        taskAdapter.setData(mDetail.goodsTasks);
        mBind.tasks.setLayoutManager(new LinearLayoutManager(mActivity));
        mBind.tasks.setAdapter(taskAdapter);
        taskAdapter.setLoadMore(false);
        mBind.tasks.setNestedScrollingEnabled(false);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initCommentListener() {
        KeyboardStateObserver.getKeyboardStateObserver(mActivity).setKeyboardVisibilityListener(
                new KeyboardStateObserver.OnKeyboardVisibilityListener() {
                    @Override
                    public void onKeyboardShow() {
                        mBind.btnComment.setVisibility(View.GONE);
                    }

                    @Override
                    public void onKeyboardHide() {
                        weakHandler.postDelayed(() -> {
//                            mBind.btnComment.setVisibility(View.VISIBLE);
                        }, 100);
                    }
                });
        mBind.nsvOperate.setOnTouchListener((view, motionEvent) -> {
            CommonUtils.hideSoftInput(mActivity, mBind.edtComment);
            return false;
        });


        //发送
        mBind.btnSend.setOnClickListener(v -> {
            String content = mBind.edtComment.getText().toString();
            if (TextUtils.isEmpty(content)) return;
            ProgressUtil.startLoad(mActivity);
            if (selectedItem != null) {
                CommentReplyData commentReplyData = new CommentReplyData(mUserId, content, mDetail.getId(), mDetail.getGoodsModel());
                commentReplyData.beMessageId = selectedItem.getId();
                Api.getService(SaleService.class).addCommentReply(commentReplyData).compose(Api.applySchedulers())
                        .subscribe(mPresenter.baseObserver(result -> {
                            if (result) {
                                selectedItem = null;
                                sendCommendSuccess();
                            }
                        }));
            } else {
                CommentPostData commentData = new CommentPostData(mUserId, content, mDetail.getId(), mDetail.getGoodsModel());
                Api.getService(SaleService.class).addComment(commentData).compose(Api.applySchedulers())
                        .subscribe(mPresenter.baseObserver(result -> {
                            if (result) {
                                sendCommendSuccess();
                            }
                        }));
            }

            CommonUtils.hideSoftInput(mActivity, mBind.edtComment);
        });

        mBind.btnComment.setOnClickListener(v -> {
            selectedItem = null;
            mBind.edtComment.setText("");
            mBind.edtComment.requestFocus();
            CommonUtils.ShowSoftInput(mActivity, mBind.edtComment);
        });

        mCommentAdapter.setOnItemClickListener((item, bind) -> {
            selectedItem = item;
            mBind.edtComment.setText("");
            mBind.edtComment.requestFocus();
            CommonUtils.ShowSoftInput(mActivity, mBind.edtComment);
        });
    }

    private void sendCommendSuccess() {
        page = 1;
        getCommentData();
        mBind.edtComment.setText("");
    }

    //获取评论数据
    private void getCommentData() {
        Api.getService(SaleService.class).getComment(mDetail.getId(), page, pageSize).compose(Api.applySchedulers())
                .subscribe(mPresenter.baseObserver(data -> {
                    mBind.refreshLayout.finishRefresh();
                    mBind.refreshLayout.finishLoadMore();
                    if (page == 1) {
                        commentList.clear();
                        mBind.refreshLayout.setEnableLoadMore(data.getData().size() > 0);
                    }
//                    commentList = transData(data.getData());
                    commentList.addAll(data.getData());
                    mBind.tvComponent.setText("留言. " + data.getTotalRows());
                    mCommentAdapter.setData(commentList);
                    mBind.refreshLayout.setEnableLoadMore(page < data.getTotalPages());
                    page += 1;
                }, responeThrowable -> {
                    mBind.refreshLayout.finishRefresh();
                    mBind.refreshLayout.finishLoadMore();
                }));
    }

}