package com.yutou.jianr_mg.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.Holder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qq.e.ads.banner2.UnifiedBannerADListener;
import com.qq.e.ads.banner2.UnifiedBannerView;
import com.qq.e.comm.util.AdError;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.MAdConfig;
import com.yutou.jianr_mg.Data.MAppHomeConfig;
import com.yutou.jianr_mg.Data.MBanner;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.AdTools;
import com.yutou.jianr_mg.Tools.Log;
import com.yutou.jianr_mg.Tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class HomeHeader {
    private static final String APPID = "1105364182";
    private static final String POSID = "1030169024275783";
    private static HomeHeader header;
    private MAppHomeConfig homeConfig;
    private ConvenientBanner banner;
    private Context context;
    private ImageLoader imageLoader;
    private LinearLayout layout;
    private LinearLayout home, action;

    private TextView hitokoto, from, time;
    private Timer timer;
    private boolean isFlash = false;
    private Handler handler;
    private MAdConfig ad;

    public static HomeHeader getHome(Context context) {
        if (header == null) {
            System.out.println("初始化头部");
            header = new HomeHeader(context);
        }
        return header;
    }

    private HomeHeader(Context context) {
        this.context = context;
        handler = new Handler();
        initBanner();
        initGameActivity();
        isFlash = true;
        imageLoader = Utils.initImageLoader(context);
        layout = new LinearLayout(context);
        home = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.item_home, null, true);
        hitokoto = home.findViewById(R.id.hitokoto);
        from = home.findViewById(R.id.from);
        time = home.findViewById(R.id.action_time);
        action = home.findViewById(R.id.action);
        timer = new Timer();

        action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (homeConfig != null) {
                    Utils.openWebView(homeConfig.getUrl());
                }
            }
        });
        initAd();
    }
    private void initAd(){
        try {
            JSONObject json = new JSONObject();
            json.put("type", 3);
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.AD_GET, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        if (json.getInt("code") == 100) {
                            ad = JSON.parseObject(json.getJSONObject("data").toString(), MAdConfig.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                        AppData.handler.post(()->showAdBanner());
                }

                @Override
                public void httpError(Exception e) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void startGameActivity() {
        timer.schedule(new TimerTask() {
            private String text;

            @Override
            public void run() {
                isFlash = true;
                long nowDate = System.currentTimeMillis();
                Date action_time = null;
                if (nowDate < homeConfig.getStartdate().getTime()) {
                    text = homeConfig.getName() + "\n距离活动开始:";
                    action_time = homeConfig.getStartdate();
                }
                if (nowDate > homeConfig.getStartdate().getTime() && nowDate < homeConfig.getEnddate().getTime()) {
                    text = homeConfig.getName() + "\n距离活动结束:";
                    action_time = homeConfig.getEnddate();
                }
                if(nowDate > homeConfig.getEnddate().getTime()){
                    text ="\n活动已结束~";
                    action_time=null;
                }
                if (action_time != null) {
                    long now_time = System.currentTimeMillis() / 1000;
                    long activityTime = action_time.getTime() / 1000;
                    long s = (activityTime - now_time) % 60;
                    long m = (activityTime - now_time) / 60 % 60;
                    long h = (activityTime - now_time) / 60 / 60;
                    text += h + ":" + m + ":" + s;
                }
                handler.post(() -> time.setText(text));

            }
        }, 0, 1000);
    }

    private Context getContext() {
        return context;
    }

    public View getView() {
        //flashHome();
        layout.removeAllViews();
        layout.setOrientation(LinearLayout.VERTICAL);
        banner = new ConvenientBanner(getContext());
        ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 400);
        banner.setLayoutParams(params);
        layout.addView(banner);
        layout.addView(home);
        return layout;
    }
    UnifiedBannerView bannerView;
    private void showAdBanner(){
        AdTools.upload(AdTools.Banner,AdTools.req);
        bannerView=new UnifiedBannerView((Activity) context, APPID, POSID, new UnifiedBannerADListener() {
            @Override
            public void onNoAD(AdError adError) {
              //  Utils.toast(getContext(),adError.getErrorMsg());
              Log.e("Banner错误：",adError.getErrorMsg());
            }

            @Override
            public void onADReceive() {
                System.out.println("测试Receive");
            }

            @Override
            public void onADExposure() {
                AdTools.upload(AdTools.Banner,AdTools.show);
            }

            @Override
            public void onADClosed() {

            }

            @Override
            public void onADClicked() {
                AdTools.upload(AdTools.Banner,AdTools.click);
                bannerView.destroy();
            }

            @Override
            public void onADLeftApplication() {

            }

            @Override
            public void onADOpenOverlay() {

            }

            @Override
            public void onADCloseOverlay() {

            }
        });
        bannerView.loadAD();

        layout.addView(bannerView);
    }

    public void setBanner(List<MBanner> list) {
        banner.setCanLoop(true);
        banner.startTurning(2000);
        banner.setPages(() -> new Banner(), list).setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
    }

    public void flashHome() {
        if (!isFlash) {
            return;
        }
        isFlash = false;
        System.out.println("刷新一言");
        HttpUtils.get(HttpApi.HITOKOTO_API, new HttpInterface() {
            JSONObject json = new JSONObject();

            @Override
            public void httpGetData(String string, int code) {
                try {
                    json = new JSONObject(string);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                AppData.handler.post(() -> {
                    try {
                        hitokoto.setText(json.getString("hitokoto"));
                        from.setText("---" + json.getString("from"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                });
            }

            @Override
            public void httpError(Exception e) {

            }
        });
    }

    private void initBanner() {

        HttpUtils.get(HttpApi.HOME_URL + HttpApi.BANNER, new HttpInterface() {
            @Override
            public void httpError(Exception e) {
                e.printStackTrace();
            }

            @Override
            public void httpGetData(String string, int code) {
                final List<MBanner> array;
                try {
                    Log.i("banner", string);
                    JSONObject json = new JSONObject(string);

                    if (json.getInt("code") == 100) {
                        array = JSON.parseArray(json.getString("data"), MBanner.class);
                    } else {
                        array = new ArrayList<>();
                    }
                    AppData.handler.post(() -> setBanner(array));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initGameActivity() {
        HttpUtils.get(HttpApi.HOME_URL + HttpApi.MG_GAME_ACTIVITY, new HttpInterface() {
            @Override
            public void httpGetData(String string, int code) {
                try {
                    JSONObject json = new JSONObject(string);
                    if (json.getInt("code") == 100) {
                        JSONObject data = new JSONObject(json.getString("data"));
                        homeConfig = new MAppHomeConfig();
                        homeConfig.setName(data.getString("name"));
                        homeConfig.setUrl(data.getString("url"));
                        homeConfig.setStartdate(new Date(data.getLong("startdate")));
                        homeConfig.setEnddate(new Date(data.getLong("enddate")));
                        homeConfig.setState(data.getInt("state"));
                        if (homeConfig.getState() == 1 || homeConfig.getState() == -1) {
                            handler.postDelayed(() -> startGameActivity(), 300);
                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.post(() -> time.setText("咕咕咕？"));
            }

            @Override
            public void httpError(Exception e) {

            }
        });
    }

    private class Banner implements Holder<MBanner> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            imageView.setLayoutParams(params);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, final MBanner data) {
            try {
                imageLoader.displayImage(data.getUrl(), imageView);
                imageView.setOnClickListener(view -> {
                    Intent intent;
                    if(data.getClick().startsWith("appWeb")){
                        intent = new Intent(getContext(),WebActivity.class);
                        intent.putExtra("url",data.getClick().substring(6));
                    }else {
                        intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(data.getClick()));
                    }
                    context.startActivity(intent);
                });
            }catch (Exception ignored){

            }

        }
    }
}
