package com.bokecc.livemodule.live.courseware;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bokecc.common.utils.Tools;
import com.bokecc.dwlivedemo.R;
import com.bokecc.dwlivedemo.download.FileUtil;
import com.bokecc.livemodule.live.DWLiveCoreHandler;
import com.bokecc.livemodule.live.DWLiveCoursewareListener;
import com.bokecc.livemodule.live.courseware.adapter.CoursewareAdapter;
import com.bokecc.livemodule.live.courseware.bean.CoursewareBean;
import com.bokecc.livemodule.view.gift.interfaces.OnClickBottomStatusListener;
import com.bokecc.sdk.mobile.live.BaseLiveCallback;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.pojo.CoursewareInfo;
import com.bokecc.sdk.mobile.live.replay.DWLiveReplay;
import com.liulishuo.okdownload.DownloadListener;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
import com.liulishuo.okdownload.core.dispatcher.DownloadDispatcher;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 课件下载控件
 * 说明：此组件初始化（调用initData()方法）前，必现为直播登录成功状态
 */
public class CoursewareComponent extends LinearLayout {

    private static final String TAG = "CoursewareComponent";

    private  String ROOT_PATH ;

    private Context mContext;

    private RecyclerView rvFileList;
    private CoursewareAdapter coursewareAdapter;

    private HashMap<CoursewareBean,DownloadTask> taskHashMap = new HashMap<>();
    private RelativeLayout llCoursewareEmpty;

    private OnCoursewareMessageListener onCoursewareMessageListener;

    private boolean isLive = true;

    public CoursewareComponent(Context context) {
        super(context);
        mContext = context;

        ROOT_PATH = FileUtil.getCCDownLoadPath(getContext())+"/courseware/";

        initView();
        initData();
    }

    public CoursewareComponent(Context context,boolean isLive) {
        super(context);
        mContext = context;
        this.isLive = isLive;

        ROOT_PATH = FileUtil.getCCDownLoadPath(getContext())+"/courseware/";

        initView();
        initData();
    }



    public CoursewareComponent(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
        initData();

    }

    // 设置直播间标题和简介
    public void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.portrait_file_layout, this, true);

        rvFileList = this.findViewById(R.id.rv_file_list);
        llCoursewareEmpty = this.findViewById(R.id.rl_courseware_empty);

        rvFileList.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));

        coursewareAdapter = new CoursewareAdapter(getContext());

        coursewareAdapter.setOnDownClickListener(new CoursewareAdapter.OnDownClickListener() {
            @Override
            public void onDownClick(CoursewareBean bean) {
                if (bean.getStatus()==CoursewareBean.STATUS_NORMAL){
                    //执行下载
                    handleDownload(bean);
                }else if (bean.getStatus()==CoursewareBean.STATUS_FETCHING){
                    //下载中，取消下载
                    cancelDown(bean);
                }else if (bean.getStatus()==CoursewareBean.STATUS_FETCHED){
                    //下载完成，执行打开
                    handleOpen(bean);

                }
            }
        });

        rvFileList.setAdapter(coursewareAdapter);
    }

    private void initData() {
        //最大并行下载数
        DownloadDispatcher.setMaxParallelRunningCount(1);
        BaseLiveCallback baseLiveCallback = new BaseLiveCallback<CoursewareInfo, Integer>() {
            @Override
            public void onSuccess(CoursewareInfo data) {
                if (data!=null&&data.getDocs()!=null&& !data.getDocs().isEmpty()){
                    llCoursewareEmpty.setVisibility(View.GONE);
                    for (int i = 0; i < data.getDocs().size(); i++) {
                        CoursewareInfo.DocsDTO docsDTO = data.getDocs().get(i);
                        if (docsDTO!=null){
                            CoursewareBean coursewareBean = new CoursewareBean();
                            coursewareBean.setName(docsDTO.getName());
                            coursewareBean.setSize(docsDTO.getFileSize());
                            coursewareBean.setDocId(docsDTO.getId());
                            coursewareBean.setType(docsDTO.getType());
                            File file = getDocFile(docsDTO.getId());
                            if (file!=null&&file.exists()&&file.length()==docsDTO.getFileSize()){
                                coursewareBean.setStatus(CoursewareBean.STATUS_FETCHED);
                            }else {
                                coursewareBean.setStatus(CoursewareBean.STATUS_NORMAL);
                            }
                            if (coursewareAdapter!=null){
                                coursewareAdapter.getList().add(coursewareBean);
                            }
                        }
                    }

                }else {
                    llCoursewareEmpty.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(Integer error) {
                Toast.makeText(mContext, "获取课件列表失败，请重试", Toast.LENGTH_SHORT).show();

            }
        };
        if (isLive){
            DWLiveCoreHandler.getInstance().setDwLiveCoursewareListener(new DWLiveCoursewareListener() {
                @Override
                public void onCoursewareEvent(CoursewareInfo coursewareInfo) {
                    if (coursewareInfo!=null&&coursewareInfo.getDocs()!=null&& !coursewareInfo.getDocs().isEmpty()){
                        for (int i = 0; i < coursewareInfo.getDocs().size(); i++) {
                            CoursewareInfo.DocsDTO docsDTO = coursewareInfo.getDocs().get(i);
                            if (onCoursewareMessageListener!=null){
                                onCoursewareMessageListener.onMessage(docsDTO.getSendStatus());
                            }
                            if (docsDTO.getSendStatus()==0){
                                //收到课件下载取消消息
                                if(coursewareAdapter!=null&&coursewareAdapter.getList()!=null){
                                    Iterator iterator = coursewareAdapter.getList().iterator();
                                    while (iterator.hasNext()){
                                        CoursewareBean coursewareBean = (CoursewareBean) iterator.next();
                                        if (coursewareBean!=null){
                                            if(coursewareBean.getDocId().equals(docsDTO.getId())){
                                                iterator.remove();
                                            }
                                        }
                                    }
                                }
                            }else {

                                //收到课件下载推送消息
                                if (docsDTO!=null){
                                    CoursewareBean coursewareBean = new CoursewareBean();
                                    coursewareBean.setName(docsDTO.getName());
                                    coursewareBean.setSize(docsDTO.getFileSize());
                                    coursewareBean.setDocId(docsDTO.getId());
                                    coursewareBean.setType(docsDTO.getType());
                                    File file = getDocFile(docsDTO.getId());
                                    if (file!=null&&file.exists()&&file.length()==docsDTO.getFileSize()){
                                        coursewareBean.setStatus(CoursewareBean.STATUS_FETCHED);
                                    }else {
                                        coursewareBean.setStatus(CoursewareBean.STATUS_NORMAL);
                                    }
                                    if (coursewareAdapter!=null){
                                        coursewareAdapter.getList().add(coursewareBean);
                                    }
                                }
                            }
                        }
                        coursewareAdapter.notifyDataSetChanged();
                        if (coursewareAdapter.getList().isEmpty()){
                            llCoursewareEmpty.setVisibility(View.VISIBLE);
                        }else {
                            llCoursewareEmpty.setVisibility(View.GONE);
                        }
                    }

                }
            });
            DWLive.getInstance().getCoursewareList(1, 50, baseLiveCallback);
        }else {
            //在线回放
            DWLiveReplay.getInstance().getCoursewareList(1, 50, baseLiveCallback);
        }


    }


    private void handleOpen(CoursewareBean bean) {
        File file = getDocFile(bean.getDocId());
        if (file!=null&&file.exists()){
            // 创建 Intent
            Intent intent = new Intent(Intent.ACTION_VIEW);
            String type = "application/pdf";
            if (bean.getType()==CoursewareBean.FILE_TYPE_PDF){
                type = "application/pdf";
            }else if (bean.getType()==CoursewareBean.FILE_TYPE_DOC){
                type = "application/msword";
            }else if (bean.getType()==CoursewareBean.FILE_TYPE_PPT){
                type = "application/vnd.ms-powerpoint";
            }else if (bean.getType()==CoursewareBean.FILE_TYPE_IMAGE){
                type = "image/*";
            }else if (bean.getType()==CoursewareBean.FILE_TYPE_GIF){
                type = "application/image";
            }else {
                type = "text/plain";
            }
            Uri pptUri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file);

            // 设置文件路径
            intent.setDataAndType(pptUri, type);
            // 添加 FLAG_ACTIVITY_NEW_TASK 标志
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            getContext().startActivity(intent);
        }
    }

    private void handleDownload(final CoursewareBean bean) {
        BaseLiveCallback baseLiveCallback = new BaseLiveCallback<String, Integer>() {
            @Override
            public void onSuccess(String url) {
                if (TextUtils.isEmpty(url)){
                    Toast.makeText(mContext, "获取下载链接失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                //{"docs":[{"docId":"05D49C38A5EEFFFE9C33DC5901307461","url":"http:\/\/doc-origin.csslcloud.net\/document\/521ABDCC70BBD79E9C33DC5901307461\/05D49C38A5EEFFFE9C33DC5901307461.pdf"}]}
                //添加进下载队列
                bean.setUrl(url);
                startDownload(bean);

            }

            @Override
            public void onError(Integer error) {
                Toast.makeText(mContext, "获取下载信息失败，请重试", Toast.LENGTH_SHORT).show();
            }
        };
        if (isLive){
            DWLive.getInstance().getCoursewareDownUrl(bean.getDocId(), baseLiveCallback);
        }else {
            DWLiveReplay.getInstance().getCoursewareDownUrl(bean.getDocId(), baseLiveCallback);
        }
    }



    private void cancelDown(CoursewareBean bean){
        if (taskHashMap.containsKey(bean)){
            DownloadTask task = taskHashMap.get(bean);
            if (task!=null){
                task.cancel();
            }
            bean.setStatus(CoursewareBean.STATUS_NORMAL);
            if (coursewareAdapter!=null){
                coursewareAdapter.notifyDataSetChanged();
            }

        }
    }

    private void cancelAllDown(){
        for (CoursewareBean bean:taskHashMap.keySet()){
            cancelDown(bean);
        }
    }


    private String getMediaFilePathFromUrl(String docId,String url){
        String nameUrl = url;
        //去掉参数
        if (url.contains("?")){
            nameUrl = url.substring(0, url.lastIndexOf("?"));
        }
        String suffix = nameUrl.substring(nameUrl.lastIndexOf(".") + 1);

        String path = ROOT_PATH + Tools.getMD5Str(docId) + "." + suffix;
        return path;
    }
    private String getMediaFileNameFromUrl(String docId,String url){
        String nameUrl = url;
        //去掉参数
        if (url.contains("?")){
            nameUrl = url.substring(0, url.lastIndexOf("?"));
        }
        String suffix = nameUrl.substring(nameUrl.lastIndexOf(".") + 1);

        String path = Tools.getMD5Str(docId) + "." + suffix;
        return path;
    }
    private void startDownload(final CoursewareBean bean) {
        if (taskHashMap.containsKey(bean)){
            return;
        }
        String path = getMediaFilePathFromUrl(bean.getDocId(), bean.getUrl());
        String fileName = getMediaFileNameFromUrl(bean.getDocId(), bean.getUrl());

        Log.i(TAG, "startDownload: path="+path);

        File file = new File(path);
        if (!file.exists()){
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        bean.setLocalPath(path);
        bean.setRealSize(0);
        bean.setFetchedSize(0);


        DownloadTask task = new DownloadTask.Builder(bean.getUrl(), new File(path).getParentFile())
                .setFilename(fileName)
                .setMinIntervalMillisCallbackProcess(500) // 下载进度回调的间隔时间（毫秒）
                .setPassIfAlreadyCompleted(false)// 任务过去已完成是否要重新下载
                .setConnectionCount(1)
                .setPriority(10)
                .build();

        DownloadListener downloadListener = new DownloadListener() {

            private long lastTime = 0;
            private long currentOffset = 0;
            private long lastOffset = 0;
            @Override
            public void taskStart(@NonNull DownloadTask task) {
                Log.i(TAG, "taskStart: ");
                bean.setStatus(CoursewareBean.STATUS_FETCHING);
                if (coursewareAdapter!=null){
                    coursewareAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void connectTrialStart(@NonNull DownloadTask task, @NonNull Map<String, List<String>> requestHeaderFields) {
                Log.i(TAG, "connectTrialStart: ");

            }

            @Override
            public void connectTrialEnd(@NonNull DownloadTask task, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
                Log.i(TAG, "connectTrialEnd: ");

            }

            @Override
            public void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause) {
                Log.i(TAG, "downloadFromBeginning: ");

            }

            @Override
            public void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info) {
                Log.i(TAG, "downloadFromBreakpoint: ");

            }

            @Override
            public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {
                Log.i(TAG, "connectStart: ");

            }

            @Override
            public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
                Log.i(TAG, "connectEnd: ");

            }

            @Override
            public void fetchStart(@NonNull DownloadTask task, int blockIndex, long contentLength) {
                Log.i(TAG, "fetchStart: contentLength="+contentLength+"");
                bean.setRealSize(bean.getRealSize()+contentLength);
                lastTime = System.currentTimeMillis();
            }


            @Override
            public void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes) {
                Log.i(TAG, "fetchProgress: blockIndex="+blockIndex+"&increaseBytes="+increaseBytes+"");

                bean.setFetchedSize(bean.getFetchedSize()+increaseBytes);
                int progress = (int) (bean.getFetchedSize()*100/bean.getRealSize());
                Log.i(TAG, "fetchProgress: "+progress);
                bean.setProgress(progress);

//                currentOffset = bean.getFetchedSize();
//                // 计算下载速度
//                long currentTime = System.currentTimeMillis();
//                long deltaTime = currentTime - lastTime;
//                long deltaOffset = currentOffset - lastOffset;
//                long speed = (long) (deltaOffset/1024 / (deltaTime/1000)*1f); // 转换为每秒字节数
//
//                // 更新上一次的时间和偏移量
//                lastTime = currentTime;
//                lastOffset = currentOffset;
                long currentTime = System.currentTimeMillis();
                long deltaTime = currentTime - lastTime;
                // 处理下载速度
//                Log.d("DownloadSpeed", "Current speed: " + speed + " bytes/second");
                double s = deltaTime*1f/1000;
                if (s>0){
                    bean.setSpeed((long) (increaseBytes/1024/s));
                }
                lastTime = currentTime;

                if (coursewareAdapter!=null){
                    coursewareAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength) {
                Log.i(TAG, "fetchEnd: contentLength="+contentLength+"");
            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) {
                Log.i(TAG, "taskEnd: ");
                bean.setStatus(CoursewareBean.STATUS_FETCHED);
                taskHashMap.remove(bean);
                if (coursewareAdapter!=null){
                    coursewareAdapter.notifyDataSetChanged();
                }

            }
        };
        taskHashMap.put(bean,task);
        task.enqueue(downloadListener);//异步执行任务
    }

    private File getDocFile(String docId){
        File file = new File(ROOT_PATH);
        if (file.exists()){
            File[] files = file.listFiles();
            for (File f:files){
                if (f.exists()&&f.isFile()&&f.getName().contains(Tools.getMD5Str(docId))){
                    return f;
                }
            }
        }
        return null;
    }




    private OnClickBottomStatusListener onClickBottomStatusListener;
    public void setListener(OnClickBottomStatusListener onClickBottomStatusListener){
        this.onClickBottomStatusListener = onClickBottomStatusListener;
    }


    public void destroy(){
        //取消所有下载，删除未下载完成的文件
    }

    public interface OnCoursewareMessageListener{
        /**
         * 课件消息状态
         * @param status 0：取消  1：新增
         */
        void onMessage(int status);
    }

    public void setOnCoursewareMessageListener(OnCoursewareMessageListener onCoursewareMessageListener) {
        this.onCoursewareMessageListener = onCoursewareMessageListener;
    }
}

