package com.tofly.ghrq_route.common.util.file;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.file.FileUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import com.tofly.ghrq_route.common.util.recorder.AudioRecordHelper;

import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

public class FileViewUtil {
    private AudioRecordHelper audioRecordHelper;

    private PermissionHelper permissionHelper;

    private PhotoHelper photoHelper;

    private TroubleTool troubleTool;

    private Context mContext;

    private GetViewCallback onGetViewCallback;

    public void setOnGetViewCallback(GetViewCallback onGetViewCallback) {
        this.onGetViewCallback = onGetViewCallback;
    }

    public FileViewUtil(Context context) {
        this.mContext = context;
        this.troubleTool = TroubleTool.getInstance();
    }

    public void getImageFileView(final String fileUrl, final GetViewCallback getViewCallback) {
        if (photoHelper == null) {
            permissionHelper = new PermissionHelper(mContext);
            photoHelper = new PhotoHelper(mContext, permissionHelper);
        }

        String real_url = NetRequestURL.newApi_dyrq.getFormattedPicture(fileUrl);
        View view = photoHelper.getPhotoViewFromUrl(real_url);

        boolean isSuccess = (view != null);
        if (getViewCallback != null) {
            getViewCallback.onGetView(isSuccess, view);
        }
    }

    public void getImageFileView(final String troubleId, final String fileUrl, final String fileName, final PhotoHelper.PhotoClickListener listener, final GetPhotoViewCallback getPhotoViewCallback) {
        if (photoHelper == null) {
            permissionHelper = new PermissionHelper(mContext);
            photoHelper = new PhotoHelper(mContext, permissionHelper);
        }

        View view = null;
        TroublePictureBean savedPicture = null;
        if (fileUrl != null && !fileUrl.isEmpty()) {
            savedPicture = troubleTool.getSavedTroublePictureByUrl(fileUrl);
            if (savedPicture == null) {
                TroublePictureBean pictureBean = new TroublePictureBean();
                String pictureid = UUID.randomUUID().toString();
                String filetype = MimeUtil.getMimeType(fileUrl);
                String time = DateUtils.getDate(new Date().getTime());
                pictureBean.setId(pictureid);
                pictureBean.setTroubleid(troubleId);
                pictureBean.setFileurl(fileUrl);
                pictureBean.setFile(fileName);
                pictureBean.setFiletype(filetype);
                pictureBean.setStatus(TroubleBean.SERVER_STATE);
                pictureBean.setCreateTime(time);
                troubleTool.saveTroublePicture(pictureBean);
                savedPicture = pictureBean;
            }
            String filepath = savedPicture.getFilepath();
            boolean bHasCache = filepath != null && !FileUtil.isFileExist(filepath);
            if (bHasCache) {
                view = photoHelper.getPhotoViewFromPath(savedPicture, listener);
            }else {
                view = photoHelper.getPhotoViewFromUrl(savedPicture, listener);
            }
        }
        boolean isSuccess = view != null;
        if (getPhotoViewCallback != null) {
            getPhotoViewCallback.onGetView(isSuccess, view, savedPicture);
        }
    }

    public void getAudioFileView(final String troubleId, final String fileUrl, int length, final String fileNote,
                                 final List<Record> records, final AudioRecordHelper.RecordClickListener listener, final GetViewCallback getViewCallback) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        final View rootView = inflater.inflate(R.layout.item_audio_record, null);
        final LinearLayout layoutAudio = rootView.findViewById(R.id.layout_audio_area);
        final ProgressBar progressBar = rootView.findViewById(R.id.progress_loading);
        final ImageView imageFailed = rootView.findViewById(R.id.image_failed);

        progressBar.setVisibility(View.VISIBLE);
        layoutAudio.setVisibility(View.GONE);
        imageFailed.setVisibility(View.GONE);

        troubleTool.getTroubleAudioFromServer(mContext, troubleId, fileUrl, length, fileNote, (isSuccess, record) -> {
            progressBar.setVisibility(View.GONE);
            View view = null;
            if (isSuccess) {
                if (audioRecordHelper == null) {
                    this.audioRecordHelper = new AudioRecordHelper(mContext);
                }
                view = audioRecordHelper.getRecordViewFromAudio(record, records, listener);
            }else {
                imageFailed.setVisibility(View.VISIBLE);
            }
            if (getViewCallback != null) {
                getViewCallback.onGetView(isSuccess, view);
            }
        });
    }

    public View getVideoFileView(final String troubleId, final String fileUrl, final String fileName, final String fileNote, final GetViewCallback getViewCallback){
        LayoutInflater inflater = LayoutInflater.from(mContext);
        final View rootView = inflater.inflate(R.layout.item_video_record, null);
        TextView textTime = rootView.findViewById(R.id.text_video_time);
        final ProgressBar progressBar = rootView.findViewById(R.id.progress_loading);
        ImageView thumbView = rootView.findViewById(R.id.image_video_thumb);

        progressBar.setVisibility(View.VISIBLE);

        troubleTool.getTroubleVideoFromServer(mContext, troubleId, fileUrl, fileName, fileNote, (isSuccess, videoBean) -> {
            progressBar.setVisibility(View.GONE);
            View view = rootView;
            if (isSuccess && videoBean != null) {
                rootView.setTag(videoBean);
            }else {
                //imageFailed.setVisibility(View.VISIBLE);
            }
            if (getViewCallback != null) {
                getViewCallback.onGetView(isSuccess, view);
            }
        });

/*
        String thumb_url = NetRequestURL.newApi_dyrq.getFormattedDownFile(videoBean.getThumb(), fileName);
        ImageLoader loader = ImageLoader.getInstance();
        DisplayImageOptions options = new DisplayImageOptions.Builder().
                showImageOnFail(new ColorDrawable(mContext.getResources().getColor(R.color.black))).build();
        loader.displayImage(thumb_url, thumbView, options);
*/

        //设置显示时长
/*        String strLength = String.format(Locale.CHINA, "%d:%02d", videoLength / 60, videoLength % 60);
        textTime.setText(strLength);*/
        rootView.setOnClickListener(view -> {
            TroublePictureBean pictureBean = (TroublePictureBean) view.getTag();
            if (pictureBean != null){
                previewVideo(pictureBean);
            }
        });

        return rootView;
    }

    private void previewVideo(TroublePictureBean pictureBean) {
        if (photoHelper == null)
            photoHelper = new PhotoHelper(mContext, permissionHelper);
        photoHelper.requestPreviewVideo(null, pictureBean.getFilepath(), (int) pictureBean.getSecond());
    }

    public void getFileView(final String troubleId, final String fileUrl, String fileName, final String fileNote, final GetViewCallback getViewCallback) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        final View rootView = inflater.inflate(R.layout.item_trouble_file, null);
        final FrameLayout layoutFile = rootView.findViewById(R.id.layout_file_area);
        final ProgressBar progressBar = rootView.findViewById(R.id.progress_loading);
        final TextView textFileName = rootView.findViewById(R.id.text_file_name);
        final ImageView imageFailed = rootView.findViewById(R.id.image_failed);
        final TextView textFileSize = rootView.findViewById(R.id.text_file_size);

        textFileName.setText(fileName);
        progressBar.setVisibility(View.VISIBLE);
        imageFailed.setVisibility(View.GONE);

        troubleTool.getTroubleFileFromServer(mContext, troubleId, fileUrl, fileName, fileNote, (isSuccess, audioBean) -> {
            progressBar.setVisibility(View.GONE);
            View view = rootView;
            if (isSuccess && audioBean != null) {
                rootView.setTag(audioBean);
                String fileSize =  FileSizeUtil.getAutoFileOrFilesSize(audioBean.getPath());
                textFileSize.setText(fileSize);
            }else {
                imageFailed.setVisibility(View.VISIBLE);
            }
            if (getViewCallback != null) {
                getViewCallback.onGetView(isSuccess, view);
            }
        });

        rootView.setOnClickListener(view -> {
            TroubleAudioBean audioBean = (TroubleAudioBean) view.getTag();
            if (audioBean != null && audioBean.getPath() != null) {
                IntentBuilder.viewFile(mContext, audioBean.getPath());
            }
        });
    }

    public View getDocumentView(TroubleAudioBean audioBean, DocLongClickListener listener) {
        if (audioBean == null)
            return null;

        LayoutInflater inflater = LayoutInflater.from(mContext);
        final View rootView = inflater.inflate(R.layout.item_trouble_file, null);
        final ProgressBar progressBar = rootView.findViewById(R.id.progress_loading);
        final TextView textFileName = rootView.findViewById(R.id.text_file_name);
        final ImageView imageFailed = rootView.findViewById(R.id.image_failed);
        final TextView textFileSize = rootView.findViewById(R.id.text_file_size);

        progressBar.setVisibility(View.GONE);
        imageFailed.setVisibility(View.GONE);

        String filePath = audioBean.getPath();
        if (FileUtil.isFileExist(filePath)) {
            String fileName = FileUtil.getFileName(filePath);
            textFileName.setText(fileName);
            rootView.setTag(audioBean);
            String fileSize =  FileSizeUtil.getAutoFileOrFilesSize(audioBean.getPath());
            textFileSize.setText(fileSize);
        }else {
            imageFailed.setVisibility(View.VISIBLE);
        }

        rootView.setOnClickListener(view -> {
            TroubleAudioBean audioBean1 = (TroubleAudioBean) view.getTag();
            if (audioBean1 != null && audioBean1.getPath() != null) {
                IntentBuilder.viewFile(mContext, audioBean1.getPath());
            }
        });

        rootView.setOnLongClickListener(view -> {
            String title = "删除文件";
            String content = "是否删除文件?";
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(title);
            builder.setMessage(content);
            builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                TroubleAudioBean audioBean1 = (TroubleAudioBean) view.getTag();
                if (audioBean1 != null)
                    audioBean1.setStatus(TroublePictureBean.PHOTO_DELETED_STATE);

                if (listener != null)
                    listener.onRemoveDoc(view, audioBean1);
            });
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
            return true;
        });

        return rootView;
    }

    public void clearAllImages() {
        if (photoHelper != null) {
            photoHelper.clearAllImages();
        }
    }

    public interface DocLongClickListener{
        void onRemoveDoc(View view, TroubleAudioBean document);
    }

    public interface GetViewCallback{
        void onGetView(boolean isSuccess, View view);
    }

    public interface GetPhotoViewCallback{
        void onGetView(boolean isSuccess, View view, TroublePictureBean pictureBean);
    }
}
