package com.efounder.chat.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
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.RedPackageObtainModel;
import com.efounder.chat.model.UserEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.google.gson.Gson;

import net.sf.json.JSONObject;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.efounder.chat.fragment.LuckMoneyHistoryFragment.retainAsignDecimals;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 红包详情界面
 *
 * @author yqs 2018/08/07
 */

public class LuckMoneyDetailActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvTitle;
    private TextView tvRecord;


    private IMStruct002 imStruct002;
    private byte chatType;
    private boolean isLuckMode = true;//拼手气红包
    private boolean isGroup = false;//是否是群组

    private ImageView ivAvatar;
    private TextView tvUsername;
    private TextView tvLeaveMessage;
    private TextView tvMoney;
    private TextView tvUnit;
    private RecyclerView recycleview;
    private TextView tvStatistics;
    private RelativeLayout llBottom;
    private TextView tvYilingqu;


    private List<RedPackageObtainModel.ListBean> mRecords;
    private MyAdapter myAdapter;
    private boolean isRob;//是否抢红包
    private JSONObject jsonObject;
    private RedPackageObtainModel model;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_luck_money_detail);
        initView();
        initListener();
        initData();
        EventBus.getDefault().register(this);
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    public static void start(Context context, IMStruct002 imStruct002) {
        startRob(context, imStruct002, false);
    }

    /**
     * 是否是抢红包
     *
     * @param context
     * @param imStruct002
     * @param isRob
     */
    public static void startRob(Context context, IMStruct002 imStruct002, boolean isRob) {
        Intent starter = new Intent(context, LuckMoneyDetailActivity.class);
        starter.putExtra("imStruct002", imStruct002);
        starter.putExtra("isRob", isRob);
        context.startActivity(starter);
    }

    private void initView() {
        //标题
        tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvRecord = (TextView) findViewById(R.id.tv_save);
        tvRecord.setVisibility(View.VISIBLE);
        tvRecord.setText(R.string.wrchatview_red_jilu);
        tvRecord.setOnClickListener(this);
        ivAvatar = (ImageView) findViewById(R.id.iv_avatar);
        tvUsername = (TextView) findViewById(R.id.tv_username);
        tvLeaveMessage = (TextView) findViewById(R.id.tv_leave_message);
        tvMoney = (TextView) findViewById(R.id.tv_money);
        tvUnit = (TextView) findViewById(R.id.tv_unit);
        recycleview = (RecyclerView) findViewById(R.id.recycleview);
        tvStatistics = (TextView) findViewById(R.id.statistics);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setAutoMeasureEnabled(true);
        llBottom = (RelativeLayout) findViewById(R.id.ll_bottom);
        tvYilingqu = (TextView) findViewById(R.id.tv_yilingqu);

        recycleview.setLayoutManager(layoutManager);
        recycleview.setHasFixedSize(true);
        recycleview.setNestedScrollingEnabled(false);
    }

    private void initListener() {

    }

    private void initData() {
        tvTitle.setText(R.string.wrchatview_red_detail);

        imStruct002 = (IMStruct002) getIntent().getSerializableExtra("imStruct002");
        isRob = getIntent().getBooleanExtra("isRob", false);
        try {
            jsonObject = JSONObject.fromObject(imStruct002.getMessage());

            tvLeaveMessage.setText(jsonObject.optString("leaveMessage"));
            tvUnit.setText(jsonObject.optString("assetUnit"));
            int redRackageCount = jsonObject.optInt("count", 1);
            String totlaMoney = jsonObject.optString("totalMoney");
            double allMoney = Double.valueOf(totlaMoney);
            String totalMoney1 = retainAsignDecimals(allMoney, 5);
            tvStatistics.setText(getResources().getString(R.string.im_red_package_detail_tip,
                    redRackageCount + "", totalMoney1, jsonObject.optString("assetUnit")));
        } catch (Exception e) {
            e.printStackTrace();
        }


        chatType = imStruct002.getToUserType();
        //初始化头像，姓名
        User user = WeChatDBManager.getInstance().getOneUserById(imStruct002.getFromUserId());
        tvUsername.setText(user.getReMark());
        LXGlideImageLoader.getInstance().showRoundUserAvatar(ivAvatar.getContext(), ivAvatar,
                user.getAvatar(), LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);

        mRecords = new ArrayList<>();
        myAdapter = new MyAdapter(this, R.layout.wechatview_item_red_obtain_record, mRecords);
        recycleview.setAdapter(myAdapter);
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            initPersonalData();
        } else {
            isGroup = true;
            initGroupRedPackageData();
        }

    }

    private void requestData() {
        mRecords.clear();
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("trusteeshipCoinId", jsonObject.optInt("trusteeshipCoinId") + "");
        map.put("packetId", jsonObject.optString("packetId", ""));
        map.put("imUserId", EnvironmentVariable.getProperty(CHAT_USER_ID));
        showLoading(R.string.common_text_please_wait);
        JFCommonRequestManager.getInstance(this).requestGetByAsyn(TAG, EnvironmentVariable.getProperty("TalkChainUrl")
                + "/tcserver/redpacket/grabRedPacket", map, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String response) {
                dismissLoading();
                try {
                    model = new Gson().fromJson(response, RedPackageObtainModel.class);
                    if (model == null) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.wrchatview_get_data_fail);
                        return;
                    }
                    // -1抢过 -2 抢完  第一次是抢到的钱  -3表示不允许自己抢
                    double data = model.getData();
                    if (data != -1 && data != -2 && data != -3) {
                        tvMoney.setText(retainAsignDecimals(data, 5));
                    } else if (data == -3) {
                        tvMoney.setText("0.00000");

                    } else if (data == -1) {
                        //已经抢过
                        tvMoney.setText(retainAsignDecimals(model.getCoin(), 5));
                    } else {
                        tvMoney.setText("0.00000");
                    }

                    if (model.getList() != null) {
                        mRecords.addAll(model.getList());
                        myAdapter.notifyDataSetChanged();
                    }

                    double allMoney = model.getRedPacket().getTotalMoney();
                    String totalMoney = retainAsignDecimals(allMoney, 5);
                    tvStatistics.setText(getResources().getString(R.string.im_red_package_detail_tip,
                            model.getRedPacket().getTotalSize() + "",
                            totalMoney, jsonObject.optString("assetUnit")));

                    tvLeaveMessage.setText(model.getRedPacket().getRemarks());

                    tvUnit.setText(jsonObject.optString("assetUnit"));
                    tvYilingqu.setText(getResources().getString(R.string.im_red_package_detail_yijingqu,model.getList().size()+""
                            ,model.getRedPacket().getTotalSize()+""));
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.wrchatview_data_error);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                dismissLoading();
                ToastUtil.showToast(AppContext.getInstance(), R.string.wrchatview_online_error);
            }
        });
    }


    private void initPersonalData() {
        //llBottom.setVisibility(View.GONE);
        // if (imStruct002.getFromUserId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
        //自己发的红包自己不能抢
        requestData();
        // }

    }

    private void initGroupRedPackageData() {
        llBottom.setVisibility(View.VISIBLE);
        requestData();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_save) {
            LuckMoneyHistoryActivity.start(LuckMoneyDetailActivity.this);
        }
    }


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

    private class MyAdapter extends CommonAdapter<RedPackageObtainModel.ListBean> {
        private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public MyAdapter(Context context, int layoutId, List<RedPackageObtainModel.ListBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, RedPackageObtainModel.ListBean redPackageObtainRecord, int position) {
            LinearLayout llContainer;
            ImageView ivIcon;
            TextView tvName;
            TextView tvTime;
            TextView tvMoney;
            LinearLayout llBestLayout;
            ImageView ivBest;
            TextView tvBest;

            tvBest = (TextView) holder.getView(R.id.tv_best);

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

            User user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(redPackageObtainRecord.getImUserId()), UserEvent.EVENT_RED_PACKAGE);
            tvName.setText(user.getReMark());
            LXGlideImageLoader.getInstance().showRoundUserAvatar(LuckMoneyDetailActivity.this,
                    ivIcon, user.getAvatar(), LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
            tvTime.setText(dateFormat.format(new Date(redPackageObtainRecord.getTime())));
            ivBest.setVisibility(redPackageObtainRecord.getBest() == 1 ? View.VISIBLE : View.GONE);
            tvMoney.setText(retainAsignDecimals(redPackageObtainRecord.getCoin(), 5) + " " + jsonObject.optString("assetUnit"));
            tvBest.setVisibility(redPackageObtainRecord.getBest() == 1 ? View.VISIBLE : View.GONE);
            if (imStruct002.getToUserType() == StructFactory.TO_USER_TYPE_PERSONAL) {
                tvBest.setVisibility(View.GONE);
            }

            if (model.getRedPacket().getType() == 1) {
                //固定额度红包不显示手气最佳
                tvBest.setVisibility(View.GONE);
            }
        }
    }

}
