package com.android.chmo.app;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.android.chmo.base.BaseActivity;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.response.VChatRes;
import com.android.chmo.http.response.VideoPriceRes;
import com.android.chmo.http.service.ModelService;
import com.android.chmo.http.service.OrderService;
import com.android.chmo.model.LoginUser;
import com.android.chmo.ui.activity.me.RechargeActivity;
import com.android.chmo.ui.dialog.ConfirmDialog;
import com.android.chmo.utils.LoginUtils;
import com.google.gson.Gson;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.activity.AVChatActivity;
import com.netease.nim.avchatkit.common.activity.ActivityManager;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2018/8/9.
 */

public class VChatManager {

    private static VChatManager vcManager;

    private String videoPk;

    private long beginTime;
    private long endTime;

    private int duration;

    private Timer timer;

    private float vPrice = 10;


    private VChatManager() {
    }

    public static VChatManager getInstance() {
        if (vcManager == null) {
            vcManager = new VChatManager();
        }
        return vcManager;
    }


    public void showPromptDialog(final Context activity, final float vPrice, final VChatCallback callback) {
        this.vPrice = vPrice;

        if (!checkBalance(vPrice)) {
            showBalanceOutDialog(activity);
            return;
        }

        String timeMsg = "您的余额只够通话" + getLimitVideoTime(vPrice) + "分钟，请尽快充值吧";
        new ConfirmDialog(activity)
                .setOutTouchDismiss(false)
                .setMsg("视频通话将产生费用\n\n" + timeMsg)
                .setDialogListener(new ConfirmDialog.DialogListener() {
                    @Override
                    public void onOk(Dialog dialog) {
                        dialog.dismiss();
                        callback.startVChat();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                        handUpVChat();
                    }
                }).show();
    }


    public void showBalanceOutDialog(final Context activity) {
        new ConfirmDialog(activity)
                .setOutTouchDismiss(false)
                .setMsg("您的余额不足，请先充值")
                .setButton("去充值", "取消")
                .setDialogListener(new ConfirmDialog.DialogListener() {
                    @Override
                    public void onOk(Dialog dialog) {
                        handUpVChat();
                        dialog.dismiss();
                        Intent intent = new Intent(activity, RechargeActivity.class);
                        activity.startActivity(intent);
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                        handUpVChat();
                    }
                }).show();
    }


    public static void call(final String account, final String name, final int type) {
        final Activity activity = ActivityManager.getInstance().currentActivity();
        ModelService.getModelVideoPrice(account, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                final VideoPriceRes res = new Gson().fromJson(result, VideoPriceRes.class);
                if (res.msg.equals("success")) {
                    VChatManager.getInstance().showPromptDialog(activity, res.vprice, new VChatManager.VChatCallback() {
                        @Override
                        public void startVChat() {
                            AVChatActivity.outgoingCall(AVChatKit.getContext(), account, name, type, AVChatActivity.FROM_INTERNAL);
                        }
                    });
                } else {
                    Toast.makeText(activity, "请求失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(activity, "请求失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }


    public void startVChat(final BaseActivity activity, final String account, final String name, float vprice) {
        showPromptDialog(activity, vprice, new VChatCallback() {
            @Override
            public void startVChat() {
                AVChatKit.outgoingCall(activity, account, name, AVChatType.VIDEO.getValue(), AVChatActivity.FROM_INTERNAL);
            }
        });
    }

    public void requestBegin(String modelPk) {
        beginTime = System.currentTimeMillis();
        OrderService.beginVChat(modelPk, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                Log.d("VChat", "requestBegin===================" + result);
                VChatRes res = new Gson().fromJson(result, VChatRes.class);
                if (res.msg.equals("success")) {
                    videoPk = res.videopk;
                    startTimer();
                }
            }

            @Override
            public void onFailure(String error) {
            }
        });
    }

    public void requestEnd() {
        endTimer();
        endTime = System.currentTimeMillis();
        double durTime = endTime / 1000 - beginTime / 1000;
        if (durTime < 60) {
            duration = 1;
        } else {
            duration = (int) Math.ceil(durTime / 60);
        }

        check();
    }

    private void check() {
        OrderService.checkVChat(videoPk, duration, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                Log.d("VChat", "check ================" + result);
                final VChatRes res = new Gson().fromJson(result, VChatRes.class);
                if (res.msg.equals("success")) {
                    reset();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            String msg = "视频总花费：" + res.coin + "元 ，当前余额：" + res.coinfee + "元";
                            Toast.makeText(ActivityManager.getInstance().currentActivity(), msg, Toast.LENGTH_SHORT).show();
                            LoginUtils.refreshUser();
                        }
                    }, 1000);
                }
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }


    public void handUpVChat() {
        ChmoApplication.getApp().sendBroadcast(new Intent("android.chmo.action.STOP"));
    }

    public void startTimer() {
        if (null != timer) {
            timer.cancel();
            timer = null;
        }
        int times = getLimitVideoTime(this.vPrice) * 60 * 1000;
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handUpVChat();
            }
        }, times);
    }

    public void endTimer() {
        if (null != timer) {
            timer.cancel();
            timer = null;
        }
    }

    private void reset() {
        videoPk = null;
        beginTime = 0;
        endTime = 0;
        duration = 0;
        vPrice = 10;
    }


    private static boolean checkBalance(float vprice) {
        LoginUser user = ChmoApplication.getApp().getLoginUser();
        float balance = Float.parseFloat(user.coin_a);
        if (balance < vprice) { // 余额小于 1分钟10块钱
            return false;
        }
        return true;
    }

    private static int getLimitVideoTime(float vprice) {
        LoginUser user = ChmoApplication.getApp().getLoginUser();
        float balance = Float.parseFloat(user.coin_a);
        float time = balance / vprice;
        return Math.round(time);
    }


    public interface VChatCallback {
        void startVChat();
    }
}
