package com.efounder.chat.item;

import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import androidx.appcompat.app.AppCompatActivity;
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.activity.LuckMoneyDetailActivity;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.fragment.ScrambleRedPackageDialogFragment;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.ViewSize;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.ui.util.DisplayUtil;
import com.efounder.util.AppContext;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

import net.sf.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

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

/**
 * 红包消息item
 *
 * @author YQS 2018/08/06
 */

public class RedPackageItem extends LinearLayout implements IMessageItem {
    private static final String TAG = "RedPackageItem";
    //未打开
    public static final int PACKAGE_NO_OPEN = 0;
    //已领取
    public static final int PACKAGE_RECEIVED = 1;
    //已抢光
    public static final int PACKAGE_WITHOUT = 2;

    //已过期
    public static final int PACKAGE_TIME_OUT = 3;
    private IMStruct002 message;
    private Context mContext;
    private View rootView;
    private ImageView ivIcon;
    private TextView tvMessage;
    private TextView tvTip;
    private TextView tvBottom;
    private LinearLayout linearLayout;
    private String packageId;//红包id
    private JSONObject messageJsonObject;


    public RedPackageItem(Context context) {
        super(context);
        mContext = context;
        int width = DisplayUtil.getMobileWidth(mContext) * 2 / 3 - 40;
        LayoutParams lp = new LayoutParams(
                width, ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setLayoutParams(lp);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rootView = inflater.inflate(R.layout.wechatview_message_item_red_package, this);//注意第二个参数
        initView();
    }

    private void initView() {
        ivIcon = (ImageView) rootView.findViewById(R.id.iv_icon);
        tvMessage = (TextView) rootView.findViewById(R.id.tv_message);
        tvTip = (TextView) rootView.findViewById(R.id.tv_tip);
        tvBottom = (TextView) rootView.findViewById(R.id.tv_bottom);
        linearLayout = rootView.findViewById(R.id.ll_layout);
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startOpenPackage();

            }
        });
    }

    private void startOpenPackage() {

        try {
            String json = message.getMessage();
            messageJsonObject = JSONObject.fromObject(json);
            int packageState = messageJsonObject.optInt("packageState");

            packageId = messageJsonObject.optString("packetId");
            byte chatType = message.getToUserType();
            if (message.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))
                    && chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                //如果是单聊 并且是 自己发送的红包直接打开详情
                LuckMoneyDetailActivity.start(mContext, message);
            } else {
                //群聊或者别人给自己发送的红包  自己是允许打开的

                //1.判断红包是否已领取 过期 领完 都只能进详情
                if (packageState == PACKAGE_RECEIVED
                        || packageState == PACKAGE_WITHOUT
                        || packageState == PACKAGE_TIME_OUT) {
                    LuckMoneyDetailActivity.start(mContext, message);
                    return;
                }

                //打开请抢红包界面
                requestAndOpenRob();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        //2.判断是不是自己发的红包，自己发的直接打开详情界面


    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        JFCommonRequestManager.getInstance(mContext).cannelOkHttpRequest(TAG);
    }

    /**
     * 请求数据打开抢界面
     */
    private void requestAndOpenRob() {
        LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.wrchatview_loading));
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("packetId", packageId + "");
        JFCommonRequestManager.getInstance(mContext).requestGetByAsyn(TAG, EnvironmentVariable.getProperty("TalkChainUrl")
                + "/tcserver/redpacket/redPacketStatus", map, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    //isOutOfDate 是否过期 1 过期 2 不过期
                    //isGrabRedPacket 是否抢过 1 抢过 2 没抢过
                    //isOutOfSize 是否抢光 1 抢光 2 没抢光
                    //{"result":"success","redPacketStatus":{"isGrabRedPacket":2,"isOutOfDate":2,"isOutOfSize":1}}
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    JSONObject redPacketStatus = jsonObject.getJSONObject("redPacketStatus");
                    if ("success".equals(jsonObject.optString("result"))) {
                        int isGrabRedPacket = redPacketStatus.optInt("isGrabRedPacket", 1);
                        int isOutOfSize = redPacketStatus.optInt("isOutOfSize", 2);
                        int isOutOfDate = redPacketStatus.optInt("isOutOfDate", 2);
                        if (isGrabRedPacket == 1) {
                            messageJsonObject.put("packageState", PACKAGE_RECEIVED);
                            message.setMessage(messageJsonObject.toString());
                            //已经抢过 进详情
                            LuckMoneyDetailActivity.start(mContext, message);
                            JFMessageManager.dbManager.update(message);
                            //通知界面刷新
                            EventBus.getDefault().post(new NotifyChatUIRefreshEvent());
                            return;
                        }


                        if (isOutOfDate == 1) {
                            //已经过期
                            messageJsonObject.put("packageState", PACKAGE_TIME_OUT);
                        } else {
                            //没过期在判断枪没抢光
                            if (isOutOfSize == 1) {
                                //已抢光
                                messageJsonObject.put("packageState", PACKAGE_WITHOUT);
                            }
                        }

                        message.setMessage(messageJsonObject.toString());
                        JFMessageManager.dbManager.update(message);
                        //通知界面刷新
                        EventBus.getDefault().post(new NotifyChatUIRefreshEvent());
                        ScrambleRedPackageDialogFragment fragment = ScrambleRedPackageDialogFragment.newInstance();
                        fragment.setMessage(message);
                        fragment.show(((AppCompatActivity) mContext).getSupportFragmentManager(), TAG);
                    } else {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.wechatview_get_red_info_fail);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.wrchatview_data_error);
                }
            }

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

    @Override
    public View messageView() {
        return this;
    }

    @Override
    public ViewSize messageViewSize() {
        return null;
    }

    @Override
    public void setIMStruct002(IMStruct002 message) {
        this.message = message;
        try {
            String json = message.getMessage();
            JSONObject jsonObject = JSONObject.fromObject(json);
            //留言
            tvMessage.setText(jsonObject.optString("leaveMessage", ""));
            //红包状态
            int packageState = jsonObject.optInt("packageState");
            GradientDrawable drawable = (GradientDrawable) linearLayout.getBackground();
            if (packageState == PACKAGE_NO_OPEN) {
                if (message.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                    tvTip.setText(R.string.wechatview_view_red);
                } else {
                    tvTip.setText(R.string.wechatview_receive_red);
                }
                drawable.setColor(getResources().getColor(R.color.wechatview_red_package_top_bg));
            } else if (packageState == PACKAGE_RECEIVED) {
                tvTip.setText(R.string.wechatview_red_received);
                drawable.setColor(getResources().getColor(R.color.wechatview_red_package_top_bg_light));

            } else if (packageState == PACKAGE_WITHOUT) {
                tvTip.setText(R.string.wechatview_red_qg);
                drawable.setColor(getResources().getColor(R.color.wechatview_red_package_top_bg_light));

            } else if (packageState == PACKAGE_TIME_OUT) {
                tvTip.setText(R.string.wechatview_red_time_out);
                drawable.setColor(getResources().getColor(R.color.wechatview_red_package_top_bg_light));
            } else {
                drawable.setColor(getResources().getColor(R.color.wechatview_red_package_top_bg));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean getIsInUse() {
        return this.isShown();
    }

    @Override
    public void setIsInUse(boolean isInUse) {


    }

    @Override
    public void prepareForReuse() {

    }
}
