package com.efounder.chat.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.model.RedPacketHistoryBean;
import com.efounder.chat.model.UserEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.disposables.Disposable;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 红包记录历史界面
 *
 * @author yqs 2018/08/07
 */

public class LuckMoneyHistoryFragment extends BaseFragment implements View.OnClickListener {

    private final String TAG = "LuckMoneyHistoryActivity";
    public static final String BASE_URL = EnvironmentVariable.getProperty("TalkChainUrl") + "/tcserver/";


    private List<RedPacketHistoryBean.GetRedPacketRecordListBean> mRecords;
    private MyAdapter myAdapter;
    private RecyclerView recycleview;
    private View rootView;
    private ImageView ivAvatar;
    private TextView tvUsername;
    private TextView tvMoney;
    private TextView tvTips;
    private SmartRefreshLayout refreshLayout;
    private String type;
    private int page = 1;
    private Disposable disposable;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.wechatview_fragment_luck_history, container, false);
        initView();
        initListener();
        initData();
        EventBus.getDefault().register(this);
        return rootView;
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        JFCommonRequestManager.getInstance(getActivity()).cannelOkHttpRequest(TAG);
        EventBus.getDefault().unregister(this);
    }

    public static LuckMoneyHistoryFragment newInstance(String type) {

        Bundle args = new Bundle();
        args.putString("type", type);
        LuckMoneyHistoryFragment fragment = new LuckMoneyHistoryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void initView() {
        ivAvatar = (ImageView) rootView.findViewById(R.id.iv_avatar);
        tvUsername = (TextView) rootView.findViewById(R.id.tv_username);
        tvMoney = (TextView) rootView.findViewById(R.id.tv_money);
        tvTips = (TextView) rootView.findViewById(R.id.tv_tips);
        recycleview = (RecyclerView) rootView.findViewById(R.id.recycleview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recycleview.setLayoutManager(layoutManager);
        refreshLayout = (SmartRefreshLayout) rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(true);

    }

    private void initListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                requestData(type);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                requestData(type);
            }
        });

    }

    private void initData() {

        type = getArguments().getString("type");
        if ("send".equals(type)) {
            tvTips.setVisibility(View.GONE);
        }
        //初始化头像，姓名
        User user = WeChatDBManager.getInstance().getOneUserById(Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)));

        tvUsername.setText(user.getReMark());
        LXGlideImageLoader.getInstance().showRoundUserAvatar(ivAvatar.getContext(), ivAvatar,
                user.getAvatar(), LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);

        mRecords = new ArrayList<>();
        myAdapter = new MyAdapter(getActivity(), R.layout.wechatview_item_red_obtain_history, mRecords, type);
        recycleview.setAdapter(myAdapter);
        refreshLayout.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refreshLayout.autoRefresh();
    }

    private void requestData(final String type) {
        if (page == 1)
            mRecords.clear();
//        JFCommonRequestManager manager = JFCommonRequestManager.getInstance(getActivity());
        final HashMap<String, String> params = new HashMap<>();
        //userId传手机号
        params.put("userId", EnvironmentVariable.getUserName());
        params.put("type", "send".equals(type) ? "2" : "1");
        params.put("pagesize", "10");
        params.put("page", String.valueOf(page));
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, BASE_URL +
                "redpacket/redPacketRecord", params, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    if (object.optString("result").equals("success")) {
                        RedPacketHistoryBean redPacketHistoryBean = com.alibaba.fastjson.JSONObject.parseObject(result, RedPacketHistoryBean.class);
                        mRecords.addAll(redPacketHistoryBean.getGetRedPacketRecordList());
                        tvMoney.setText(redPacketHistoryBean.getPage().getAllRow() + "");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                myAdapter.notifyDataSetChanged();
                if (page == 1) {
                    refreshLayout.finishRefresh(100);
                } else {
                    refreshLayout.finishLoadMore(100);
                }

            }

            @Override
            public void onReqFailed(String errorMsg) {
                myAdapter.notifyDataSetChanged();
                if (page == 1) {
                    refreshLayout.finishRefresh(100);
                } else {
                    refreshLayout.finishLoadMore(100);
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.but_send) {

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void solveUserEvent(UserEvent userEvent) {
        if (userEvent.getEventType() == UserEvent.EVENT_RED_PACKAGE) {
            myAdapter.notifyDataSetChanged();
        }
    }

    private class MyAdapter extends CommonAdapter<RedPacketHistoryBean.GetRedPacketRecordListBean> {

        String type;

        public MyAdapter(Context context, int layoutId, List<RedPacketHistoryBean.GetRedPacketRecordListBean> datas, String type) {
            super(context, layoutId, datas);
            this.type = type;
        }

        @Override
        protected void convert(ViewHolder holder, RedPacketHistoryBean.GetRedPacketRecordListBean redPacketHistoryBean, int position) {
            LinearLayout llContainer;
            ImageView ivIcon;
            TextView tvName;
            TextView tvTime;
            TextView tvMoney;
            LinearLayout llBestLayout;
            ImageView ivBest;
            llContainer = holder.getView(R.id.ll_container);
            ivIcon = holder.getView(R.id.iv_icon);
            tvName = holder.getView(R.id.tv_name);
            tvTime = holder.getView(R.id.tv_time);
            tvMoney = holder.getView(R.id.tv_money);
            llBestLayout = holder.getView(R.id.ll_best_layout);
            ivBest = holder.getView(R.id.iv_best);

            if (type.equals("send")) {
                if (redPacketHistoryBean.getType() == 0) {
                    //随机红包
                    tvName.setText(R.string.wechatview_fight_red);
                } else {
                    tvName.setText(R.string.wechatview_ordinary_red);
                }
            } else {
                //发红包的用户
                if (redPacketHistoryBean.getUserName() != null) {
                    tvName.setText(redPacketHistoryBean.getUserName());
                } else {
                    tvName.setText(redPacketHistoryBean.getUserId());
                }
            }

            tvTime.setText(redPacketHistoryBean.getTimestamp());

            BigDecimal bd1 = new BigDecimal(redPacketHistoryBean.getTotalMoney());
//            tvMoney.setText(bd1.toPlainString());
            tvMoney.setText(retainAsignDecimals(redPacketHistoryBean.getTotalMoney(), 5) + " " + redPacketHistoryBean.getCoinName());

        }
    }

    /**
     * 保留指定位数的小数
     *
     * @param d
     * @param scale 小数位数
     * @return
     */
    public static String retainAsignDecimals(double d, int scale) {
        // https://www.cnblogs.com/zhangqf/p/6179945.html
        if (d == 0) {
            return "0";
        }
        BigDecimal d1 = new BigDecimal(Double.toString(d));
        String result = d1.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
        return result;
    }
}
