package com.tofly.ghrq_route.common.util;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.controller.TroubleController;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.ui.activity.UiBigImageList;
import com.tofly.ghrq_route.common.util.image.ImageUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author YCHK
 * 下载文档
 */
public class DownLoadUtil {
    private Context context;
    private DBDaoHelper dbDaoHelper;
    private String sdcard;
    private List<AnimationDrawable> mAnimationDrawables;
    private List<Record> mAudioRecords;
    private TroubleController troubleController;

    public DownLoadUtil(Context context) {
        this.context = context;
        dbDaoHelper = DBDaoHelper.getInstance();
        mAnimationDrawables = new ArrayList<>();
        mAudioRecords = new ArrayList<>();
        troubleController = new TroubleController(context);
    }

    /**
     * 加载图片
     */
    public void getPhotoView(final String url, final String path, final ImageView imageFileIcon, final ProgressBar progressBar) {
        ArrayList<String> mAdditionPhotos = new ArrayList<>();
        if (url != null) {
            ImageLoader loader = ImageLoader.getInstance();
            DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
                    .showImageOnFail(R.mipmap.ico_user_name)
                    .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                    .cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
                    .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                    .imageScaleType(ImageScaleType.NONE)// 设置图片以如何的编码方式显示
                    .bitmapConfig(Bitmap.Config.ARGB_8888)// 设置图片的解码类型//
                    .build();
            loader.displayImage(url, imageFileIcon, imageOptions, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    progressBar.setVisibility(View.VISIBLE);
                    imageFileIcon.setVisibility(View.GONE);
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    progressBar.setVisibility(View.GONE);
                    imageFileIcon.setVisibility(View.VISIBLE);
                    imageFileIcon.setImageResource(R.mipmap.ic_close_grey_400_24dp);
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    progressBar.setVisibility(View.GONE);
                    imageFileIcon.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
            mAdditionPhotos.add(url);
            imageFileIcon.setTag(url);
        } else {
            progressBar.setVisibility(View.GONE);
            Bitmap bitmap = ImageUtil.getimage(path, 100, 100);
            imageFileIcon.setImageBitmap(bitmap);
            mAdditionPhotos.add(path);
            imageFileIcon.setTag(path);
        }
        imageFileIcon.setOnClickListener(v -> {
            // 点击图片查看大图
            ImageView imageV = (ImageView) v;
            String PicAbsolutePath = imageV.getTag().toString();
            System.out.println(PicAbsolutePath);
            Bundle mBundle = new Bundle();
            mBundle.putString(ImageUtil.CURRENT_PATH_KEY, PicAbsolutePath);
            mBundle.putStringArrayList(ImageUtil.PICS_PATH_KEY, mAdditionPhotos);
            Intent intent = new Intent(context, UiBigImageList.class);
            intent.putExtras(mBundle);
            context.startActivity(intent);
        });
    }

    /**
     * 加载语音
     */
    public void getAudioView(final String url, final String path, final String messageId, final LinearLayout audioLayout, final ProgressBar progressBar) {
        progressBar.setVisibility(View.VISIBLE);
        boolean bHasCache = false;
        TroubleAudioBean audioBean;
        if (!TextUtils.isEmpty(url)) {
            audioBean = dbDaoHelper.queryTroubleAudio(url);
        } else {
            audioBean = dbDaoHelper.queryTroubleAudio1(path);
        }
        String filePath = null;
        if (audioBean != null) {
            filePath = audioBean.getPath();
            if (filePath != null && new File(filePath).exists()) {
                bHasCache = true;
            }
        }
        if (bHasCache) {
            Record record = new Record();
            record.setPath(filePath);
            record.setSecond(audioBean.getSecond());
            record.setPlayed(false);
            mAudioRecords.add(record);
            audioLayout.setTag(record);
            progressBar.setVisibility(View.GONE);
            audioLayout.setVisibility(View.VISIBLE);
        } else {
            UserBean user = BaseApp.getInstance().getLoginUser();
            troubleController.getTroubleAudio(user.getToken(), url, new TroubleCallBack() {
                @Override
                public void onGetTroubleAudio(boolean isSuccess, int errorCode, String errMsg, String path) {
                    super.onGetTroubleAudio(isSuccess, errorCode, errMsg, path);
                    if (isSuccess) {
                        progressBar.setVisibility(View.GONE);
                        audioLayout.setVisibility(View.VISIBLE);

                        Record record = new Record();
                        record.setPath(path);
                        record.setSecond(1);
                        record.setPlayed(false);
                        mAudioRecords.add(record);
                        audioLayout.setTag(record);

                        TroubleAudioBean audioBean = new TroubleAudioBean();
                        String audioId = UUID.randomUUID().toString();
                        audioBean.setId(audioId);
                        audioBean.setTroubleid(messageId);
                        audioBean.setPath(path);
                        audioBean.setSecond(1);
                        audioBean.setUrl(url);
                        audioBean.setStatus(TroubleBean.TROUBLE_STATE);
                        dbDaoHelper.insertOrUpdateTroubleAudio(audioBean);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        audioLayout.setVisibility(View.VISIBLE);
                        audioLayout.setBackgroundResource(R.mipmap.ic_close_grey_400_24dp);
                    }
                }
            });
        }
        audioLayout.setVisibility(View.VISIBLE);
        audioLayout.setOnClickListener(view -> {
            Record record1 = (Record) view.getTag();
            if (record1 == null)
                return;
            record1.setPlayed(true);
            final AnimationDrawable animationDrawable = (AnimationDrawable) audioLayout.getBackground();
            //重置动画
            resetAnim(animationDrawable);
            //重置数据状态
            resetData();

            //处理点击正在播放的语音时，可以停止；再次点击时重新播放。
            if (record1.isPlaying()) {
                record1.setPlaying(false);
                MediaManager.release();//重置
            } else {
                record1.setPlaying(true);
                //获取语音信号栏，开始播放动画
                animationDrawable.start();
                //播放前重置。
                MediaManager.release();
                //开始实质播放
                MediaManager.playSound(record1.getPath(),
                        new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                animationDrawable.selectDrawable(0);//显示动画第一帧
                                animationDrawable.stop();
                            }
                        });
            }
        });
    }

    private void resetData() {
        if (mAudioRecords != null) {
            for (Record record : mAudioRecords) {
                record.setPlaying(false);//保证在第二次点击该语音栏时当作没有“不是在播放状态”。
            }
        }
    }

    private void resetAnim(AnimationDrawable animationDrawable) {
        if (!mAnimationDrawables.contains(animationDrawable)) {
            mAnimationDrawables.add(animationDrawable);
        }
        for (AnimationDrawable ad : mAnimationDrawables) {
            ad.selectDrawable(0);
            ad.stop();
        }
    }

    /**
     * 加载文档
     */

    public void getFile(TextView textView, String filename, String url,String path, ProgressBar progressBar) {
        textView.setOnClickListener(v -> {
            //检测是否安装了wps软件，没有安装则去下载
            if (isAvilible(context, "cn.wps.moffice_eng")) {
               if (!TextUtils.isEmpty(url)){
                   String sdpath = Environment.getExternalStorageDirectory() + "/dyrq_route/build_manage/" + filename;
                   File file = new File(sdpath);
                   if (file.exists()) {
                       aTob(file);
                   } else {
                       downloadFile(filename, url, progressBar);
                   }
               }else {
                   File file = new File(path);
                   aTob(file);
               }
            } else {
                // 从市场上下载
                Uri uri = Uri.parse("market://details?id=cn.wps.moffice_eng");
                // 直接从指定网址下载
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(it);
            }
        });
    }

    private void aTob(File file) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("OpenMode", "ReadOnly");// 只读模式
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setClassName("cn.wps.moffice_eng", "cn.wps.moffice.documentmanager.PreStartActivity2");
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        intent.putExtras(bundle);
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文档
     */
    private void downloadFile(String filename, String urls, ProgressBar progressBar) {
        progressBar.setVisibility(View.VISIBLE);
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String sdpath = Environment.getExternalStorageDirectory() + "/";
                sdcard = sdpath + "dyrq_route/build_manage/";
                File file = new File(sdcard);
                if (!file.exists()) {
                    file.mkdirs();
                }
                URL url = new URL(urls);
                URLConnection rulConnection = url.openConnection();
                HttpURLConnection conn = (HttpURLConnection) rulConnection;
                conn.setRequestMethod("GET");
                conn.connect();
                InputStream is = conn.getInputStream();
                File apkFile = new File(sdcard, urldecodeUTF8(filename));
                FileOutputStream fos = new FileOutputStream(apkFile);
                int len = 2048;
                byte buf[] = new byte[len];
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.close();
                is.close();
                progressBar.setVisibility(View.GONE);
                if (apkFile.exists()) {
                    aTob(apkFile);
                }
            }
        } catch (IOException e) {
            progressBar.setVisibility(View.GONE);
            e.printStackTrace();
        }

    }

    /**
     * 验证手机是否安装了wps
     */
    private boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    public static String urldecodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLDecoder.decode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

}
