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.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.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.FeedAdListener;
import com.ym.zxhcsdk.manager.ZXHCAdViewManager;
import com.ym.zxhcsdk.webview.HcWebActivity;

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

public class ZXHCFeedAD {

    private Activity context;
    private String codeId;
    private int width;
    private int height;
    private FeedAdListener listener;

    public ZXHCFeedAD(Activity context, String codeId, int width, int height, FeedAdListener listener) {
        this.context = context;
        this.codeId = codeId;
        this.width = width;
        this.height = height;
        this.listener = listener;
    }

    private HcAdBean adBean;
    private Bitmap mBitmap;

    public void loadAD() {
        Map<String, String> map = new HashMap<>();
        map.put("pid", codeId);
        map.put("type", "api");
        map.put("ad_type", "3");
        map.put("ad_w", width + "");
        map.put("ad_h", 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) {
                            mBitmap = bitmap;
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listener.OnAdLoaded();
                                }
                            });
                        }

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

            }

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

//    private ViewGroup feedVp;

    public void destroyFeedAd(ViewGroup feedVp) {
        if (feedVp != null) {
            ZXHCAdViewManager.getInstance().removeAdView(context, feedVp);
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    listener.OnAdClosed();
                }
            });
        } else {
            Log.d("wxw", "feedAd null");
        }
    }

    //private int downX = -999, downY = -999, downRawX = -999, downRawY = -999, upX = -999, upY = -999, upRawX = -999, upRawY = -999;

    public void showAd(ViewGroup vp) {
//        feedVp = vp;
        context.runOnUiThread(new Runnable() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public void run() {
                LayoutInflater inflater = LayoutInflater.from(context);
                View view = inflater.inflate(R.layout.hc_feed_ad, null);

                TextView desc = view.findViewById(R.id.id_ad_feed_desc);
                TextView title = view.findViewById(R.id.id_ad_feed_title);
                desc.setText(adBean.getContent());
                title.setText(adBean.getTitle());
                ImageView feedImg = view.findViewById(R.id.id_ad_feed_img);
                ImageView closeImg = view.findViewById(R.id.id_ad_feed_close);
                feedImg.setImageBitmap(mBitmap);
                closeImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        destroyFeedAd(vp);
                    }
                });
                feedImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listener.OnAdClicked();
                        FeedAdClick();
                        ClickReport();
                    }
                });

                feedImg.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;
                    }
                });
                view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                    @Override
                    public void onViewAttachedToWindow(View v) {
                        ShowReport();
                        listener.OnAdShow();
                    }

                    @Override
                    public void onViewDetachedFromWindow(View v) {
                    }
                });
                vp.addView(view);
                ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                layoutParams.width = width;
                layoutParams.height = height;
                view.setLayoutParams(layoutParams);
            }
        });
    }

    private void FeedAdClick() {
        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")) {
                    new HcDownLoadUtils(context).downloadAPK(adBean);
                }
            }
        } 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")) {
                        new HcDownLoadUtils(context).downloadAPK(adBean);
                    }
                }
            }
            if (IsSuccess) {
                dpLinkSuccessReport();
            } else {
                if (PhoneUtils.getInstance().IsInstallApp(context,adBean.getApp_name())){
                    dpLinkFailReport("3");
                }else {
                    dpLinkFailReport("2");
                }
            }
        }
    }

    private void ClickReport() {
        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 ShowReport() {
        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 dpLinkSuccessReport() {
        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(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 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;
//    }

}
