package com.maplehaze.adsdk.demo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.maplehaze.adsdk.base.MhCouponInfo;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.util.Util;
import com.maplehaze.adsdk.MaplehazeSDK;
import com.maplehaze.adsdk.MessageDialogActivity;
import com.maplehaze.adsdk.TextDialogActivity;
import com.maplehaze.adsdk.WebViewActivity;
import com.maplehaze.adsdk.bean.AdEffect;
import com.maplehaze.adsdk.bid.MhBiddingLossReason;
import com.maplehaze.adsdk.demo.utils.AutoFitViewSizeUtil;
import com.maplehaze.adsdk.demo.utils.CouponUtil;
import com.maplehaze.adsdk.demo.utils.DensityUtil;
import com.maplehaze.adsdk.demo.utils.MhGlideUtil;
import com.maplehaze.adsdk.demo.utils.NativeUtil;
import com.maplehaze.adsdk.demo.utils.OaidGetHelper;
import com.maplehaze.adsdk.demo.utils.RadioGroupUtil;
import com.maplehaze.adsdk.demo.utils.RandomAdUtil;
import com.maplehaze.adsdk.demo.utils.RestartUtl;
import com.maplehaze.adsdk.demo.utils.SharePfUtil;
import com.maplehaze.adsdk.demo.utils.ToastUtil;
import com.maplehaze.adsdk.nativ.NativeAd;
import com.maplehaze.adsdk.nativ.NativeAdData;
import com.maplehaze.adsdk.view.ext.NativeShakeLayout;
import com.maplehaze.adsdk.view.ext.MhDownloadCancelDialog;
import com.maplehaze.adsdk.view.ext.NativeWiggleLayout;

import java.util.ArrayList;
import java.util.List;

public class NativeActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "NativeActivity";
    private LinearLayout showAdContain;
    private EditText mPostIdEt;
    private ScrollView mScrollView;
    private List<NativeAdData> mAdData = null;
    private NativeAdData clickNativeAdData;
    private CheckBox mImage16_9, mImage9_16, mImage20_3, mImage1_1;

    private boolean isEnableServerConfig = false;

    private boolean mIsMute = false;
    private MhDownloadCancelDialog downloadCancelConfirmDialog;
    private static final int AD_COUNT = 2;

    private boolean isEcpm;
    private boolean isAdCallback;
    private int biddingPrice;
    private boolean isNoBiddingCompatibilityModel;
    private boolean isAdContainShow=true;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_native);
        showAdContain = findViewById(R.id.show_ad_contain);

        mPostIdEt = ((EditText) findViewById(R.id.posId));
        mPostIdEt.setText(Constants.NATIVE_POS_ID);
        isEcpm = SharePfUtil.getEcpmConfig(this);
        isAdCallback = SharePfUtil.getAdCallBackToastConfig(this);
        biddingPrice = SharePfUtil.getBiddingPrice(this);
        isNoBiddingCompatibilityModel = SharePfUtil.getNoBiddingCompatibilityModeSwitch(this);

        mScrollView=(ScrollView)findViewById(R.id.scrollView);
//        mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                mScrollView.post(new Runnable() {
//                    public void run() {
//                        mScrollView.fullScroll(View.FOCUS_DOWN);
//                    }
//                });
//            }
//        });

        CheckBox muteViewOptionCb = findViewById(R.id.muteOptionCb);
        muteViewOptionCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.d(TAG, "muteViewOptionCb check: " + isChecked);
                mIsMute = isChecked;
            }
        });


        CheckBox showHideAdContain = findViewById(R.id.show_hide_ad_contain);
        showHideAdContain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.d(TAG, "showHideAdContain check: " + isChecked);
                isAdContainShow=isChecked;
                if(isAdContainShow){
                    showAdContain.setVisibility(View.VISIBLE);
                }else{
                    showAdContain.setVisibility(View.INVISIBLE);
                }
            }
        });






        final CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                updatePosID();
            }
        };

        mImage16_9 = findViewById(R.id.image_16_9);
        mImage9_16 = findViewById(R.id.image_9_16);
        mImage20_3 = findViewById(R.id.image_20_3);
        mImage1_1 = findViewById(R.id.image_1_1);
        mImage16_9.setOnCheckedChangeListener(listener);
        mImage9_16.setOnCheckedChangeListener(listener);
        mImage20_3.setOnCheckedChangeListener(listener);
        mImage1_1.setOnCheckedChangeListener(listener);



        if (SharePfUtil.getDevelopMode(this)){
            isEnableServerConfig = true;
        }
        if (savedInstanceState!=null){
            RestartUtl.startClearLastTask(this);
        }
    }


    private NativeAd getNativeAd() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;

        int viewWidth = DensityUtil.px2dip(this, screenWidth) - 20; // 减去布局中的margin
        int viewHeight = 300;


        String posId = getPosID();
        NativeAd.NativeAdListener listener = new NativeAd.NativeAdListener() {

            /**
             * 广告请求完
             */
            @Override
            public void onADLoaded(final List<NativeAdData> adList) {
                Log.i(TAG, "onADLoaded");
                if (!isFinishing()){
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_load_ad_success);
                    showAdContain.removeAllViews();
                    List<NativeAdData> adDataList=new ArrayList<>();
                    if (adList!=null){
                        adDataList.add(adList.get(0));
                    }

                    if (isNoBiddingCompatibilityModel) {//兼容非竞价模式广告位
                        List<NativeAdData> resultList = noBiddingCompatibilityModeAd(adDataList);
                        if (!resultList.isEmpty()) {
                            releaseAd(mAdData);
                            mAdData = resultList;
                            showAdList(resultList);
                        } else {
                            ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
                        }
                    } else {//竞价模式
                        List<NativeAdData> resultList = biddingAd(adDataList);
                        if (resultList.size() > 0) {
                            releaseAd(mAdData);
                            mAdData = resultList;
                            showAdList(resultList);
                        } else {
                            if (!isEcpm) {
                                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_bidding_ad);
                            }
                        }
                    }
                }else{
                    Log.e(TAG, "activity isFinishing no need onADLoaded");
                }
            }

            @Override
            public void onNoAD() {
                Log.i(TAG, "onNoAD");
                showAdContain.removeAllViews();
            }

            @Override
            public void onADError(int error) {
                Log.i(TAG, "onADError error==" + error);
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_ad_error, error));
            }
        };


        // view宽高需要传dp
        NativeAd nativeAd = new NativeAd(this.getApplicationContext(), posId, viewWidth, viewHeight, AD_COUNT, listener);
        nativeAd.setMute(mIsMute);
        //---------------only for test -----------------------
        if (SharePfUtil.getDevelopMode(this)){
            nativeAd.setTestEnableServerConfig(true);//  only for demo
        }else{
            nativeAd.setTestEnableServerConfig(isEnableServerConfig);//  only for demo
        }
        //---------------only for test -----------------------
        return nativeAd;
    }


    private List<NativeAdData> biddingAd(List<NativeAdData> adList) {
        List<NativeAdData> resultList = new ArrayList<>();
        //竞价广告位需要和运营申请开通，非竞价模式返回的ecpm不作为有效价格
        int bidPrice = biddingPrice; //演示媒侧多预算价格过滤
        for (int i = 0; i < adList.size(); i++) {
            NativeAdData item = adList.get(i);
            int adEcpm = item.getEcpm();
            Log.i(TAG, "adEcpm=" + adEcpm + " bidPrice=" + bidPrice);
            if (adEcpm >= bidPrice) {
                resultList.add(item);
                //上报竞价成功，需要展示前上报
                int winPrice = adEcpm;//竞胜成交价
                item.sendWinNotification(winPrice);
                if (isEcpm) {
                    ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_success, adEcpm));
                }
            } else {
                //MhBiddingLossReason.LOW_PRICE 竞争力不足
                //MhBiddingLossReason.NOT_COMPETITION 有广告回包但是未参与竞价
                //MhBiddingLossReason.NO_AD 无广告回包
                //MhBiddingLossReason.OTHER 其他（有回包）
                int winPrice = 1000;//竞胜方出价，接入的时候需要传入竞胜方出价
                item.sendLossNotification(winPrice, MhBiddingLossReason.LOW_PRICE);
                if (isEcpm) {
                    ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_fial, adEcpm));
                }

            }
        }
        return resultList;
    }


    private List<NativeAdData> noBiddingCompatibilityModeAd(List<NativeAdData> adList) {
        List<NativeAdData> resultList = new ArrayList<>();
        //竞价广告位需要和运营申请开通，非竞价模式返回的ecpm不作为有效价格
        for (int i = 0; i < adList.size(); i++) {
            NativeAdData item = adList.get(i);
            int adEcpm = item.getEcpm();
            if (adEcpm == -1) {//非竞价广告
                Log.i(TAG, "非竞价广告 adEcpm=" + adEcpm);
                resultList.add(item);
                if (isEcpm) {
                    ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_no_bidding_ecpm, adEcpm));
                }
            } else {
                int bidPrice = biddingPrice; //演示媒侧多预算价格过滤
                Log.i(TAG, "adEcpm=" + adEcpm + " bidPrice=" + bidPrice);
                if (adEcpm >= bidPrice) {
                    resultList.add(item);
                    //上报竞价成功，需要展示前上报
                    int winPrice = adEcpm;//竞胜成交价
                    item.sendWinNotification(winPrice);
                    if (isEcpm) {
                        ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_success, adEcpm));
                    }
                } else {
                    //MhBiddingLossReason.LOW_PRICE 竞争力不足
                    //MhBiddingLossReason.NOT_COMPETITION 有广告回包但是未参与竞价
                    //MhBiddingLossReason.NO_AD 无广告回包
                    //MhBiddingLossReason.OTHER 其他（有回包）
                    int winPrice = 1000;//竞胜方出价，接入的时候需要传入竞胜方出价
                    item.sendLossNotification(winPrice, MhBiddingLossReason.LOW_PRICE);
                    if (isEcpm) {
                        ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_fial, adEcpm));
                    }
                }
            }
        }
        return resultList;
    }


    private void showAdList(List<NativeAdData> resultList) {
        for (int i = 0; i < resultList.size(); i++) {
            NativeAdData item = resultList.get(i);
            if (item.getNativeType() == NativeAdData.IMAGE) {
                handleImageItem(item);
            } else if (item.getNativeType() == NativeAdData.VIDEO) {
                handleVideoItem(item);
            }

        }
    }


    private void handleImageItem(NativeAdData adData) {
        Log.d(TAG, "xxx handleImageItem");
        Log.d(TAG, "xxx title:" + adData.getTitle());//标题
        Log.d(TAG, "xxx desc:" + adData.getDesc());//描述
        Log.d(TAG, "xxx icon url:" + adData.getIconUrl());//logo
        Log.d(TAG, "xxx img url:" + adData.getImgUrl());//图片地址
        Log.d(TAG, "xxx native isDownloadType:" + adData.isDownloadType());//是否下载类型广告
        Log.d(TAG, "xxx direct:" + adData.getDirectionType());// 1为横向图片或视频，2为竖向图片或视频
        Log.d(TAG, "xxx isShakeInterfaceEffect:" + adData.isShakeInterfaceEffect());// 是否是摇一摇类型广告
        Log.d(TAG, "xxx width:" + adData.getWidth() + "  height:" + adData.getHeight());//素材宽高，部分素材没有返回宽高
        // interact_type:
        // 0 --- 打开网页
        // 1 --- app下载
        Log.d(TAG, "xxx interact type:" + adData.getInteractType());

        ViewGroup viewContainer = adData.getAdRootView(NativeActivity.this);

        @SuppressLint("InflateParams") View adView = getLayoutInflater().inflate(R.layout.native_ad_layout, null);
        viewContainer.addView(adView);

        @SuppressLint("InflateParams") View spaceView = getLayoutInflater().inflate(R.layout.native_space_layout, null);
        ViewGroup appContainer = viewContainer.findViewById(R.id.ad_download_container);
        ImageView appIcon = viewContainer.findViewById(R.id.app_icon);
        TextView appName = viewContainer.findViewById(R.id.app_title);
        TextView appDesc = viewContainer.findViewById(R.id.app_desc);


        ImageView adImage = viewContainer.findViewById(R.id.ad_image);
        ViewGroup adImageLayout = viewContainer.findViewById(R.id.ad_image_layout);


        ViewGroup h5Container = viewContainer.findViewById(R.id.ad_h5_container);
        ImageView h5Icon = viewContainer.findViewById(R.id.h5_icon);
        TextView h5Title = viewContainer.findViewById(R.id.h5_title);
        TextView h5Desc = viewContainer.findViewById(R.id.h5_desc);
        TextView h5OpenBtn = viewContainer.findViewById(R.id.h5_open_btn);
        TextView appDownloadBtn = viewContainer.findViewById(R.id.app_download_btn);
        TextView appDownloading = viewContainer.findViewById(R.id.mh_app_downloading_btn);
        ProgressBar appDownloadingProgressbar = viewContainer.findViewById(R.id.mh_app_download_progressbar);
        ImageView appDownloadCancel = viewContainer.findViewById(R.id.mh_app_download_cancel);
        View appDownloadingLayout = viewContainer.findViewById(R.id.mh_app_downloading_layout);


        appDownloadCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDownloadCancelConfirmDialog(adData);
            }
        });
        ImageView adLogoIv = viewContainer.findViewById(R.id.ad_logo_iv);
        adLogoIv.setImageResource(adData.getAdLogoDrawableRes());//整图(广告 logo+文字)
        //adData.getAdLogoName();//单广告文字
        //adData.getAdLogoImageDrawableRes();//单广告logo


        View downloadLayout = viewContainer.findViewById(R.id.mh_download_layout);
        if (adData.isDownloadType()) {//是否下载类型广告

            downloadLayout.setVisibility(View.VISIBLE);
            TextView appVersionTv = downloadLayout.findViewById(R.id.mh_app_version_tv);
            TextView appNameTv = downloadLayout.findViewById(R.id.mh_app_name_tv);
            setTextviewString(appNameTv, adData.getAppName());
            setTextviewString(appVersionTv, adData.getAppVersion());

            TextView appPublisherTv = downloadLayout.findViewById(R.id.mh_app_publisher_tv);
            setTextviewString(appPublisherTv, adData.getPublisher());

            downloadLayout.findViewById(R.id.mh_privacy_detail_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(adData.getPrivacyUrl())) {
                        WebViewActivity.skipWebViewActivity(NativeActivity.this, adData.getPrivacyUrl());
                    }
                }
            });

            downloadLayout.findViewById(R.id.mh_app_permissions_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(adData.getPermission())) {
                        MessageDialogActivity.skipMessageDialogActivity(NativeActivity.this, NativeActivity.this.getResources().getString(R.string.mh_app_permissions), adData.getPermission());
                    } else if (!TextUtils.isEmpty(adData.getPermissionUrl())) {
                        WebViewActivity.skipWebViewActivity(NativeActivity.this, adData.getPermissionUrl());
                    }
                }
            });

            downloadLayout.findViewById(R.id.mh_app_info_detail_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(adData.getAppInfo())) {
                        TextDialogActivity.skipTextDialogActivity(NativeActivity.this, NativeActivity.this.getResources().getString(R.string.mh_app_info), adData.getAppInfo());
                    } else if (!TextUtils.isEmpty(adData.getAppInfoUrl())) {
                        WebViewActivity.skipWebViewActivity(NativeActivity.this, adData.getAppInfoUrl());
                    }
                }
            });

        } else {
            downloadLayout.setVisibility(View.GONE);
        }


        if (adData.getInteractType() == 0) {
            if (TextUtils.isEmpty(adData.getIconUrl())) {
                h5Icon.setVisibility(View.GONE);
            } else {
                h5Icon.setVisibility(View.VISIBLE);
                Glide.with(NativeActivity.this).load(adData.getIconUrl()).skipMemoryCache(true).into(h5Icon);
            }
            h5Title.setText(adData.getTitle());
            h5Desc.setText(adData.getDesc());
            // 广告转化文案
            h5OpenBtn.setText(adData.getActionDescription());
            appContainer.setVisibility(View.GONE);
            h5Container.setVisibility(View.VISIBLE);
        } else if (adData.getInteractType() == 1) {
            if (TextUtils.isEmpty(adData.getIconUrl())) {
                appIcon.setVisibility(View.GONE);
            } else {
                appIcon.setVisibility(View.VISIBLE);
                Glide.with(NativeActivity.this).load(adData.getIconUrl()).skipMemoryCache(true).into(appIcon);
            }
            appName.setText(adData.getTitle());
            appDesc.setText(adData.getDesc());
            appDownloadBtn.setText(adData.getActionDescription());
            appContainer.setVisibility(View.VISIBLE);
            h5Container.setVisibility(View.GONE);
        }

        String imageUrl = adData.getImgUrl();
        if (Util.isOnMainThread() && !isFinishing()) {
            Glide.with(NativeActivity.this)
                    .load(imageUrl)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {

                            if (!isFinishing()){
                                if (adImage == null || adImageLayout == null) {
                                    return false;
                                }
                                if (adImage.getScaleType() != ImageView.ScaleType.FIT_XY) {
                                    adImage.setScaleType(ImageView.ScaleType.FIT_XY);
                                }

                                if (resource != null && resource.getIntrinsicHeight() != 0 && resource.getIntrinsicWidth() != 0) {
                                    //一个广告可能配置不同尺寸的广告，尺寸按比例设置
                                    AutoFitViewSizeUtil.fitViewSize(adImageLayout, adImage, resource.getIntrinsicHeight(), resource.getIntrinsicWidth());
                                }
                            }
                            return false;
                        }
                    })
                    .into(adImage);
        }

        adData.registerNativeItemListener(new NativeAdData.NativeAdItemListener() {
            /**
             * 广告曝光
             */
            @Override
            public void onADExposed() {
                Log.i(TAG, "xxx onADExposed");
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), "广告展示");
                }

            }

            /**
             * 广告点击
             */
            @Override
            public void onADClicked() {
                Log.i(TAG, "xxx onADClicked");
                clickNativeAdData=adData;
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), "广告点击");
                }
            }

            /**
             * 广告关闭
             */
            @Override
            public void onADClosed() {
                Log.i(TAG, "xxx onADClosed");
            }

            /**
             * 下载中
             */
            @Override
            public void onProgressUpdate(int progress) {
                Log.i(TAG, "xxx onProgressUpdate, progress: " + progress);

                appDownloadingLayout.setVisibility(View.VISIBLE);
                appDownloadBtn.setVisibility(View.GONE);
                appDownloadCancel.setVisibility(View.GONE);
                appDownloadingProgressbar.setProgress(progress);
                appDownloading.setText("暂停下载");
                appDownloading.setSelected(true);
            }

            /**
             * 下载完成
             */
            @Override
            public void onDownloadFinished() {
                Log.i(TAG, "xxx onDownloadFinished");
                appDownloadCancel.setVisibility(View.VISIBLE);
                appDownloadingLayout.setVisibility(View.GONE);
                appDownloadBtn.setVisibility(View.VISIBLE);
                appDownloadBtn.setText("立即安装");
                appDownloading.setText("立即安装");
                appDownloading.setSelected(false);
            }

            /**
             * 下载安装完成
             */
            @Override
            public void onInstalled() {
                Log.i(TAG, "xxx onInstalled");
                appDownloadCancel.setVisibility(View.VISIBLE);
                appDownloadingLayout.setVisibility(View.GONE);
                appDownloadBtn.setVisibility(View.VISIBLE);
                appDownloadBtn.setText("立即打开");
                appDownloading.setText("立即打开");
                appDownloading.setSelected(false);
            }

            /**
             * 下载暂停
             */
            @Override
            public void onStop() {
                Log.i(TAG, "xxx onStop");
                appDownloading.setSelected(false);
                appDownloadingLayout.setVisibility(View.VISIBLE);
                appDownloadBtn.setVisibility(View.GONE);
                appDownloading.setText("继续下载");
                appDownloadCancel.setVisibility(View.VISIBLE);
            }

            /**
             * 下载取消
             */
            @Override
            public void onCancel() {
                Log.i(TAG, "xxx onCancel");
                appDownloadCancel.setVisibility(View.VISIBLE);
                appDownloadingLayout.setVisibility(View.GONE);
                appDownloadBtn.setVisibility(View.VISIBLE);
                appDownloadBtn.setText("立即下载");
                appDownloading.setText("立即下载");
                appDownloading.setSelected(false);
            }

            /**
             * 下载失败
             */
            @Override
            public void onDownloadFailed() {
                Log.i(TAG, "xxx onDownloadFailed");
            }

            /**
             * 视频播放开始
             */
            @Override
            public void onVideoPlayStart() {
                Log.i(TAG, "xxx onVideoPlayStart");
            }

            /**
             * 播放完成
             */
            @Override
            public void onVideoPlayComplete() {
                Log.i(TAG, "xxx onVideoPlayComplete");
            }

            /**
             * 视频播放出错
             * @param error
             */
            @Override
            public void onVideoPlayError(int error) {
                Log.i(TAG, "xxx onVideoPlayError");
            }
        });
        viewContainer.findViewById(R.id.ad_dislike).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    showAdContain.removeView(viewContainer);
                    showAdContain.removeView(spaceView);
                    ToastUtil.showToast(getApplicationContext(),R.string.mh_demo_ad_close);
                }catch (Exception ignored){

                }

            }
        });
        //可点击的View的列表
        List<View> clickViews = new ArrayList<>();


        //1.可以将摇扭控件添加需要添加的位置，也可以自己封装一下布局
        ViewGroup shakeContainer = viewContainer.findViewById(R.id.ad_shake_container);

        if (adData.isShakeInterfaceEffect()) {//2.判断是否支持摇一摇，返回true
            Log.d(TAG, "xxx isShakeInterfaceEffect true");
            shakeContainer.removeAllViews();
            final NativeShakeLayout shakeLayout = new NativeShakeLayout(getApplicationContext());
            shakeContainer.setVisibility(View.VISIBLE);
            //3.添加摇一摇控件到父布局
            shakeContainer.addView(shakeLayout);
            //4.注册摇一摇事件
            shakeLayout.bindAd(adData);
            //5.添加摇一摇点击事件
            clickViews.add(shakeLayout);//摇一摇可以触发点击事件（可选）
            //6.添加摇一摇回调
            shakeLayout.setOnShakeCallBack(new NativeShakeLayout.ShakeCallBack() {
                @Override
                public void shakeStart() {

                }

                @Override
                public void shakeEnd(View v, float x, float y, float z) {
                    Log.i(TAG, "xxx shakeEnd");
                }
            });
        }else if (adData.isWiggleInterfaceEffect()){//2.判断是否支持扭一扭，返回true
            shakeContainer.removeAllViews();
            final NativeWiggleLayout wiggleLayout = new NativeWiggleLayout(getApplicationContext());
            shakeContainer.setVisibility(View.VISIBLE);
            //3.添加扭一扭控件到父布局
            //如果shakeContainer设置的是wrap_content，需要设置宽高。宽高比1：1 设置固定宽高例如：shakeContainer.addView(wiggleLayout,new ViewGroup.LayoutParams(100,100));
            shakeContainer.addView(wiggleLayout,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
            //4.注册扭一扭事件
            wiggleLayout.bindAd(adData);
            //5.添加扭一扭点击事件
            clickViews.add(wiggleLayout);//扭一扭可以触发点击事件（可选）

        }else {
            Log.d(TAG, "xxx isShakeInterfaceEffect false");
            shakeContainer.setVisibility(View.GONE);
            shakeContainer.removeAllViews();
        }
//        clickViews.add(viewContainer);
//        clickViews.add(adImage);
        clickViews.add(h5OpenBtn);


        //用于下载，查看详情，立即安装，打开的按钮
        List<View> creativeViews = new ArrayList<>();
        creativeViews.add(appDownloadBtn);
        creativeViews.add(appDownloading);

        if (adData.getCouponInfo()!=null){
            View couponView= CouponUtil.getCouponView(NativeActivity.this,adData.getCouponInfo());
            TextView actionTv=couponView.findViewById(R.id.tv_action);
            adImageLayout.addView(couponView,CouponUtil.getFrameLayoutParams());
            creativeViews.add(actionTv);
        }



        // 注册点击曝光函数
        //原生点击曝光函数onExposed参数creativeViews点击可以直接下载或进入落地页，clickViews为触发广告点击行为的View
        adData.onExposed(viewContainer, creativeViews, clickViews);

        showAdContain.addView(viewContainer);
        showAdContain.addView(spaceView);
    }


    private void showDownloadCancelConfirmDialog(NativeAdData tmpData) {
        if (downloadCancelConfirmDialog == null) {
            downloadCancelConfirmDialog = new MhDownloadCancelDialog(NativeActivity.this);
        }
        downloadCancelConfirmDialog.setDownloadListener(new MhDownloadCancelDialog.Listener() {
            @Override
            public void onCancel(View v) {
                downloadCancelConfirmDialog.dismiss();
            }

            @Override
            public void onOk(View v) {
                downloadCancelConfirmDialog.dismiss();
                if (tmpData != null) {
                    tmpData.cancelDownload();
                }
            }
        });
        try {
            downloadCancelConfirmDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void handleVideoItem(NativeAdData adData) {
        Log.d(TAG, "xxx handleVideoItem");
        Log.d(TAG, "xxx title:" + adData.getTitle());//标题
        Log.d(TAG, "xxx desc:" + adData.getDesc());//描述
        Log.d(TAG, "xxx icon url:" + adData.getIconUrl());//logo
        Log.d(TAG, "xxx img url:" + adData.getImgUrl());//图片地址
        Log.d(TAG, "xxx native isDownloadType:" + adData.isDownloadType());//是否下载类型广告
        Log.d(TAG, "xxx direct:" + adData.getDirectionType());// 1为横向图片或视频，2为竖向图片或视频
        Log.d(TAG, "xxx isShakeInterfaceEffect:" + adData.isShakeInterfaceEffect());// 释放是摇一摇类型广告
        Log.d(TAG, "xxx width:" + adData.getWidth() + "  height:" + adData.getHeight());//素材宽高，部分素材没有返回宽高

        // interact_type:
        // 0 --- 打开网页
        // 1 --- app下载
        Log.d(TAG, "xxx interact type:" + adData.getInteractType());

        ViewGroup rootView = adData.getAdRootView(NativeActivity.this);
        View viewContainer = getLayoutInflater().inflate(R.layout.native_item_video, rootView, true);


        @SuppressLint("InflateParams") View spaceView = getLayoutInflater().inflate(R.layout.native_space_layout, null);

//        TextView adDes = viewContainer.findViewById(R.id.ad_desc);
//        adDes.setText(adData.getDesc());

        FrameLayout videoContainer = viewContainer.findViewById(R.id.video_container);
        // 0为横向图片或视频，1为竖向图片或视频
//        if (adData.getDirectionType() == 1) {
//            ViewGroup.LayoutParams params = videoContainer.getLayoutParams();
//            params.width = dip2px(this, 112);
//            videoContainer.setLayoutParams(params);
//        }
        videoContainer.setVisibility(View.INVISIBLE);
        viewContainer.post(new Runnable() {
            @Override
            public void run() {
                videoContainer.setVisibility(View.VISIBLE);//这里使用一套布局适配不同尺寸的布局，防止尺寸改变闪一下
                //一个广告可能配置不同尺寸的广告，尺寸按比例设置
                AutoFitViewSizeUtil.fitViewSize(viewContainer, videoContainer, adData.getHeight(), adData.getWidth());
            }
        });


        videoContainer.removeAllViews();



        ViewGroup appContainer = viewContainer.findViewById(R.id.ad_download_container);
        ImageView appIcon = viewContainer.findViewById(R.id.app_icon);
        TextView appName = viewContainer.findViewById(R.id.app_title);
        TextView appDesc = viewContainer.findViewById(R.id.app_desc);


        ViewGroup h5Container = viewContainer.findViewById(R.id.ad_h5_container);
        ImageView h5Icon = viewContainer.findViewById(R.id.h5_icon);
        TextView h5Title = viewContainer.findViewById(R.id.h5_title);
        TextView h5Desc = viewContainer.findViewById(R.id.h5_desc);
        TextView h5OpenBtn = viewContainer.findViewById(R.id.h5_open_btn);


        TextView appDownloadBtn = viewContainer.findViewById(R.id.app_download_btn);
        TextView appDownloading = viewContainer.findViewById(R.id.mh_app_downloading_btn);
        ProgressBar appDownloadingProgressbar = viewContainer.findViewById(R.id.mh_app_download_progressbar);
        ImageView appDownloadCancel = viewContainer.findViewById(R.id.mh_app_download_cancel);
        View appDownloadingLayout = viewContainer.findViewById(R.id.mh_app_downloading_layout);

        appDownloadCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDownloadCancelConfirmDialog(adData);
            }
        });

        ImageView adLogoIv = viewContainer.findViewById(R.id.ad_logo_iv);
        adLogoIv.setImageResource(adData.getAdLogoDrawableRes());//整图(广告 logo+文字)
//        adData.getAdLogoName();//单广告文字
//        adData.getAdLogoImageDrawableRes();//单广告logo


        View downloadLayout = viewContainer.findViewById(R.id.mh_download_layout);
        if (adData.isDownloadType()) {
            downloadLayout.setVisibility(View.VISIBLE);
            TextView appVersionTv = downloadLayout.findViewById(R.id.mh_app_version_tv);
            TextView appNameTv = downloadLayout.findViewById(R.id.mh_app_name_tv);
            setTextviewString(appNameTv, adData.getAppName());
            setTextviewString(appVersionTv, adData.getAppVersion());

            TextView appPublisherTv = downloadLayout.findViewById(R.id.mh_app_publisher_tv);
            setTextviewString(appPublisherTv, adData.getPublisher());

            downloadLayout.findViewById(R.id.mh_privacy_detail_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(adData.getPrivacyUrl())) {
                        WebViewActivity.skipWebViewActivity(NativeActivity.this, adData.getPrivacyUrl());
                    }
                }
            });

            downloadLayout.findViewById(R.id.mh_app_permissions_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(adData.getPermission())) {
                        MessageDialogActivity.skipMessageDialogActivity(NativeActivity.this, NativeActivity.this.getResources().getString(R.string.mh_app_permissions), adData.getPermission());
                    } else if (!TextUtils.isEmpty(adData.getPermissionUrl())) {
                        WebViewActivity.skipWebViewActivity(NativeActivity.this, adData.getPermissionUrl());
                    }
                }
            });

            downloadLayout.findViewById(R.id.mh_app_info_detail_tv).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(adData.getAppInfo())) {
                        TextDialogActivity.skipTextDialogActivity(NativeActivity.this, NativeActivity.this.getResources().getString(R.string.mh_app_info), adData.getAppInfo());
                    } else if (!TextUtils.isEmpty(adData.getAppInfoUrl())) {
                        WebViewActivity.skipWebViewActivity(NativeActivity.this, adData.getAppInfoUrl());
                    }
                }
            });

        } else {
            downloadLayout.setVisibility(View.GONE);
        }


        if (adData.getInteractType() == 0) {
            if (TextUtils.isEmpty(adData.getIconUrl())) {
                h5Icon.setVisibility(View.GONE);
            } else {
                h5Icon.setVisibility(View.VISIBLE);
                Glide.with(NativeActivity.this).load(adData.getIconUrl()).skipMemoryCache(true).into(h5Icon);
            }
            h5Title.setText(adData.getTitle());
            h5Desc.setText(adData.getDesc());
            // 广告转化文案
            h5OpenBtn.setText(adData.getActionDescription());
            appContainer.setVisibility(View.GONE);
            h5Container.setVisibility(View.VISIBLE);
        } else if (adData.getInteractType() == 1) {
            if (TextUtils.isEmpty(adData.getIconUrl())) {
                appIcon.setVisibility(View.GONE);
            } else {
                appIcon.setVisibility(View.VISIBLE);
                Glide.with(NativeActivity.this).load(adData.getIconUrl()).skipMemoryCache(true).into(appIcon);
            }
            appName.setText(adData.getTitle());
            appDesc.setText(adData.getDesc());
            appDownloadBtn.setText(adData.getActionDescription());
            appContainer.setVisibility(View.VISIBLE);
            h5Container.setVisibility(View.GONE);
        }


        adData.registerNativeItemListener(new NativeAdData.NativeAdItemListener() {


            /**
             * 曝光
             */
            @Override
            public void onADExposed() {
                Log.i(TAG, "xxx onADExposed");
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), "广告展示");
                }
            }

            /**
             * 广告点击
             */
            @Override
            public void onADClicked() {
                Log.i(TAG, "xxx onADClicked");
                clickNativeAdData=adData;
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), "广告点击");
                }
            }

            /**
             * 广告关闭
             */
            @Override
            public void onADClosed() {
                Log.i(TAG, "xxx onADClosed");
            }

            /**
             * 下载中
             */
            @Override
            public void onProgressUpdate(int progress) {
                Log.i(TAG, "xxx onProgressUpdate, progress: " + progress);
                appDownloadingLayout.setVisibility(View.VISIBLE);
                appDownloadBtn.setVisibility(View.GONE);
                appDownloadCancel.setVisibility(View.GONE);
                appDownloadingProgressbar.setProgress(progress);
                appDownloading.setText("暂停下载");
                appDownloading.setSelected(true);
            }

            /**
             * 下载完成
             */
            @Override
            public void onDownloadFinished() {
                Log.i(TAG, "xxx onDownloadFinished");
                appDownloadCancel.setVisibility(View.VISIBLE);
                appDownloadingLayout.setVisibility(View.GONE);
                appDownloadBtn.setVisibility(View.VISIBLE);
                appDownloadBtn.setText("立即安装");
                appDownloading.setText("立即安装");
                appDownloading.setSelected(false);
            }

            /**
             * 安装完成
             */
            @Override
            public void onInstalled() {
                Log.i(TAG, "xxx onInstalled");
                appDownloadCancel.setVisibility(View.VISIBLE);
                appDownloadingLayout.setVisibility(View.GONE);
                appDownloadBtn.setVisibility(View.VISIBLE);
                appDownloadBtn.setText("立即打开");
                appDownloading.setText("立即打开");
                appDownloading.setSelected(false);
            }

            /**
             * 广告暂停
             */
            @Override
            public void onStop() {
                Log.i(TAG, "xxx onStop");
                appDownloading.setSelected(false);
                appDownloadingLayout.setVisibility(View.VISIBLE);
                appDownloadBtn.setVisibility(View.GONE);
                appDownloading.setText("继续下载");
                appDownloadCancel.setVisibility(View.VISIBLE);
            }

            /**
             * 下载取消
             */
            @Override
            public void onCancel() {
                Log.i(TAG, "xxx onCancel");
                appDownloadCancel.setVisibility(View.VISIBLE);
                appDownloadingLayout.setVisibility(View.GONE);
                appDownloadBtn.setVisibility(View.VISIBLE);
                appDownloadBtn.setText("立即下载");
                appDownloading.setText("立即下载");
                appDownloading.setSelected(false);
            }

            /**
             * 下载失败
             */
            @Override
            public void onDownloadFailed() {
                Log.i(TAG, "xxx onDownloadFailed");
            }

            /**
             * 播放开始
             */
            @Override
            public void onVideoPlayStart() {
                Log.i(TAG, "xxx onVideoPlayStart");
            }

            /**
             * 播放完成
             */
            @Override
            public void onVideoPlayComplete() {
                Log.i(TAG, "xxx onVideoPlayComplete");
            }

            /**
             * 播放异常
             */
            @Override
            public void onVideoPlayError(int error) {
                Log.i(TAG, "xxx onVideoPlayComplete");
            }
        });
        viewContainer.findViewById(R.id.ad_dislike).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    showAdContain.removeView(rootView);
                    showAdContain.removeView(spaceView);
                    ToastUtil.showToast(getApplicationContext(),R.string.mh_demo_ad_close);
                }catch (Exception ignored){

                }

            }
        });
        //获取视频的播放的view 的adData.getVideoView(NativeActivity.this)
        videoContainer.addView(adData.getVideoView(NativeActivity.this));
        //可点击的View的列表
        List<View> clickViews = new ArrayList<>();
        //1.可以将摇扭控件添加需要添加的位置，也可以自己封装一下布局
        ViewGroup shakeContainer = viewContainer.findViewById(R.id.ad_shake_container);

        if (adData.isShakeInterfaceEffect()) {  //2.判断是否支持摇一摇，返回true
            Log.d(TAG, "xxx isShakeInterfaceEffect true");
            shakeContainer.removeAllViews();
            final NativeShakeLayout shakeLayout = new NativeShakeLayout(getApplicationContext());
            shakeContainer.setVisibility(View.VISIBLE);
            //3.添加摇一摇控件到父布局
            shakeContainer.addView(shakeLayout);
            //4.注册摇一摇事件
            shakeLayout.bindAd(adData);
            //5.添加摇一摇点击事件
            clickViews.add(shakeLayout);//摇一摇可以触发点击事件（可选）
            //6.添加摇一摇回调
            shakeLayout.setOnShakeCallBack(new NativeShakeLayout.ShakeCallBack() {
                @Override
                public void shakeStart() {

                }

                @Override
                public void shakeEnd(View v, float x, float y, float z) {
                    Log.i(TAG, "xxx shakeEnd");
                }
            });
        }else if (adData.isWiggleInterfaceEffect()){//2.判断是否支持扭一扭，返回true
            shakeContainer.removeAllViews();
            final NativeWiggleLayout wiggleLayout = new NativeWiggleLayout(getApplicationContext());
            shakeContainer.setVisibility(View.VISIBLE);
            //3.添加扭一扭控件到父布局
            //如果shakeContainer设置的是wrap_content，需要设置宽高。宽高比1：1 shakeContainer.addView(wiggleLayout,new ViewGroup.LayoutParams(100,100));
            shakeContainer.addView(wiggleLayout,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
            //4.注册扭一扭事件
            wiggleLayout.bindAd(adData);
            //5.添加扭一扭点击事件
            clickViews.add(wiggleLayout);//扭一扭可以触发点击事件（可选）

        }else {
            Log.d(TAG, "xxx isShakeInterfaceEffect false");
            shakeContainer.setVisibility(View.GONE);
            shakeContainer.removeAllViews();
        }


//        clickViews.add(viewContainer);
        clickViews.add(h5OpenBtn);

        //用于下载，查看详情，立即安装，打开的按钮
        List<View> creativeViews = new ArrayList<>();
        creativeViews.add(appDownloadBtn);
        creativeViews.add(appDownloading);

        // 注册点击曝光函数
        //原生点击曝光函数onExposed参数clickViews为触发广告点击行为的View，creativeViews点击可以直接下载或进入落地页
        adData.onExposed(viewContainer, creativeViews, clickViews);
        showAdContain.addView(rootView);
        showAdContain.addView(spaceView);
    }

    //优惠券
    private void handleCoupon(NativeAdData adData) {

        MhCouponInfo couponInfo = adData.getCouponInfo();
        if (couponInfo != null) {
            int couponType = couponInfo.getCouponType();//优惠券类型 1：满减优惠券
            int couponThreshold = couponInfo.getCouponThreshold();//满减 单位分
            int couponValue = couponInfo.getCouponValue();//优惠金额 单位分
            int couponTime = couponInfo.getCouponTime();//优惠券有效时间 单位分钟
            Log.i(TAG,"couponType="+couponType+" couponValue="+couponValue+" couponThreshold="+couponThreshold+" couponTime="+couponTime);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.load_native:
                OaidGetHelper.getInstance().initOaid(getApplicationContext());
                getNativeAd().loadAd();
                break;
        }
    }

    private void updatePosID() {
        String postId = NativeUtil.getNativeId(mImage16_9.isChecked(), mImage9_16.isChecked(), mImage20_3.isChecked(), mImage1_1.isChecked());
        mPostIdEt.setText(postId);
    }

    private String getPosID() {
        String posId = mPostIdEt.getText().toString();
        return TextUtils.isEmpty(posId) ? Constants.NATIVE_POS_ID : posId;
    }


    private void setTextviewString(TextView textView, String msg) {
        if (!TextUtils.isEmpty(msg)) {
            textView.setText(msg);
        } else {
            textView.setText("");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAdData != null) {
            for (NativeAdData ad : mAdData) {
                if (ad != null) {
                    ad.resume();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseAd(mAdData);
        mAdData = null;
        MhGlideUtil.clearMemory(this);

    }

    private void releaseAd(List<NativeAdData> list) {
        if (list != null) {
            for (NativeAdData ad : list) {
                if (ad != null) {
                    ad.destroy();
                }
            }
        }
    }


}
