package com.tofly.ghrq_route.base.ui;

import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.AudioRecordButton;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.Location.LocationUtil;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.file.FileViewUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import com.tofly.ghrq_route.common.util.recorder.AudioRecordHelper;
import com.tofly.ghrq_route.module.trouble.domain.AuditFileBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.latte_core.base.IPresenter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hzw.graffiti.WaterMarkParams;

public abstract class BaseMapFileActivity<P extends IPresenter> extends BaseMapActivity<P> {

    protected PhotoHelper photoHelper;

    protected PermissionHelper permissionHelper;

    protected FileViewUtil fileViewUtil;

    protected List<TroublePictureBean> mPicturesUpload = new ArrayList<>();

    protected final List<Record> mAudiosRecords = new ArrayList<>();

    protected final List<TroubleAudioBean> mDocumentsUpload = new ArrayList<>();

    private AudioRecordHelper audioRecordHelper;

    private boolean isVideoEnable = true;

    private boolean isAudioEnable = false;

    private boolean isDocEnable = false;

    @Override @CallSuper
    public void initView() {
        super.initView();
    }

    @CallSuper
    public void initNet() {
        super.initNet();

        permissionHelper = new PermissionHelper(this);
        photoHelper = new PhotoHelper(this, permissionHelper);
        fileViewUtil = new FileViewUtil(this);
        audioRecordHelper = new AudioRecordHelper(this, permissionHelper, getAudioRecordBtn());

        initListener();
    }

    private void initListener() {
        MyAudioRecordButton recordBtn = getAudioRecordBtn();
        if (recordBtn != null) {
            AudioRecordButton.AudioFinishRecorderListener mRecorderListener = (seconds, filePath) -> {
                String time = DateUtils.getDate(new Date().getTime());
                int audioLength = (int) seconds <= 0 ? 1 : (int) seconds;

                final Record recordModel = new Record();
                recordModel.setSecond(audioLength);
                recordModel.setPath(filePath);
                recordModel.setPlayed(false);
                recordModel.setCreateTime(time);
                mAudiosRecords.add(recordModel);

                View view = getRecordViewFromAudio(recordModel);
                LinearLayout gallery = getPhotoGallery();
                if (gallery != null)
                    gallery.addView(view);
            };
            recordBtn.setAudioFinishRecorderListener(mRecorderListener);
        }

        Button btnAddPhoto = getAddPhotoBtn();
        if (btnAddPhoto != null) {
            btnAddPhoto.setOnClickListener(view -> showAddFileDialog());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (photoHelper != null) {
            photoHelper.handleActivityResult(requestCode, resultCode, data);
        }
    }

    protected void showAddFileDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        String[] modes = new String[]{"拍照", "照片", "短视频", "录音", "附件"};
        List<String> modeList = new ArrayList<>(Arrays.asList(modes));
        if (!isVideoEnable) {
            modeList.remove("短视频");
        }
        if (!isAudioEnable) {
            modeList.remove("录音");
        }
        if (!isDocEnable) {
            modeList.remove("附件");
        }
        String[] newModes = modeList.toArray(new String[modeList.size()]);
        dialog.setItems(newModes,
                (arg0, i) -> {
                    String mode = newModes[i];
                    if (mode.equals("拍照")) {
                        getPicFromSysCamera();
                    } else if (mode.equals("照片")) {
                        getPicFromSysAlbums();
                    }else if (mode.equals("短视频")) {
                        requestVideoView();
                    } else if (mode.equals("录音")) {
                        startAudioRecord();
                    } else if (mode.equals("附件")) {
                        requestFileView();
                    }
                });
        dialog.setCancelable(true);
        dialog.show();
    }

    protected WaterMarkParams getWaterMarkParams() {
        WaterMarkParams params = null;
        LocationUtil_xu.CoordinateClass location = getLocation();
        if (location != null) {
            params = new WaterMarkParams();
            params.mbNeedGps = 1;
            String strLng = LocationUtil.formatLocation(location.Longtitude);
            String strLat = LocationUtil.formatLocation(location.Latitude);
            if (!strLng.isEmpty() && !strLat.isEmpty()) {
                double lng = Double.parseDouble(strLng);
                double lat = Double.parseDouble(strLat);
                strLng = LocationUtil.formatLocation(lng);
                strLat = LocationUtil.formatLocation(lat);
                params.mLongitude = strLng;
                params.mLatitude = strLat;
            }
            params.mAddress = location.addr;
            UserBean userBean = new UserBean();
            if (userBean != null) {
                params.mUser = userBean.getUsername();
                params.mCompany = userBean.getCompany_name();
            }
            params.mReportTime = DateUtils.getDate();
        }
        return params;
    }

    /**
     * 调用系统相机拍照.
     * isNeedWatermark 是否需要水印需要获取系统配置参数
     */
    private void getPicFromSysCamera() {
        boolean isPhotoWaterMark = BaseApp.getInstance().getIsPhotoWatermark() == 1;

        photoHelper.requestCameraPhoto(isPhotoWaterMark, this::getWaterMarkParams, (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getPhotoViewFromPath(pictureBean);
                    LinearLayout gallery = getPhotoGallery();
                    if (gallery != null)
                        gallery.addView(view);

                    if (photoViewListener != null) {
                        photoViewListener.getPhotoView(pictureBean, view);
                    }
                }
            } else {
                ToastUtil.showToast(this, errStr);
            }
        });
    }

    /**
     * 获取系统相册照片
     * 需要根据配置 判断是否需要添加水印
     */
    private void getPicFromSysAlbums() {
        boolean isPhotoWaterMark = BaseApp.getInstance().getIsPhotoWatermark() == 1;

        photoHelper.requestImagePhoto(isPhotoWaterMark, this::getWaterMarkParams, (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getPhotoViewFromPath(pictureBean);
                    LinearLayout gallery = getPhotoGallery();
                    if (gallery != null)
                        gallery.addView(view);

                    if (photoViewListener != null) {
                        photoViewListener.getPhotoView(pictureBean, view);
                    }
                }
            } else {
                ToastUtil.showToast(this, errStr);
            }
        });
    }

    protected View getPhotoViewFromPath(TroublePictureBean pictureBean) {
        return photoHelper.getPhotoViewFromPath(pictureBean, (view, picture) -> {
                    LinearLayout gallery = getPhotoGallery();
                    if (gallery != null)
                        gallery.removeView(view);
                    mPicturesUpload.remove(picture);

                    if (photoViewListener != null) {
                        photoViewListener.getPhotoView(picture, view);
                    }
                });
    }

    protected void requestVideoView() {
        photoHelper.requestRecordSmallVideo((success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getVideoViewFromPath(pictureBean);
                    LinearLayout gallery = getPhotoGallery();
                    gallery.addView(view);

                    if (photoViewListener != null) {
                        photoViewListener.getPhotoView(pictureBean, view);
                    }
                }
            }else {
                ToastUtil.showToast(this, errStr);
            }
        });
    }

    public View getVideoViewFromPath(TroublePictureBean pictureBean) {
        return photoHelper.getVideoViewFromPath(pictureBean,
                (view, picture) -> {
                    LinearLayout gallery = getPhotoGallery();
                    if (gallery != null)
                        gallery.removeView(view);
                    mPicturesUpload.remove(picture);

                    if (photoViewListener != null) {
                        photoViewListener.getPhotoView(picture, view);
                    }
                 });
    }

    public void getVideoViewFromUrl(TroublePictureBean pictureBean) {
        LinearLayout gallery = getPhotoGallery();
        if (gallery != null) {
            getSchemeFiles(pictureBean, gallery);
        }
    }

    private void startAudioRecord() {
        MyAudioRecordButton recordBtn = getAudioRecordBtn();
        if (recordBtn != null) {
            if (audioRecordHelper != null) {
                boolean hasPermission = audioRecordHelper.checkRecordPermission();
                if (!hasPermission) {
                    audioRecordHelper.requestRecordPermission();
                } else {
                    recordBtn.setCanRecord(true);
                    recordBtn.setRecordMode();
                }
            }
            recordBtn.performClick();
        }
    }

    protected View getRecordViewFromAudio(Record record) {
        return audioRecordHelper.getRecordViewFromAudio(record,
                mAudiosRecords, (view, record1) -> {
                    mAudiosRecords.remove(record1);
                    LinearLayout gallery = getPhotoGallery();
                    if (gallery != null)
                        gallery.removeView(view);
                });
    }

    protected void requestFileView() {
        photoHelper.requestDocumentFile((success, errStr, document) -> {
            if (success && document != null) {
                View rootView = fileViewUtil.getDocumentView(document, (view1, document1) -> {
                    LinearLayout gallery = getPhotoGallery();
                    if (gallery != null)
                        gallery.removeView(view1);
                    mDocumentsUpload.remove(document1);
                });
                if (rootView != null) {
                    mDocumentsUpload.add(document);
                    LinearLayout gallery = getPhotoGallery();
                    if (gallery != null)
                        gallery.addView(rootView);
                }
            }
        });
    }

    protected void getSchemeFiles(TroublePictureBean pictureBean, final ViewGroup rootView) {
        if (pictureBean != null) {
            FileViewUtil.GetViewCallback getViewCallback = (isSuccess, view) -> {
                if (isSuccess && view != null) {
                    rootView.addView(view);

                    view.setOnLongClickListener(view1 -> {
                        photoHelper.showDeleteFileDialog((dialog, which) -> {
                            TroublePictureBean picture = (TroublePictureBean) view1.getTag();
                            if (picture != null) {
                                String picPath = picture.getFilepath();
                                String thumbPath = picture.getFilethumb();
                                FileUtil.deleteFile(picPath);
                                FileUtil.deleteFile(thumbPath);
                            }

                            LinearLayout gallery = getPhotoGallery();
                            if (gallery != null)
                                gallery.removeView(view);

                            if (photoViewListener != null) {
                                photoViewListener.getPhotoView(picture, view1);
                            }
                        });
                        return true;
                    });
                }
            };

            String fileName = pictureBean.getFile();
            String fileurl = pictureBean.getFileurl();
            String fileNote = pictureBean.getFilenote();
            String schemeId = pictureBean.getTroubleid();
            if (FileUtil.isFileTypeImage(fileName)) {
                fileViewUtil.getImageFileView(fileurl, getViewCallback);
            }  else if (FileUtil.isFileTypeVideo(fileName)) {
                fileViewUtil.getVideoFileView(schemeId, fileurl, fileName, fileNote, getViewCallback);
            } else if (FileUtil.isFileTypeAudio(fileName)) {
                fileViewUtil.getAudioFileView(schemeId, fileurl, 1, fileNote, mAudiosRecords, null, getViewCallback);
            } else {
                fileViewUtil.getFileView(schemeId, fileurl, fileName, fileNote, getViewCallback);
            }
        }
    }

    protected void getSchemeFiles(String schemeId, AuditFileBean fileBean, String fileNote, final ViewGroup rootView) {
        if (fileBean != null) {
            FileViewUtil.GetViewCallback getViewCallback = (isSuccess, view) -> {
                if (isSuccess && view != null) {
                    rootView.addView(view);
                }
            };

            String fileName = fileBean.getFileName();
            String filePath = fileBean.getPath();
            if (FileUtil.isFileTypeImage(fileName)) {
                fileViewUtil.getImageFileView(filePath, getViewCallback);
            } else if (FileUtil.isFileTypeVideo(fileName)) {
                fileViewUtil.getVideoFileView(schemeId, filePath, fileName, fileNote, getViewCallback);
            } else if (FileUtil.isFileTypeAudio(fileName)) {
                fileViewUtil.getAudioFileView(schemeId, filePath, 1, fileNote, mAudiosRecords, null, getViewCallback);
            } else {
                fileViewUtil.getFileView(schemeId, filePath, fileName, fileNote, getViewCallback);
            }
        }
    }

    protected boolean checkHasData() {
        if (mPicturesUpload != null && mPicturesUpload.size() > 0) {
            return true;
        }

        return (mAudiosRecords != null && mAudiosRecords.size() > 0);
    }

    protected boolean bRemoveCacheFile = true;
    protected void removeCacheFile() {
        if (!bRemoveCacheFile)
            return;

        //删除临时文件
        if (mPicturesUpload != null && mPicturesUpload.size() > 0) {
            for (TroublePictureBean pictureBean : mPicturesUpload) {
                String file = pictureBean.getFilepath();
                FileUtil.deleteFile(file);
            }
        }

        if (mAudiosRecords != null && mAudiosRecords.size() > 0) {
            for (Record record : mAudiosRecords) {
                String file = record.getPath();
                FileUtil.deleteFile(file);
            }
        }
    }

    public abstract Button getAddPhotoBtn();

    public abstract LinearLayout getPhotoGallery();

    public abstract MyAudioRecordButton getAudioRecordBtn();

    public void setVideoEnable(boolean videoEnable) {
        isVideoEnable = videoEnable;
    }

    public void setAudioEnable() {
        isAudioEnable = true;
    }

    protected void setDocEnable() {
        isDocEnable = true;
    }

    public void setPhotoListener(PhotoHelper.PhotoViewListener photoListener) {
        this.photoViewListener = photoListener;
    }
    public PhotoHelper.PhotoViewListener photoViewListener;

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //重置数据状态
        if (mAudiosRecords != null) {
            for (Record record : mAudiosRecords) {
                record.setPlaying(false);
            }
        }
        MediaManager.release();//重置
    }
}
