package com.ym.zxhcsdk.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ym.zxhcsdk.HcDownLoadUtils;
import com.ym.zxhcsdk.HcAdBean;
import com.ym.zxhcsdk.HttpClientUtils;
import com.ym.zxhcsdk.PhoneUtils;
import com.ym.zxhcsdk.R;
import com.ym.zxhcsdk.ZXHCConstant;
import com.ym.zxhcsdk.listener.SplashAdListener;
import com.ym.zxhcsdk.manager.ZXHCAdViewManager;
import com.ym.zxhcsdk.webview.HcWebActivity;

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

public class ZXHCSplashAD {

    private Activity context;
    private String codeId;
    private SplashAdListener listener;
    private int fetchDelay;

    public ZXHCSplashAD(Activity context, String codeId, SplashAdListener listener, int fetchDelay) {
        this.context = context;
        this.codeId = codeId;
        this.listener = listener;
        this.fetchDelay = fetchDelay;
    }

//    private ConcurrentLinkedQueue<HcAdBean> splashAdBean = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<Bitmap> splashBitmap = new ConcurrentLinkedQueue<>();

    private HcAdBean adBean;
    private Bitmap bitmapImg;

    //只获取广告
    public void fetchAdOnly() {
        Map<String, String> map = new HashMap<>();
        map.put("pid", codeId);
        map.put("type", "api");
        map.put("ad_type", "3");
        map.put("ad_w", ZXHCConstant.device_width);
        map.put("ad_h", ZXHCConstant.device_height);
        HttpClientUtils.get(ZXHCConstant.BASE_URL, map, new HttpClientUtils.OnRequestCallBack() {
            @Override
            public void onSuccess(String json) {
                adBean = PhoneUtils.getInstance().jsonToObj(json);
                adBean.setShowReport(false);
                adBean.setClickReport(false);
                adBean.setClickDpLinkSucReport(false);
                adBean.setClickDpLinkfailReport(false);
                if (adBean.getSrcUrls().size() > 0) {
                    HttpClientUtils.LoadImg(adBean.getSrcUrls().get(0), new HttpClientUtils.OnRequestImgCallBack() {
                        @Override
                        public void onSuccess(Bitmap bitmap) {
                            bitmapImg = bitmap;
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listener.OnAdLoaded();
//                                    ViewGroup vp = ZXHCAdViewManager.getInstance().newFrameLayout(context);
//                                    ZXHCAdViewManager.getInstance().showAdView(context, vp, false);
//                                    showAd(vp);
                                }
                            });

                        }

                        @Override
                        public void onError(String errorMsg) {
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listener.OnError("2" + errorMsg);
                                }
                            });
                        }
                    });
                } else {
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.OnError("广告数据为0");
                        }
                    });
                }
            }

            @Override
            public void onError(String errorMsg) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listener.OnError(errorMsg);
                    }
                });

            }
        });
    }

    CountDownTimer countDownTimer = null;

    private void countDown(int time, TextView textView) {
        long times = time * 1000;
        //时间  倒计时   入参long类型
        countDownTimer = new CountDownTimer(times, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                delayTime = (int) millisUntilFinished / 1000;
                textView.setText(delayTime + "");
                if (delayTime == 0) {
                    textView.setText("跳过");
                }
            }

            @Override
            public void onFinish() {
                if (splashView != null) {
                    ZXHCAdViewManager.getInstance().removeAdView(context, splashView);
                }
                listener.OnAdClosed();
                countDownTimer.cancel();
                countDownTimer = null;
            }
        };
        countDownTimer.start();
    }


    private int delayTime;
    private TextView jumpTv;

    private ViewGroup splashView;

    public void showAd(ViewGroup vp) {
        splashView = vp;
        context.runOnUiThread(new Runnable() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public void run() {
                LayoutInflater inflater = LayoutInflater.from(context);
                View view = inflater.inflate(R.layout.hc_splash_ad, null);
                ImageView splashImg = view.findViewById(R.id.ad_id_hc_Splash_img);
                jumpTv = view.findViewById(R.id.ad_id_jump_text);
                splashImg.setImageBitmap(bitmapImg);
                delayTime = fetchDelay + 1;
                jumpTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (delayTime > 0) {
                            if (countDownTimer != null) {
                                countDownTimer.cancel();
                                countDownTimer = null;
                                ZXHCAdViewManager.getInstance().removeAdView(context, vp);
                                listener.OnAdClosed();
                            }
                        }
                    }
                });
                splashImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listener.OnAdClicked();
                        SplashAdClick(adBean);
                        ClickReport(adBean);
                    }
                });
                splashImg.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                ZXHCConstant.downX = event.getX() + "";
                                ZXHCConstant.downY = event.getY() + "";
                                ZXHCConstant.downRawX = event.getRawX() + "";
                                ZXHCConstant.downRawY = event.getRawY() + "";
                                break;
                            case MotionEvent.ACTION_MOVE:

                                break;
                            case MotionEvent.ACTION_UP:
                                ZXHCConstant.upX = event.getX() + "";
                                ZXHCConstant.upY = event.getY() + "";
                                ZXHCConstant.upRawX = event.getRawX() + "";
                                ZXHCConstant.upRawY = event.getRawY() + "";
                                break;
                        }
                        return false;
                    }
                });
                countDown(delayTime, jumpTv);
                view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                    @Override
                    public void onViewAttachedToWindow(View v) {
                        ShowReport(adBean);
                        listener.OnAdShow();
                    }

                    @Override
                    public void onViewDetachedFromWindow(View v) {
                    }
                });


                vp.addView(view);

            }
        });
    }

    private void SplashAdClick(HcAdBean adBean) {
        boolean IsSuccess = true;
        if (TextUtils.isEmpty(adBean.getDeeplink())) {
            if (!TextUtils.isEmpty(adBean.getTarget_type())) {
                if (adBean.getTarget_type().equals("0")) {//0:网页跳转 1:下载类应用（默认值 0）
                    if (adBean.getDUrl() != null && adBean.getDUrl().size() > 0) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Intent intent = new  Intent(context,    HcWebActivity.class);
                                    intent.putExtra("url",adBean.getDUrl().get(0));
                                    context.startActivity(intent);
                                }catch (ClassCastException exception){
                                    exception.printStackTrace();
                                }

                            }
                        });
                    }
                } else if (adBean.getTarget_type().equals("1")) {
                    DownLoadApk();
                }
            }
        } else {
            try {
                Uri uri = Uri.parse(adBean.getDeeplink().trim());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                IsSuccess = false;
                if (!TextUtils.isEmpty(adBean.getTarget_type())) {
                    if (adBean.getTarget_type().equals("0")) {//0:网页跳转 1:下载类应用（默认值 0）
                        if (adBean.getDUrl() != null && adBean.getDUrl().size() > 0) {
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Intent intent = new  Intent(context, HcWebActivity.class);
                                        intent.putExtra("url",adBean.getDUrl().get(0));
                                        context.startActivity(intent);
                                    }catch (ClassCastException exception){
                                        exception.printStackTrace();
                                    }

                                }
                            });
                        }
                    } else if (adBean.getTarget_type().equals("1")) {
                        DownLoadApk();
                    }
                }
            }
            if (IsSuccess) {
                dpLinkSuccessReport(adBean);
            } else {
                if (PhoneUtils.getInstance().IsInstallApp(context, adBean.getApp_name())) {
                    dpLinkFailReport(adBean, "3");
                } else {
                    dpLinkFailReport(adBean, "2");
                }
            }
        }
    }


    private void ShowReport(HcAdBean adBean) {
        if (adBean.isShowReport()) {
            return;
        }
        adBean.setShowReport(true);
        //曝光上报
        if (adBean.getMonitorUrl().size() > 0) {
            for (int i = 0; i < adBean.getMonitorUrl().size(); i++) {
                String showReport = adBean.getMonitorUrl().get(i);
                HttpClientUtils.GetEvent(showReport);
            }
        }
    }

    private void ClickReport(HcAdBean adBean) {
        if (adBean.isClickReport()) {
            return;
        }
        adBean.setClickReport(true);
        //点击上报
        if (adBean.getClickUrl().size() > 0) {
            for (int i = 0; i < adBean.getClickUrl().size(); i++) {
                String clickReport = adBean.getClickUrl().get(i);
                HttpClientUtils.GetEvent(clickReport);
            }
        }
    }

    private void dpLinkSuccessReport(HcAdBean adBean) {
        if (adBean.isClickDpLinkSucReport()) {
            return;
        }
        adBean.setClickDpLinkSucReport(true);
        //唤醒成功上报
        if (adBean.getDpSuccmonitorUrls() != null && adBean.getDpSuccmonitorUrls().size() > 0) {
            for (int i = 0; i < adBean.getDpSuccmonitorUrls().size(); i++) {
                HttpClientUtils.GetEvent(adBean.getDpSuccmonitorUrls().get(i));
            }
        }
    }

    private void dpLinkFailReport(HcAdBean adBean, String reason) {
        if (adBean.isClickDpLinkfailReport()) {
            return;
        }
        adBean.setClickDpLinkfailReport(true);
        //唤醒失败上报
        if (adBean.getDpFailmonitorUrls() != null && adBean.getDpFailmonitorUrls().size() > 0) {
            for (int i = 0; i < adBean.getDpFailmonitorUrls().size(); i++) {
                String url = adBean.getDpFailmonitorUrls().get(i);
                url = url.replace("__DP_REASON__", reason);//1-被拦截，2-应用未安装，3-调起异常 (vivo广告必须替换)
                HttpClientUtils.GetEvent(url);
            }
        }
    }

    private void DownLoadApk() {
        new HcDownLoadUtils(context).downloadAPK(adBean);
    }


}
