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.DownLoadUtils;
import com.ym.zxhcsdk.HcAdBean;
import com.ym.zxhcsdk.HttpClientUtils;
import com.ym.zxhcsdk.R;
import com.ym.zxhcsdk.ZXHCConstant;
import com.ym.zxhcsdk.listener.FeedAdListener;
import com.ym.zxhcsdk.manager.ZXHCAdViewManager;

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 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 =  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;
                            listener.OnAdLoaded();
                        }

                        @Override
                        public void onError(String errorMsg) {
                            listener.OnError(errorMsg);
                        }
                    });
                }

            }

            @Override
            public void onError(String errorMsg) {
                listener.OnError(errorMsg);
            }
        });
    }

//    private ViewGroup feedVp;

    public void destroyFeedAd(ViewGroup feedVp) {
        if (feedVp != null) {
            listener.OnAdClosed();
            ZXHCAdViewManager.getInstance().removeAdView(context, feedVp);
            feedVp = null;
        }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);
                Log.d("wxw", "adBean.getContent()"+adBean.getContent()+"adBean.getApp_name()"+adBean.getApp_name());
                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:
                                downX = (int) event.getX();
                                downY = (int) event.getY();
                                downRawX = (int) event.getRawX();
                                downRawY = (int) event.getRawY();
                                Log.e("WXW", "downX = " + downX + "; downY = " + downY + "; downRawX = " + downRawX + "; downRawY = " + downRawY);
                                break;
                            case MotionEvent.ACTION_MOVE:

                                break;
                            case MotionEvent.ACTION_UP:
                                upX = (int) event.getX();
                                upY = (int) event.getY();
                                upRawX = (int) event.getRawX();
                                upRawY = (int) event.getRawY();
                                Log.e("WXW", "upX = " + upX + "; upY = " + upY + "; upRawX = " + upRawX + "; upRawY = " + upRawY);
                                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;
                Log.d("wxw", "width"+width+"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) {
                        Uri uri = Uri.parse(adBean.getDUrl().get(0));
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        context.startActivity(intent);
                    }
                } else if (adBean.getTarget_type().equals("1")) {
                   new DownLoadUtils(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) {
                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);
                        }
                    } else if (adBean.getTarget_type().equals("1")) {
                        new DownLoadUtils(context).downloadAPK(adBean);
                    }
                }
            }
            if (IsSuccess) {
                dpLinkSuccessReport();
            } else {
                dpLinkFailReport();
            }
        }
    }

    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);
                clickReport.replace("__RE_DOWN_X__", downX + "");//手指按下时相对于广告位左上角的横坐标
                clickReport.replace("__RE_DOWN_Y__", downY + "");//手指按下时相对于广告位左上角的纵坐标
                clickReport.replace("__RE_UP_X__", upX + "");//手指抬起时相对于广告位左上角的横坐标
                clickReport.replace("__RE_UP_Y__", upY + "");//手指抬起时相对于广告位左上角的纵坐标
                clickReport.replace("__DOWN_X__", downRawX + "");//手指按下时相对于屏幕左上角的横坐标
                clickReport.replace("__DOWN_Y__", downRawY + "");//手指按下时相对于屏幕左上角的纵坐标
                clickReport.replace("__UP_X__", upRawX + "");//手指抬起时相对于屏幕左上角的横坐标
                clickReport.replace("__UP_Y__", upRawY + "");//手指抬起时相对于屏幕左上角的纵坐标
                clickReport.replace("__UTC_TS__", System.currentTimeMillis() + "");//客户端触发时间戳,自 1970 年起的毫秒 ，13 位
                clickReport.replace("__UTC_TS_SECOND__", System.currentTimeMillis() / 1000 + "");//客户端触发时间戳,自 1970 年起的秒 ，10 位
                clickReport.replace("__WIDTH__", "-999");//实际广告位的宽，单位为像素
                clickReport.replace("__HEIGHT__", "-999");//实际广告位的高，单位为像素
                clickReport.replace("__LATITUDE__", "-999");//地理位置信息, 纬度
                clickReport.replace("__LONGITUDE__", "-999");//地理位置信息, 经度
                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);
                showReport.replace("__RE_DOWN_X__", downX + "");//手指按下时相对于广告位左上角的横坐标
                showReport.replace("__RE_DOWN_Y__", downY + "");//手指按下时相对于广告位左上角的纵坐标
                showReport.replace("__RE_UP_X__", upX + "");//手指抬起时相对于广告位左上角的横坐标
                showReport.replace("__RE_UP_Y__", upY + "");//手指抬起时相对于广告位左上角的纵坐标
                showReport.replace("__DOWN_X__", downRawX + "");//手指按下时相对于屏幕左上角的横坐标
                showReport.replace("__DOWN_Y__", downRawY + "");//手指按下时相对于屏幕左上角的纵坐标
                showReport.replace("__UP_X__", upRawX + "");//手指抬起时相对于屏幕左上角的横坐标
                showReport.replace("__UP_Y__", upRawY + "");//手指抬起时相对于屏幕左上角的纵坐标
                showReport.replace("__UTC_TS__", System.currentTimeMillis() + "");//客户端触发时间戳,自 1970 年起的毫秒 ，13 位
                showReport.replace("__UTC_TS_SECOND__", System.currentTimeMillis() / 1000 + "");//客户端触发时间戳,自 1970 年起的秒 ，10 位
                showReport.replace("__WIDTH__", "-999");//实际广告位的宽，单位为像素
                showReport.replace("__HEIGHT__", "-999");//实际广告位的高，单位为像素
                showReport.replace("__LATITUDE__", "-999");//地理位置信息, 纬度
                showReport.replace("__LONGITUDE__", "-999");//地理位置信息, 经度
                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() {
        if (adBean.isClickDpLinkfailReport()){
            return;
        }
        adBean.setClickDpLinkfailReport(true);
        //唤醒失败上报
        if (adBean.getDpFailmonitorUrls() != null && adBean.getDpFailmonitorUrls().size() > 0) {
            for (int i = 0; i < adBean.getDpFailmonitorUrls().size(); i++) {
                HttpClientUtils.GetEvent(adBean.getDpFailmonitorUrls().get(i));
            }
        }
    }




    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;
    }

}
