package com.yidianling.uikit.custom.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.yidianling.common.tools.RxImageTool;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper;
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage;
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.router.YdlCommonRouterManager;
import com.ydl.ydlcommon.utils.StringUtils;
import com.ydl.ydlcommon.utils.YDLCacheUtils;

/**
 * Created by haorui on 2019/5/22.
 * Des:
 */
public class ConfideOrderInfoView extends RelativeLayout {
    private Context mContext = null;
    private String mSessionId;
    private IP2PCustomActionHandler.DocInfo info = null;
    private TextView tv_status = null;
    private TextView tv_tips = null;
    private TextView tv_action = null;
    private TextView tv_order_info = null;
    private ImageView iv_call = null;

    public ConfideOrderInfoView(Context context, String sessionId) {
        super(context);
        this.mContext = context;
        this.mSessionId= sessionId;
        initView();
    }

    public ConfideOrderInfoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private void initView() {
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.leftMargin = RxImageTool.dp2px(8f);
        params.rightMargin = RxImageTool.dp2px(8f);
        setLayoutParams(params);
        View.inflate(mContext, R.layout.im_nim_chat_confide_order_info_view, this);
        setBackground(getResources().getDrawable(R.drawable.im_bg_im_confide_action));
        tv_status = findViewById(R.id.tv_status);
        tv_tips = findViewById(R.id.tv_tips);
        tv_action = findViewById(R.id.tv_action);
        iv_call = findViewById(R.id.iv_call);
        tv_order_info = findViewById(R.id.tv_order_info);
    }


    public void setData(IP2PCustomActionHandler.DocInfo info) {
        this.info = info;
        updateUI();
        setClick();
    }

    private void updateUI() {
        //有未完成订单
        if (info.hasAvailableListenOrder == 2) {
            tv_status.setText("剩余时间：" + coverTime(Integer.valueOf(info.listenOrderRemainTime)));
            tv_tips.setVisibility(View.GONE);


            if (info.is_online == 3) { //通话中
                tv_action.setText("通话中");
                tv_action.setTextColor(getResources().getColor(R.color.platform_color_FF6633));
            } else if (info.is_online == 4 || info.is_online == 1) { //继续拨打
                tv_action.setVisibility(View.GONE);
                iv_call.setVisibility(View.VISIBLE);
            } else if (info.is_online == 2) { //离线
                tv_action.setText("喊TA上线");
                tv_action.setBackground(getResources().getDrawable(R.drawable.im_background_chat_confide_order_call_online));
                tv_action.setTextColor(getResources().getColor(R.color.platform_color_1DA1F2));
            }

        } else if (info.listenOrderCommentStatus == 1) {//订单未评价
            tv_status.setText("已结束");
            tv_action.setBackground(getResources().getDrawable(R.drawable.im_background_chat_confide_order_action));
            tv_action.setTextColor(getResources().getColor(R.color.im_white));
            tv_action.setText("去评价");
            tv_tips.setVisibility(View.VISIBLE);
        }
        tv_order_info.setText(info.listenOrderDesc);
    }

    void setClick() {
        iv_call.setOnClickListener(view -> {
            if (info.is_online == 1 || info.is_online == 4) {//通话中
                //跳转专家倾述主页
                ActionHandlerStorage.getL(mSessionId).confide();
            }
        });
        tv_action.setOnClickListener(view -> {
            if (info.is_online == 2) {//离线  喊ta上线
                //走发送留言逻辑：一天只能给同一个老师发送一次留言
                checkNeedSendMsg();
            }

            if (info.is_online == 1 || info.is_online == 3 || info.is_online == 4) {//通话中
                //跳转专家倾述主页
                ActionHandlerStorage.getL(mSessionId).confide();
            }

            if (info.listenOrderCommentStatus == 1) {//待评价订单
                if (TextUtils.isEmpty(info.listenOrderCommentUrl)) {
                    ToastUtil.toastShort("评价页面参数错误，请退出重试");
                    return;
                }
                H5Params h5Params = new H5Params(info.listenOrderCommentUrl, "评价");
                NewH5Activity.start(mContext, h5Params);
            }
        });

        //点击整个view，跳转订单详情页面
        setOnClickListener(view -> {
            if (!TextUtils.isEmpty(info.listenOrderUrl)) {//订单详情
                H5Params h5Params = new H5Params(info.listenOrderUrl, "订单详情");
                NewH5Activity.start(mContext, h5Params);
            }
        });
    }


    //时间转化
    private String coverTime(int time) {
        return String.valueOf((time / 60)) + ":" + time % 60;
    }

    /**
     * 判断是否需要给老师发送留言
     */
    private void checkNeedSendMsg() {
        String localTime = YDLCacheUtils.Companion.getSendMsgTime(YdlCommonRouterManager.INSTANCE.getYdlCommonRoute().getUid() + "", ActionHandlerStorage.getL(mSessionId).getInfo().toUid);
        //是否是同一天
        if (StringUtils.compareTime(localTime)) {//是同一天
            ToastUtil.toastShort("已留言");
            return;
        }
        String text = "老师好，我想找您倾诉，请尽快上线私聊我，我在等您";
        //以用户的身份发送消息给老师
        IMMessage message = MessageBuilder.createTextMessage(ActionHandlerStorage.getL(mSessionId).getInfo().toUid, SessionTypeEnum.P2P, text);
        NIMClient.getService(MsgService.class).sendMessage(message, false).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                YDLCacheUtils.Companion.saveSendMsgTime(YdlCommonRouterManager.INSTANCE.getYdlCommonRoute().getUid() + "", ActionHandlerStorage.getL(mSessionId).getInfo().toUid, System.currentTimeMillis() + "");
            }

            @Override
            public void onFailed(int code) {
                if (code == 7101) {
                    ToastUtil.toastShort("您已被对方拉黑!");
                } else if (code == 404) {

                } else {
                    //上传至后台
                    ActionHandlerStorage.getL(mSessionId).uploadSendMessageError(code);
                }
            }

            @Override
            public void onException(Throwable exception) {

            }
        });
        MessageListPanelHelper.getInstance().notifyAddMessage(message);
    }
}
