package com.ym.zxhcsdk;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import java.io.File;

import static android.content.Context.DOWNLOAD_SERVICE;

public class  HcDownLoadUtils {
    private DownloadManager downloadManager = null;

    //下载的ID
//    private long downloadId = 0;
//    private String filePath = null;
//    private String mFileName;
//    private boolean isDownloading = false;
    private Activity activity;

//    private List<HcAdBean>

    public HcDownLoadUtils(Activity activity) {
        this.activity = activity;
        //注册广播监测下载情况
        activity.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        this.downloadManager = (DownloadManager) HcAppliContext.get().getSystemService(DOWNLOAD_SERVICE);
    }

    //下载apk
    public boolean downloadAPK(HcAdBean adBean) {
//        if (ZXHCConstant.adList.size()<=0){
//            return false;
//        }
        for (int i = 0; i < ZXHCConstant.adList.size(); i++) {
            if (ZXHCConstant.adList.get(i).getDown_url().equals(adBean.getDown_url())) {
                if (ZXHCConstant.adList.get(i).isDownOver()) {
                    try {
                        installAPK(ZXHCConstant.adList.get(i));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        }

        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(adBean.getDown_url()));
//        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://203.187.160.132:9011/qd.shouji.qihucdn.com/c3pr90ntc0td/nqapk/sjzs2_100000003_5f1aaeb8c462450478/201012/d1208503899d47cab3251dfaa06aaf95/appstore-300090091.apk"));
//        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://a.xzfile.com/apk/tuan800_downcc.apk"));
        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false);
        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle(adBean.getTitle());
        request.setDescription(adBean.getContent());
        request.setVisibleInDownloadsUi(true);
        if (TextUtils.isEmpty(adBean.getApp_name())) {
            adBean.setApp_name(adBean.getTitle());
        }
        //设置下载的路径
        File file = new File(activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), adBean.getApp_name() + "");
        if (file.exists()) {
            file.delete();
        }
        request.setDestinationUri(Uri.fromFile(file));
        String filePath = file.getAbsolutePath();
        adBean.setDownLoadFilePath(filePath);
        //获取DownloadManager
        if (downloadManager == null)
            downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列，加入下载队列后会给该任务返回一个long型的id，通过该id可以取消任务，重启任务、获取下载的文件等等
        if (downloadManager != null) {
            long downloadId = downloadManager.enqueue(request);
            adBean.setDownLoadId(downloadId);
        }
        DownLoadStartReport(adBean);
        adBean.setDownOver(false);
        ZXHCConstant.adList.add(adBean);
        return true;
    }

    //广播监听下载的各个状态
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            for (int i = 0; i < ZXHCConstant.adList.size(); i++) {
                checkStatus(ZXHCConstant.adList.get(i), i);
            }
        }
    };

    //检查下载状态
    private void checkStatus(HcAdBean adBean, int i) {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(adBean.getDownLoadId());
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
//                    Log.d("wxw", "下载暂停" + adBean.getDownLoadId());
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
//                    Log.d("wxw", "下载延迟" + adBean.getDownLoadId());
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
//                    Log.d("wxw", "正在下载" + adBean.getDownLoadId());
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    cursor.close();
//                    Log.d("wxw", "下载完成" + adBean.getDownLoadId());
                    DownLoadSuccessReport(adBean);
                    //下载完成安装APK
                    installAPK(adBean);
                    adBean.setDownOver(true);
                    ZXHCConstant.adList.set(i, adBean);
                    activity.unregisterReceiver(receiver);
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
//                    Log.d("wxw", "下载失败" + adBean.getDownLoadId());
                    cursor.close();
                    break;
            }
        }
    }


    private void installAPK(HcAdBean adBean) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Android 7.0以上要使用FileProvider
        File file = new File(adBean.getDownLoadFilePath());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(activity, PhoneUtils.getInstance().getAppPackage() + ".zxhc.fileProvider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS, adBean.getApp_name())), "application/vnd.android.package-archive");
        }
        activity.startActivity(intent);
        InstallStartReport(adBean);
    }


    private void DownLoadSuccessReport(HcAdBean adBean) {

        if (adBean.getFinishdownloadmonitorUrls() != null && adBean.getFinishdownloadmonitorUrls().size() > 0) {
            for (int i = 0; i < adBean.getFinishdownloadmonitorUrls().size(); i++) {
                HttpClientUtils.GetEvent(adBean.getFinishdownloadmonitorUrls().get(i));
            }
        }

    }

    private void DownLoadStartReport(HcAdBean adBean) {
        if (adBean.getStartdownloadmonitorUrls() != null && adBean.getStartdownloadmonitorUrls().size() > 0) {
            for (int i = 0; i < adBean.getStartdownloadmonitorUrls().size(); i++) {
                HttpClientUtils.GetEvent(adBean.getStartdownloadmonitorUrls().get(i));
            }
        }
    }

    private void InstallStartReport(HcAdBean adBean) {
        if (adBean.getStartInstallmonitorUrls() != null && adBean.getStartInstallmonitorUrls().size() > 0) {
            for (int i = 0; i < adBean.getStartInstallmonitorUrls().size(); i++) {
                HttpClientUtils.GetEvent(adBean.getStartInstallmonitorUrls().get(i));
            }
        }
    }


}
