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.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
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.DownLoadUtils;
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.WebActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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) {
//                Gson jsons = new Gson();
//                HcAdBean adBean = jsons.fromJson(json, HcAdBean.class);
                adBean = 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(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) {
//                        Uri uri = Uri.parse(adBean.getDUrl().get(0));
//                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                        context.startActivity(intent);
                        Intent intent = new  Intent(context, WebActivity.class);
                        intent.putExtra("url",adBean.getDUrl().get(0));
                        context.startActivity(intent);
                    }
                } 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) {
//                            Uri uri = Uri.parse(adBean.getDUrl().get(0));
//                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                            context.startActivity(intent);
                            Intent intent = new  Intent(context, WebActivity.class);
                            intent.putExtra("url",adBean.getDUrl().get(0));
                            context.startActivity(intent);
                        }
                    } 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 DownLoadUtils(context).downloadAPK(adBean);
    }


    private HcAdBean jsonToObj(String jsonString) {
        HcAdBean adBean = null;
        try {
            JSONObject root = new JSONObject(jsonString);
            adBean = new HcAdBean();
            adBean.setHeight(root.optInt("height"));
            adBean.setWidth(root.optInt("width"));
            //曝光
            JSONArray monitorUrl = root.optJSONArray("monitorUrl");
            List<String> monitorList = new ArrayList<String>();
            if (monitorUrl != null) {
                for (int i = 0; i < monitorUrl.length(); i++) {
                    monitorList.add(monitorUrl.optString(i));
                }
            }
            adBean.setMonitorUrl(monitorList);

            //点击
            JSONArray clickUrl = root.optJSONArray("clickUrl");
            List<String> clickList = new ArrayList<String>();
            if (clickUrl != null) {
                for (int i = 0; i < clickUrl.length(); i++) {
                    clickList.add(clickUrl.optString(i));
                }
            }
            adBean.setClickUrl(clickList);
            //图片
            JSONArray srcUrl = root.optJSONArray("srcUrls");
            List<String> srcList = new ArrayList<String>();
            if (srcUrl != null) {
                for (int i = 0; i < srcUrl.length(); i++) {
                    srcList.add(srcUrl.optString(i));
                }
            }
            adBean.setSrcUrls(srcList);
            //落地页
            JSONArray dUrl = root.optJSONArray("dUrl");
            List<String> dList = new ArrayList<String>();
            if (dUrl != null) {
                for (int i = 0; i < dUrl.length(); i++) {
                    dList.add(dUrl.optString(i));
                }
            }
            adBean.setDUrl(dList);

            adBean.setPid(root.optString("pid"));
            adBean.setCid(root.optInt("cid"));
            adBean.setPlan_id(root.optInt("plan_id"));
            adBean.setTarget_type(root.optString("target_type"));
            adBean.setAd_show_type(root.optInt("ad_show_type"));
            adBean.setFrom(root.optString("from"));
            adBean.setReq_id(root.optString("req_id"));

            adBean.setApp_name(root.optString("app_name"));
            adBean.setPackage_name(root.optString("package_name"));
            adBean.setDown_url(root.optString("down_url"));
            adBean.setTitle(root.optString("title"));
            adBean.setContent(root.optString("content"));
            adBean.setDeeplink(root.optString("deeplink"));


            JSONArray startInstallmonitorUrl = root.optJSONArray("startInstallmonitorUrls");
            List<String> startInstallmonitorUrlList = new ArrayList<String>();
            if (startInstallmonitorUrl != null) {
                for (int i = 0; i < startInstallmonitorUrl.length(); i++) {
                    startInstallmonitorUrlList.add(startInstallmonitorUrl.optString(i));
                }
            }
            adBean.setStartInstallmonitorUrls(startInstallmonitorUrlList);

            JSONArray finishInstallmonitorUrl = root.optJSONArray("finishInstallmonitorUrls");
            List<String> finishInstallmonitorList = new ArrayList<String>();
            if (finishInstallmonitorUrl != null) {
                for (int i = 0; i < finishInstallmonitorUrl.length(); i++) {
                    finishInstallmonitorList.add(finishInstallmonitorUrl.optString(i));
                }
            }
            adBean.setFinishInstallmonitorUrls(finishInstallmonitorList);


            JSONArray startdownloadmonitorUrl = root.optJSONArray("startdownloadmonitorUrls");
            List<String> startInstallmonitorList = new ArrayList<String>();
            if (startdownloadmonitorUrl != null) {
                for (int i = 0; i < startdownloadmonitorUrl.length(); i++) {
                    startInstallmonitorList.add(startdownloadmonitorUrl.optString(i));
                }
            }
            adBean.setStartdownloadmonitorUrls(startInstallmonitorList);

            JSONArray finishdownloadmonitorUrl = root.optJSONArray("finishdownloadmonitorUrls");
            List<String> finishdownloadmonitorlList = new ArrayList<String>();
            if (finishdownloadmonitorUrl != null) {
                for (int i = 0; i < finishdownloadmonitorUrl.length(); i++) {
                    finishdownloadmonitorlList.add(finishdownloadmonitorUrl.optString(i));
                }
            }
            adBean.setFinishdownloadmonitorUrls(finishdownloadmonitorlList);

            JSONArray activemonitorUrl = root.optJSONArray("activemonitorUrls");
            List<String> activemonitorList = new ArrayList<String>();
            if (activemonitorUrl != null) {
                for (int i = 0; i < activemonitorUrl.length(); i++) {
                    activemonitorList.add(activemonitorUrl.optString(i));
                }
            }
            adBean.setActivemonitorUrls(activemonitorList);

            JSONArray dpSuccmonitorUrl = root.optJSONArray("dpSuccmonitorUrls");
            List<String> dpSuccmonitorList = new ArrayList<String>();
            if (dpSuccmonitorUrl != null) {
                for (int i = 0; i < dpSuccmonitorUrl.length(); i++) {
                    dpSuccmonitorList.add(dpSuccmonitorUrl.optString(i));
                }
            }
            adBean.setDpSuccmonitorUrls(dpSuccmonitorList);

            JSONArray dpFailmonitorUrl = root.optJSONArray("dpFailmonitorUrls");
            List<String> dpFailmonitorList = new ArrayList<String>();
            if (dpFailmonitorUrl != null) {
                for (int i = 0; i < dpFailmonitorUrl.length(); i++) {
                    dpFailmonitorList.add(dpFailmonitorUrl.optString(i));
                }
            }
            adBean.setDpFailmonitorUrls(dpFailmonitorList);

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

        return adBean;
    }
}
