package com.sunzee.mvp.advertising;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.orhanobut.hawk.Hawk;
import com.sunzee.base.BaseActivity;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.BasePresenter;
import com.sunzee.model.Global;
import com.sunzee.model.Heartbeat;
import com.sunzee.model.HttpResult;
import com.sunzee.model.domain.GetAdBean;
import com.sunzee.retrofit.ApiCallback;
import com.sunzee.utils.AlarmManagerUtil;
import com.sunzee.utils.FileUtil;
import com.wuxiaolong.androidutils.library.LogUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告界面 presenter
 * 需求：
 */
public class AdvertisingPresenter extends BasePresenter<AdvertisingView> {

    private static final String TAG = "AdvertisingPresenter";

    public AdvertisingPresenter(AdvertisingView view) {
        attachView(view);
    }


    //--------------------------------------------------------------------------广告 start----------------------------------------------------------------------------------------------
    public void play() {
        requstCleanRule();
        //2.读文件的数据
        int leftFileSize = leftVideoImageFile();
        int rightFileSize = rightVideoImageFile();
        Log.d(TAG, "initView: leftFileSize" + leftFileSize);
        Log.d(TAG, "initView: rightFileSize" + rightFileSize);
        if (leftFileSize != 0) {
            mvpView.playRight(playFile);
        }
        if (rightFileSize != 0) {
            mvpView.playLeft(playFileList);
        }
    }

    //下载在本地的所有文件
    private File[] allFiles;
    //本地所有<文件名字，文件>的对应
    private Map<String, File> playList;
    //要播放的文件
    private Map<Integer, GetAdBean> showOut;
    //要播放的文件名字(实体)
    private ArrayList<GetAdBean> names;
    //要播放的文件列表
    private List<File> allPlayList;

    /**
     * 获取左边视频图片的文件
     *
     * @return
     */
    private int rightVideoImageFile() {
        showOut = Hawk.get("show_out", new HashMap<Integer, GetAdBean>());
        Log.d(TAG, "show_out rightVideoImageFile: " + showOut);
        this.allFiles = FileUtil.getAllFiles(Environment.getExternalStorageDirectory().getPath() + "/rightvideoimg/", "");
        //判断是否为空
        if (this.allFiles == null || this.allFiles.length <= 0) {
            LogUtil.d(TAG, "rightvideoimg initView: 文件为空，没有下载");
            return 0;
        }
//获取本地所有文件的名字
        playList = new HashMap<>();
        //获取名字与文件对应关系
        for (int i = 0; i < this.allFiles.length; i++) {
            String name = this.allFiles[i].getName();
            String fileName = name.substring(0, name.length() - 4);//获取文件名
            LogUtil.d(TAG, "rightvideoimg initView: 本地所有的文件名：" + fileName);
            // 文件名 文件

            playList.put(fileName, this.allFiles[i]);
        }
        if (showOut == null || showOut.size() <= 0) {
            //没有要播放的文件
            LogUtil.d(TAG, "showOut initView: 没有要播放的文件");
            return 0;
        }
        names = new ArrayList<>();
        for (int i = 0; i < allFiles.length; i++) {
            if (showOut.get(i) != null) {
                String name = showOut.get(i).getId();
                LogUtil.d(TAG, "showOut initView: 广告选择要播放的文件名：" + name);
                names.add(showOut.get(i));
            }
        }
        if (names == null || names.size() <= 0) {
//            ToastUtil.showToast("请选择文件播放");
            LogUtil.d(TAG, "showOut initView: 没有选择播放的文件");
            return 0;
        }
        allPlayList = new ArrayList<>();
        if (playList == null || playList.size() <= 0) {
            LogUtil.d(TAG, "rightvideoimg initView: playList为空");
            return 0;
        }
        //通过名字找出要找出需要播放的文件
        for (int i = 0; i < names.size(); i++) {
            File file = playList.get(names.get(i).getId());
            if (file != null) {
                LogUtil.d(TAG, "rightvideoimg initView: 通过名字找到的播放文件：" + file.getName());
                allPlayList.add(file);
            }
        }
        if (allPlayList == null || allPlayList.size() <= 0) {
            LogUtil.d(TAG, "rightvideoimg showOUt initView: allPlayList为0");
            return 0;
        }
        return setTimeRules();
    }

    //真正要播放的文件
    private ArrayList<File> playFileList;
    //要播放的实体 用于判断是图片还是视频
    private ArrayList<GetAdBean> playRules;

    /**
     * 获取当前时间规则与要播放的文件
     */
    private int setTimeRules() {
        playFileList = new ArrayList<>();
        playRules = new ArrayList<>();
        HashMap<String, String> ad_rules_map = Hawk.get("ad_rules_map", new HashMap<String, String>());
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        LogUtil.e(TAG, "judeImgVideoAndPlay: hour=" + hour);
        //当前时间段
        String timeSort = hour + "-" + (hour + 1);
        LogUtil.d(TAG, "judeImgVideoAndPlay:timeSort= " + timeSort);
        Log.d(TAG, "setTimeRules: names" + names);
        //获取当前时间段的要播放的id
        for (int i = 0; i < names.size(); i++) {
            for (Map.Entry<String, String> entry : ad_rules_map.entrySet()) {
                entry.getKey();
                entry.getValue();
                if (entry.getValue().contains(timeSort)) {
                    if (entry.getKey().equals(names.get(i).getId())) {
                        LogUtil.d(TAG, "judeImgVideoAndPlay: 添加要播放的文件:" + names.get(i).getId());
                        playRules.add(names.get(i));
                    }
                }
            }

        }
        //获取当前时间段要播放的实体
        for (int i = 0; i < playRules.size(); i++) {

            //当前时间段要播放的文件
            File file = playList.get(playRules.get(i).getId());
            if (file != null) {
                LogUtil.d(TAG, "judeImgVideoAndPlay: 当前时间段要播放的文件的id：" + playRules.get(i).getId());
                playFileList.add(file);
            }
        }
        LogUtil.e(TAG, "setTimeRules: playFileList.size()=" + playFileList.size());
        if (playFileList.size() <= 0) {
            LogUtil.d(TAG, "playFileList: 空");
            return 0;
        }
        return playFileList.size();
    }


    //A屏 要播放的文件
    private ArrayList<File> playFile;
    private ArrayList<GetAdBean> adBeans;

    /**
     * 获取右边视频图片的文件
     *
     * @return
     */
    private int leftVideoImageFile() {
        File[] allFiles = FileUtil.getAllFiles(Environment.getExternalStorageDirectory().getPath() + "/leftvideoimg/", "");
        if (allFiles == null || allFiles.length <= 0) {
            LogUtil.e(TAG, "playCorporationAd: 没有下载A屏文件");
            return 0;
        }
        adBeans = Hawk.get("showAdA", new ArrayList<GetAdBean>());//为空
        Log.d(TAG, "showAdA leftVideoImageFile: " + adBeans);
        if (adBeans == null || adBeans.size() <= 0) {
            LogUtil.e(TAG, "playCorporationAd: 没有下载A屏数据");
            return 0;
        }

        //按照网络数据顺序添加
        playFile = new ArrayList<>();
        for (int i = 0; i < adBeans.size(); i++) {
            GetAdBean getAdBean = adBeans.get(i);
            for (int j = 0; j < allFiles.length; j++) {
                String name = allFiles[j].getName();
                LogUtil.d(TAG, "playCorporationAd: name= " + name);
                String fileName = name.substring(0, name.length() - 4);//获取文件名
                Log.d(TAG, "leftVideoImageFile: " + fileName + ":getAdBean.getId()+" + getAdBean.getId());
                if (fileName.equals(getAdBean.getId())) {
                    playFile.add(allFiles[j]);
                }
            }
        }

        if (playFile == null || playFile.size() <= 0) {
            Log.d(TAG, "playCorporationAd: 没有匹配的广告数据");
            return 0;
        }

        for (int i = 0; i < playFile.size(); i++) {
            LogUtil.d(TAG, "playCorporationAd: 本地的 name=" + playFile.get(i).getName());
            LogUtil.d(TAG, "playCorporationAd: 网络的 name=" + adBeans.get(i).getId());
        }
        return playFile.size();
    }

    //--------------------------------------------------------------------------广告 end----------------------------------------------------------------------------------------------

    private void requstCleanRule() {
        Map<String, String> params = new HashMap<>();
        params.put("clientId", Heartbeat.deviceId);
        addSubscription(apiStores.cleanRule(params), new ApiCallback<HttpResult<String>>() {
            @Override
            public void onSuccess(HttpResult<String> model) {
                String times = model.getData();
                Log.d(TAG, "onSuccess: " + times);
                if (!TextUtils.isEmpty(times)) {
                    String[] Alltime = times.split("\\,");
                    Global.alarmNumber = Alltime.length;
                    for (int i = 0; i < Alltime.length; i++) {
                        String[] data = Alltime[i].split(":");
                        for (String datum : data) {
                            Log.d(TAG, "onSuccess: "+datum);
                        }
                        //设置定时闹钟
                        AlarmManagerUtil.setAlarm(BaseApplication.getContext(), 1, Integer.valueOf(data[0]), Integer.valueOf(data[1]), Integer.valueOf(data[2]), i, 0, "闹钟响了26");
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
            }

            @Override
            public void onFinish() {
            }
        });
    }
}
