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.os.Handler;
import android.os.Message;
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;


import java.util.Timer;
import java.util.TimerTask;

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;
    private Timer mTimer;//倒计时
    private final int countDownWhat = 0;
    private boolean isSetDisplay = false;
    private boolean isVideoCompletion = false;//是否播放完成

    @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();
            }
        });

        //倒计时
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (RewardVideoMediaPlayer.getInstance().isPrepared) {//等待资源加载完成
                    if ((RewardVideoMediaPlayer.getInstance().getMediaPlayer().getCurrentPosition() / 1000)
                            < (RewardVideoMediaPlayer.getInstance().getMediaPlayer().getDuration() / 1000)) {
                        mHandler.sendEmptyMessage(countDownWhat);
                    }
                }
            }
        }, 0,1000);
    }

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case countDownWhat:
                    TopTimeTv.setText((RewardVideoMediaPlayer.getInstance().getMediaPlayer().getDuration() / 1000)
                            - (RewardVideoMediaPlayer.getInstance().getMediaPlayer().getCurrentPosition() / 1000) + " s");
                    break;
            }
        }
    };


    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(RewardVideoMediaPlayer.getInstance().getActivity()).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(RewardVideoMediaPlayer.getInstance().getActivity()).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);

        //设置声音按钮
        ImageView soundImgOpen = findViewById(R.id.reward_ad_sound_open);
        ImageView soundImgClose = findViewById(R.id.reward_ad_sound_close);
        soundImgOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soundImgOpen.setVisibility(View.GONE);
                soundImgClose.setVisibility(View.VISIBLE);
                RewardVideoMediaPlayer.getInstance().getMediaPlayer().setVolume(0,0);

            }
        });

        soundImgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soundImgClose.setVisibility(View.GONE);
                soundImgOpen.setVisibility(View.VISIBLE);
                RewardVideoMediaPlayer.getInstance().getMediaPlayer().setVolume(1,1);
            }
        });


    }

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

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

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

    /**
     * 播放激励视频错误回调
     * @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");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isSetDisplay) {
            if (!isVideoCompletion) {
                if (!RewardVideoMediaPlayer.getInstance().getMediaPlayer().isPlaying()) {
                    RewardVideoMediaPlayer.getInstance().startVideo();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (RewardVideoMediaPlayer.getInstance().getMediaPlayer().isPlaying()) {
            RewardVideoMediaPlayer.getInstance().getMediaPlayer().pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RewardVideoMediaPlayer.getInstance().closeVideoAdPage();
        mTimer.cancel();
        mHandler.removeCallbacksAndMessages(null);
    }

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