package com.tofly.ghrq_route.common.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
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.base.ui.BaseUi;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.module.message.controller.MessageCallBack;
import com.tofly.ghrq_route.module.message.controller.MessageController;
import com.tofly.ghrq_route.module.message.domain.InMessageBean;
import com.tofly.ghrq_route.module.message.domain.MessageDeatilBean;
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.util.image.ImageUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author YCHK
 * 已发消息详情
 */
public class UiMessageSDetail extends BaseUi {

    @BindView(R.id.text_user_name)
    TextView textUserName;
    @BindView(R.id.text_send_date)
    TextView textSendDate;
    @BindView(R.id.layout_addition_area)
    LinearLayout layoutAdditionArea;
    @BindView(R.id.text_addition_num)
    TextView textAdditionNum;
    @BindView(R.id.layout_message_addition)
    LinearLayout layoutMessageAddition;
    @BindView(R.id.text_message_content)
    TextView textMessageContent;
    @BindView(R.id.tv_unread)
    TextView tvUnread;
    @BindView(R.id.tv_read)
    TextView tvRead;
    @BindView(R.id.v_view)
    View Vview;

    private DBDaoHelper dbDaoHelper;
    private UserBean mUser;
    private MessageController messageController;
    private TroubleController troubleController;
    private ArrayList<String> mAdditionPhotos;
    private List<Record> mAudioRecords;
    private List<AnimationDrawable> mAnimationDrawables = new ArrayList<>();
    private List<InMessageBean.FilesBean> filesBeans = new ArrayList<>();

    private String Id;
    private String name, time, unread, read;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_message_sdetail);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        mUser = BaseApp.getInstance().getLoginUser();
        dbDaoHelper = DBDaoHelper.getInstance();
        Id = getIntent().getStringExtra("messageId");
        name = getIntent().getStringExtra("name");
        time = getIntent().getStringExtra("time");
        unread = getIntent().getStringExtra("unread");
        // read = getIntent().getStringExtra("read");
        messageController = new MessageController(this);
        messageController.getMsgDetail(Id, new MessageCallBack() {

            @Override
            public void onDetailMsg(boolean isSuccess, int errorCoed, String errMs, MessageDeatilBean data) {
                super.onDetailMsg(isSuccess, errorCoed, errMs, data);
                if (isSuccess) {
                    if (data != null) {
                        if (!TextUtils.isEmpty(unread)) {
                            tvUnread.setText(unread);
                        }
                        if (!TextUtils.isEmpty(read)) {
                            tvRead.setText(read);
                        }
                        /*发送者名称*/
                        if (!TextUtils.isEmpty(name))
                            textUserName.setText(name);
                        /*发送时间*/
                        if (!TextUtils.isEmpty(time))
                            textSendDate.setText(time);

                        if (!TextUtils.isEmpty(data.getMessage())) {
                            textMessageContent.setText(data.getMessage());
                        }
                        if (data.getPhotos() != null && data.getPhotos().size() > 0) {
                            for (String photo : data.getPhotos()) {
                                InMessageBean.FilesBean filesBean = new InMessageBean.FilesBean();
                                filesBean.setFiletype("image");
                                filesBean.setFilename(photo);
                                filesBeans.add(filesBean);
                            }
                        }
                        if (data.getAudios() != null && data.getAudios().size() > 0) {
                            for (String file : data.getAudios()) {
                                InMessageBean.FilesBean filesBean = new InMessageBean.FilesBean();
                                filesBean.setFiletype("audio");
                                filesBean.setFilename(file);
                                filesBeans.add(filesBean);
                            }

                        }
                        if (filesBeans.size() > 0) {
                            int totalNum = filesBeans.size();
                            layoutAdditionArea.setVisibility(View.VISIBLE);
                            Vview.setVisibility(View.VISIBLE);
                            for (InMessageBean.FilesBean files : filesBeans) {
                                View fileView = getViewFromFile(files, String.valueOf(data.getMessageId()));
                                layoutMessageAddition.addView(fileView);
                            }
                            textAdditionNum.setText(String.format("%d个", totalNum));
                        } else {
                            layoutAdditionArea.setVisibility(View.GONE);
                            Vview.setVisibility(View.GONE);
                        }
                    }
                } else {
                    toast(errMs);
                }
            }
        });
    }


    private View getViewFromFile(InMessageBean.FilesBean filesBean, String messageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View rootView = inflater.inflate(R.layout.item_message_addition, null);

        final ImageView imageFileIcon = (ImageView) rootView.findViewById(R.id.image_file_icon);
        final LinearLayout audioLayout = (LinearLayout) rootView.findViewById(R.id.layout_audio_signal);
        TextView textFileName = (TextView) rootView.findViewById(R.id.text_file_name);
        final ProgressBar progressBar = (ProgressBar) rootView.findViewById(R.id.progress_image);
        audioLayout.setVisibility(View.GONE);
        imageFileIcon.setVisibility(View.GONE);
        progressBar.setVisibility(View.INVISIBLE);
        String[] aar = filesBean.getFilename().split("/");
        if (aar.length > 0) {
            textFileName.setText(aar[aar.length - 1]);
        }
        String sIconUrl = filesBean.getFilename();
        InMessageBean.File_Type file_type = filesBean.getFileType();
        if (sIconUrl != null) {
            String faceurl = NetRequestURL.newApi_dyrq.getFormattedPicture(sIconUrl);
            if (file_type.isEqual(InMessageBean.File_Type.FILE_TYPE_IMAGE)) {
                if (mAdditionPhotos == null)
                    mAdditionPhotos = new ArrayList<>();
                getPhotoView(faceurl, imageFileIcon, progressBar);
            } else if (file_type.isEqual(InMessageBean.File_Type.FILE_TYPE_AUDIO)) {
                if (mAudioRecords == null)
                    mAudioRecords = new ArrayList<Record>();
                int audioLenth = 1;
                getAudioView(faceurl, audioLenth, messageId, audioLayout, progressBar);
            }
        }

        rootView.setTag(filesBean);

        return rootView;
    }

    private void getPhotoView(final String url, final ImageView imageFileIcon, final ProgressBar progressBar) {
        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);
        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(UiMessageSDetail.this, UiBigImageList.class);
            intent.putExtras(mBundle);
            startActivity(intent);
        });
    }

    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();
        }
    }

    private void getAudioView(final String url, final int audioLenth, final String messageId,
                              final LinearLayout audioLayout, final ProgressBar progressBar) {
        progressBar.setVisibility(View.VISIBLE);
        audioLayout.setVisibility(View.GONE);

        boolean bHasCache = false;
        TroubleAudioBean audioBean = dbDaoHelper.queryTroubleAudio(url);
        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();
            if (troubleController == null)
                troubleController = new TroubleController(this);
            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(audioLenth);
                        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(audioLenth);
                        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.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();
                            }
                        });
            }
        });
    }

    @Override
    protected void onDestroy() {
        BaseApp.cancelAllRequest(getClass().getName());
        //重置数据状态
        resetData();
        MediaManager.release();//重置
        super.onDestroy();
    }
}

