package com.ym.zxhcsdk.ads;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;

import com.ym.zxhcsdk.HcDownLoadUtils;
import com.ym.zxhcsdk.HttpClientUtils;
import com.ym.zxhcsdk.PhoneUtils;
import com.ym.zxhcsdk.R;
import com.ym.zxhcsdk.listener.RewardVideoAdUpdateViewListener;
import com.ym.zxhcsdk.webview.HcWebActivity;

public class RewardvideoPortraitADActivity extends Activity implements SurfaceHolder.Callback, RewardVideoAdUpdateViewListener {

    private SurfaceView sfv_reward_show;
    private SurfaceHolder surfaceHolder;
    private FrameLayout frameView;

    private TextView bottomTitle;
    private TextView bottomDesc;
    private ImageView bottomIcon;
    private TextView bottomBtnTv;
    private TextView TopTimeTv;
    private ImageView TopClose;
    private ImageView ivPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rewardvideo_portrait_a_d);
        bindViews();
        RewardVideoMediaPlayer.getInstance().setRewardVideoUpdateListener(this);//设置播放回调监听，更新Activity View
    }

    private void bindViews() {
        sfv_reward_show = findViewById(R.id.sfv_reward_video_ad_show);
        frameView = findViewById(R.id.frame_content);
        bottomTitle = findViewById(R.id.reward_video_ad_title);
        bottomDesc = findViewById(R.id.reward_video_ad_desc);
        bottomIcon = findViewById(R.id.reward_ad_app_icon);
        bottomBtnTv = findViewById(R.id.reward_video_ad_btn);
        TopTimeTv = findViewById(R.id.reward_ad_time);
        TopClose = findViewById(R.id.reward_ad_close);
        ivPreview = findViewById(R.id.id_iv_preview);

//        设置底部信息
        bottomTitle.setText(RewardVideoMediaPlayer.getInstance().getHcAdBean().getVideo_title());
        bottomDesc.setText(RewardVideoMediaPlayer.getInstance().getHcAdBean().getVideo_desc());
        bottomBtnTv.setText(RewardVideoMediaPlayer.getInstance().getHcAdBean().getVideo_iconbuttontext());
        //设置底部logo
        HttpClientUtils.LoadImg(RewardVideoMediaPlayer.getInstance().getHcAdBean().getVideo_icon_url(), new HttpClientUtils.OnRequestImgCallBack() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        bottomIcon.setImageBitmap(bitmap);
                    }
                });
            }

            @Override
            public void onError(String errorMsg) {

            }
        });
        //设置预览图
        HttpClientUtils.LoadImg(RewardVideoMediaPlayer.getInstance().getHcAdBean().getVideo_cover_image(), new HttpClientUtils.OnRequestImgCallBack() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ivPreview.setImageBitmap(bitmap);
                    }
                });
            }

            @Override
            public void onError(String errorMsg) {

            }
        });




        findViewById(R.id.ll_bottom_download).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RewardVideoMediaPlayer.getInstance().clickVideoAd();
                RewardVideoAdClick();

            }
        });
        //初始化SurfaceHolder类，SurfaceView的控制器
        surfaceHolder = sfv_reward_show.getHolder();
        surfaceHolder.addCallback(this);
        SetAdVideo();

        TopClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

//TODO 点击按钮，跳转的落地页, 或者是软件下载地
//址。（可通过 target_type 字段判断是到普通
//落地页还是下载 app，唤醒则通过 deeplink 是
//否为空判断）   确认video_endbutoonurl 具体含义   以及跳转Web的路径
    private void RewardVideoAdClick() {
        boolean IsSuccess = true;
        if (TextUtils.isEmpty(RewardVideoMediaPlayer.getInstance().getHcAdBean().getDeeplink())) {
            if (!TextUtils.isEmpty(RewardVideoMediaPlayer.getInstance().getHcAdBean().getTarget_type())) {
                if (RewardVideoMediaPlayer.getInstance().getHcAdBean().getTarget_type().equals("0")) {//0:网页跳转 1:下载类应用（默认值 0）
                    if (RewardVideoMediaPlayer.getInstance().getHcAdBean().getDUrl() != null && RewardVideoMediaPlayer.getInstance().getHcAdBean().getDUrl().size() > 0) {
                        try {
                            Intent intent = new  Intent(RewardvideoPortraitADActivity.this, HcWebActivity.class);
                            intent.putExtra("url",RewardVideoMediaPlayer.getInstance().getHcAdBean().getDUrl().get(0));
                            startActivity(intent);
                        }catch (ClassCastException exception){
                            exception.printStackTrace();
                        }
                    }
                } else if (RewardVideoMediaPlayer.getInstance().getHcAdBean().getTarget_type().equals("1")) {
                    new HcDownLoadUtils(this).downloadAPK(RewardVideoMediaPlayer.getInstance().getHcAdBean());
                }
            }
        } else {
            try {
                Uri uri = Uri.parse(RewardVideoMediaPlayer.getInstance().getHcAdBean().getDeeplink().trim());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } catch (Exception e) {
                IsSuccess=false;
                if (!TextUtils.isEmpty(RewardVideoMediaPlayer.getInstance().getHcAdBean().getTarget_type())) {
                    if (RewardVideoMediaPlayer.getInstance().getHcAdBean().getTarget_type().equals("0")) {//0:网页跳转 1:下载类应用（默认值 0）
                        if (RewardVideoMediaPlayer.getInstance().getHcAdBean().getDUrl() != null && RewardVideoMediaPlayer.getInstance().getHcAdBean().getDUrl().size() > 0) {
                            try {
                                Intent intent = new  Intent(RewardvideoPortraitADActivity.this, HcWebActivity.class);
                                intent.putExtra("url",RewardVideoMediaPlayer.getInstance().getHcAdBean().getDUrl().get(0));
                                startActivity(intent);
                            }catch (ClassCastException exception){
                                exception.printStackTrace();
                            }
                        }
                    } else if (RewardVideoMediaPlayer.getInstance().getHcAdBean().getTarget_type().equals("1")) {
                        new HcDownLoadUtils(this).downloadAPK(RewardVideoMediaPlayer.getInstance().getHcAdBean());
                    }
                }
            }
            if (IsSuccess) {
                dpLinkSuccessReport();
            } else {
                if (PhoneUtils.getInstance().IsInstallApp(this,RewardVideoMediaPlayer.getInstance().getHcAdBean().getApp_name())){
                    dpLinkFailReport("3");
                }else {
                    dpLinkFailReport("2");
                }
            }
        }
    }

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

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


    private void SetAdVideo(){
        TopClose.setVisibility(View.GONE);
        TopTimeTv.setVisibility(View.VISIBLE);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        Log.d("wxw", "surfaceCreated");
        RewardVideoMediaPlayer.getInstance().getMediaPlayer().setDisplay(surfaceHolder);
        RewardVideoMediaPlayer.getInstance().startVideo();
    }

    @Override
    public void OnShowListener() {
        ivPreview.setVisibility(View.GONE);
    }

    /**
     * 播放激励视频完成回调
     */
    @Override
    public void OnCompletionListener() {
        TopClose.setVisibility(View.VISIBLE);
        TopTimeTv.setVisibility(View.GONE);
    }

    /**
     * 播放激励视频错误回调
     * @param error
     */
    @Override
    public void OnErrorListener(String error) {
        TopClose.setVisibility(View.VISIBLE);
        TopTimeTv.setVisibility(View.GONE);
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        Log.d("wxw", "surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        Log.d("wxw", "surfaceDestroyed");
    }

    private int delayTime;
    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() {
                countDownTimer.cancel();
                countDownTimer = null;
            }
        };
        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RewardVideoMediaPlayer.getInstance().closeVideoAdPage();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}