package com.yidianling.im.session.viewholder;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.im.bean.OrderStatusBean;
import com.yidianling.im.config.constants.ImConstants;
import com.yidianling.im.helper.IMChatUtil;
import com.yidianling.im.http.ImRetrofitApi;
import com.yidianling.im.session.extension.CustomAttachmentConfirmOrder;
import com.yidianling.nimbase.common.ui.recyclerview.adapter.BaseMultiItemFetchLoadAdapter;
import com.yidianling.uikit.business.session.viewholder.MsgViewHolderBase;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 确认服务单  消息类型 38
 */
public class MsgViewHolderConfirmOrder extends MsgViewHolderBase {

    private TextView tv_title, tv_date, tv_type, tv_submit;
    private View lin_root;
    private ImageView img_icon;
    /***跳转url*/
    public String url;
    /***订单id*/
    public String orderId;
    /***服务单id*/
    public String serviceId;
    /***0 未确认 1已确认*/
    public int flag;
    public boolean isSureed = false;//是否已确认

    public MsgViewHolderConfirmOrder(BaseMultiItemFetchLoadAdapter adapter) {
        super(adapter);
    }

    @Override
    protected int getContentResId() {
        return R.layout.im_ui_message_custom_confirm_order;
    }

    @Override
    protected void inflateContentView() {
        tv_title = view.findViewById(R.id.tv_title);
        tv_date = view.findViewById(R.id.tv_date);
        tv_type = view.findViewById(R.id.tv_type);
        lin_root = view.findViewById(R.id.lin_root);
        img_icon = view.findViewById(R.id.img_icon);
        tv_submit = view.findViewById(R.id.tv_submit);

        if (isReceivedMessage()) {
            setAvatarRightInVisibity();
            lin_root.setBackgroundResource(R.drawable.im_bg_radius_no_topleft_white_8);
        } else {
            setAvatarLeftInVisibity();
            lin_root.setBackgroundResource(R.drawable.im_bg_radius_no_topright_white_8);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void bindContentView() {
        if (isReceivedMessage()) {
            setAvatarRightInVisibity();
        } else {
            setAvatarLeftInVisibity();
        }

        MsgAttachment attachment = message.getAttachment();
        if (attachment instanceof CustomAttachmentConfirmOrder) {
            CustomAttachmentConfirmOrder customAttachment = (CustomAttachmentConfirmOrder) attachment;
            tv_title.setText(customAttachment.title);
            tv_date.setText(customAttachment.bookingTime == null ? "" : customAttachment.bookingTime);
            tv_type.setText(customAttachment.servicetype == null ? "" : customAttachment.servicetype);
            url = customAttachment.url;
            orderId = customAttachment.orderId;
            serviceId = customAttachment.serviceId;
            flag = customAttachment.status;

            if (flag == 1) {
                // 1代表已确认，0代表待确认
                tv_submit.setText("已确认");
                tv_submit.setEnabled(false);
                tv_submit.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_radius_gray_linear_12));
                img_icon.setVisibility(View.VISIBLE);
                tv_submit.setVisibility(View.GONE);
                updateLocalMsg();
            } else {
                tv_submit.setText("确认");
                tv_submit.setEnabled(true);
                tv_submit.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_radius_green_linear_12));
                img_icon.setVisibility(View.GONE);
                tv_submit.setVisibility(View.VISIBLE);
            }

            tv_submit.setOnClickListener(v -> {
                //确定按钮给服务端发消息发送
                //确认接口
                ToastUtil.toastShort(context, "发送中...");

                String str = new Gson().toJson(new OrderStatusBean(serviceId != null ? serviceId : orderId, "3"));
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), str);

                Disposable subscribe = ImRetrofitApi.Companion.getImRetrofitApi().standardOrderServiceOperation(body)
                        .compose(RxUtils.INSTANCE.resultJavaData())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(it -> {
                                    //确认完成，按钮置灰，更新本地消息
                                    updateLocalMsg();
                                    // 跳转服务单评价页
                                    new Handler().postDelayed(() -> {
                                        H5Params orderParams = new H5Params(ImConstants.Companion.getPLAY_SCORE_URL() + IMChatUtil.doctorId + "/" + serviceId, null);
                                        NewH5Activity.start(context, orderParams);
                                    }, 1000);
                                }, throwable ->
                                        ToastUtil.toastShort(throwable.getMessage())
                        );

            });

        }
        try {
            Map<String, Object> map = message.getLocalExtension();
            if (map != null) {
                Object obj = map.get("isSure");
                Object exp = map.get("isExpired");
                if (obj != null) {
                    boolean b = (boolean) obj;
                    if (flag == 1 || b) {
                        updateSureView("已确认");
                    }
                } else if (exp != null) {
                    boolean expb = (boolean) exp;
                    if (expb) {
                        updateSureView("已确认");
                    }
                } else {
                    isSureed = false;
                    tv_submit.setText("确认");
                    tv_submit.setEnabled(true);
                    tv_submit.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_radius_green_linear_12));
                }

            } else {
                isSureed = false;
                tv_submit.setText("确认");
                tv_submit.setEnabled(true);
                tv_submit.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_radius_green_linear_12));
            }
        } catch (Exception e) {
        }

        hideItemBg();
    }

    @Override
    protected void onItemClick() {
        if (TextUtils.isEmpty(url) && orderId == null) {
            return;
        }

        if (orderId == null || orderId.isEmpty()) {
            NewH5Activity.start(context, new H5Params(url, null));
        } else {
            //跳转新订单详情页
            H5Params orderParams = new H5Params(
                    ImConstants.Companion.getORDER_DETAIL() + (orderId.isEmpty() ? "" : orderId), null);
            NewH5Activity.start(context, orderParams);
        }
    }

    private void updateLocalMsg() {
        updateSureView("已确认");
        //更新本地消息
        Map<String, Object> map = message.getLocalExtension();
        if (map == null) {
            map = new HashMap();
        }
        map.put("isSure", true);
        message.setLocalExtension(map);
        NIMClient.getService(MsgService.class).updateIMMessage(message);
        //同时更新历史同订单未确认的消息状态
        NIMClient.getService(MsgService.class).queryMessageList(message.getSessionId(), SessionTypeEnum.P2P, 0, 100).setCallback(new RequestCallback<List<IMMessage>>() {
            @Override
            public void onSuccess(List<IMMessage> param) {
                if (param != null && param.size() > 0) {
                    for (IMMessage msg : param) {
                        MsgAttachment attachment = msg.getAttachment();
                        if (attachment instanceof CustomAttachmentConfirmOrder) {
                            CustomAttachmentConfirmOrder customAttachConsultSubScript = (CustomAttachmentConfirmOrder) attachment;
                            if (customAttachConsultSubScript.orderId.equals(orderId)) {
                                //修改历史消息状态为已失效
                                Map map1 = msg.getLocalExtension();
                                if (map1 == null) {
                                    map1 = new HashMap();
                                    map1.put("isExpired", true);
                                    msg.setLocalExtension(map1);
                                    NIMClient.getService(MsgService.class).updateIMMessage(msg);
                                    //通知ui刷新
                                    getMsgAdapter().updateItemAtLocalExtension(msg);
                                } else {
                                    map1 = new HashMap();
                                    map1.put("isExpired", true);
                                    msg.setLocalExtension(map1);
                                    NIMClient.getService(MsgService.class).updateIMMessage(msg);
                                    //通知ui刷新
                                    getMsgAdapter().updateItemAtLocalExtension(msg);
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailed(int code) {

            }

            @Override
            public void onException(Throwable exception) {

            }
        });
    }

    private void updateSureView(String btnName) {
        tv_submit.setText(btnName);
        tv_submit.setEnabled(false);
        tv_submit.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_radius_gray_linear_12));
    }
}
