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

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.widget.NestedScrollView;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.AudioRecordButton;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.google.android.material.snackbar.Snackbar;
import com.mgq.base.utils.file.FileUtil;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.string.StringUtil;
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.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.ui.view.UserListView;
import com.tofly.ghrq_route.module.message.controller.MessageCallBack;
import com.tofly.ghrq_route.module.message.controller.MessageController;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.user.domain.MessageUserBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import com.tofly.ghrq_route.common.util.recorder.AudioRecordHelper;

import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.hzw.graffiti.WaterMarkParams;

/**
 * Created by Amu on 2017/5/10.
 * 回复消息
 */

public class UiMessageReply extends BaseUi {
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.layout_main_root)
    NestedScrollView layoutMainRoot;
    @BindView(R.id.text_reply_name)
    TextView textReplyName;
    @BindView(R.id.layout_recver_area)
    LinearLayout layoutRecverArea;
    @BindView(R.id.image_add_recver)
    ImageView imageAddRecver;
    @BindView(R.id.dangerreport_et)
    EditText dangerreportEt;
    @BindView(R.id.layout_addition_area)
    LinearLayout layoutAddtionArea;
    @BindView(R.id.text_add_photo)
    TextView textAddPhoto;
    @BindView(R.id.dangerreport1_gallery)
    LinearLayout pictureGallery;
    @BindView(R.id.layout_addpic_area)
    LinearLayout layoutAddpicArea;
    @BindView(R.id.text_add_audio)
    TextView textAddAudio;
    @BindView(R.id.dangerreport1_addaudio)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.audio_record_gallery)
    LinearLayout audioRecordGallery;
    @BindView(R.id.layout_addaudio_area)
    LinearLayout layoutAddaudioArea;
    @BindView(R.id.num_size)
    TextView numSize;

    private UserBean mUser;

    private List<MessageUserBean> mRecverList = null;

    private MessageController messageController;

    private List<TroublePictureBean> mPicturesUpload = new ArrayList<TroublePictureBean>();
    private PhotoHelper photoHelper;
    private PermissionHelper permissionHelper;

    private List<Record> mAudiosUpload = new ArrayList<>();
    private AudioRecordHelper audioRecordHelper;
    private AudioRecordButton.AudioFinishRecorderListener mRecorderListener;
    private int Id, createUserId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_message_reply);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

        EventBusUtil.register(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_message_reply_send, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_send: {
                hideSoftKeyboard();
                sendMessage();
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {

    }

    private void initData() {
        Id = getIntent().getIntExtra("id", -1);
        mUser = BaseApp.getInstance().getLoginUser();
        permissionHelper = new PermissionHelper(this);
        textReplyName.setText(mUser.getRealName());
        createUserId = getIntent().getIntExtra("createUserId", -1);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        audioRecordHelper = new AudioRecordHelper(this, permissionHelper, btnAddAudio);
        audioRecordHelper.initRecordButton();
        mRecorderListener = (seconds, filePath) -> {
            final Record recordModel = new Record();
            String time = DateUtils.getDate(new Date().getTime());
            recordModel.setSecond((int) seconds <= 0 ? 1 : (int) seconds);
            recordModel.setPath(filePath);
            recordModel.setPlayed(false);
            recordModel.setCreateTime(time);
            mAudiosUpload.add(recordModel);
            View view = getRecordViewFromAudio(recordModel);
            audioRecordGallery.addView(view);
        };
        btnAddAudio.setAudioFinishRecorderListener(mRecorderListener);

        setOnNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmCancelEdit();
            }
        });

        dangerreportEt.addTextChangedListener(new TextWatcher() {
            private CharSequence enterWords;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                enterWords = s;
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                numSize.setText("还可以输入" + (100 - s.length()) + "字");
                selectionStart = dangerreportEt.getSelectionStart();
                selectionEnd = dangerreportEt.getSelectionEnd();
                if (enterWords.length() > 100) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    dangerreportEt.setText(s);
                    dangerreportEt.setSelection(tempSelection);
                }
            }
        });
    }

    @Subscribe
    public void onMessageEvent(UiMessageUserSelect.MessageUserSelectEvent event) {
        if (event.message.equals(UiMessageUserSelect.MESSAGE_USER_SELECTED)) {
            List<MessageUserBean> userBeanList = event.userList;
            if (userBeanList != null) {
                mRecverList = userBeanList;
                UserListView userListView = new UserListView(this, mRecverList);
                View rootView = userListView.getViewWithNoTitle();
                if (rootView != null) {
                    layoutRecverArea.removeAllViews();
                    layoutRecverArea.addView(rootView);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        confirmCancelEdit();
    }

    private boolean checkHasInput() {
        boolean hasText = false;
        boolean hasPicture = false;
        boolean hasAudio = false;

        String textInput = dangerreportEt.getText().toString();
        if (textInput != null && !textInput.isEmpty()) {
            hasText = true;
        }

        if (mPicturesUpload != null && mPicturesUpload.size() > 0) {
            hasPicture = true;
        }

        if (mAudiosUpload != null && mAudiosUpload.size() > 0) {
            hasAudio = true;
        }

        if (hasAudio || hasPicture || hasText) {
            return true;
        } else
            return false;
    }

    private void confirmCancelEdit() {
        boolean hasInput = checkHasInput();
        if (hasInput) {
            String title = "退出编辑";
            String content = "退出编辑，当前输入将会丢失。是否继续?";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(title);
            builder.setMessage(content);
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    removeCacheFile();
                    finish();
                }
            });
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
        } else {
            finish();
        }
    }

    private void sendMessage() {
        boolean hasText = false;
        String textInput = dangerreportEt.getText().toString();
        if (textInput != null && !textInput.isEmpty()) {
            hasText = true;
        }
        if (hasText) {
            String title = "发送消息";
            String content = "是否发送消息?";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(title);
            builder.setMessage(content);
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    uploadMessageInfo();
                }
            });
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
        } else {
            showSnackbar("请输入消息的内容");
        }
    }

    private void uploadMessageInfo() {
        String strUploading = getString(R.string.reply_sending_info);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        String textInput = dangerreportEt.getText().toString();
        if (messageController == null)
            messageController = new MessageController(this);
        String userIds = getSendUsers();
        messageController.sendMsg(Id, textInput, userIds, mPicturesUpload, mAudiosUpload, new MessageCallBack() {
            @Override
            public void onSendMsg(boolean isSuccess, int errorCode, String errMsg) {
                super.onSendMsg(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    showUploadFinishedDialog();

                } else {
                    String strWarn = getString(R.string.message_send_info_err) + errMsg;
                    showSnackbar(strWarn);
                }
            }
        });
    }

    private String getSendUsers() {
        String userIds = "";
        List<String> users = new ArrayList<>();
        String userid = String.valueOf(createUserId);
        users.add(userid);
        if (mRecverList != null) {
            for (MessageUserBean userBean : mRecverList) {
                if (userBean != null && userBean.getId() != 0) {
                    users.add(String.valueOf(userBean.getId()));
                }
            }
        }
        if (users != null && users.size() > 0) {
            userIds = StringUtil.listToString(users, ',');
        }
        return userIds;
    }

    private List<String> getUploadFiles() {
        List<String> files = new ArrayList<>();
        for (TroublePictureBean pictureBean : mPicturesUpload) {
            files.add(pictureBean.getFilepath());
        }
        for (Record record : mAudiosUpload) {
            files.add(record.getPath());
        }
        return files;
    }

    private void showSnackbar(String msg) {
        Snackbar.make(layoutMainRoot, msg, Snackbar.LENGTH_SHORT).show();
    }

    @OnClick({R.id.image_add_recver, R.id.dangerreport1_addpic})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_add_recver: {
                hideSoftKeyboard();
                Intent intent=new Intent(this,UiMessageUserSelect.class);
                startActivity(intent);
            }
            break;
            case R.id.dangerreport1_addpic:
                hideSoftKeyboard();
                showAddPictureDialog();
                break;
        }
    }

    private void showAddPictureDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(UiMessageReply.this).
                setItems(new String[]{"从手机相册选择", "拍照"},
                        (arg0, i) -> {
                            if (i == 0) {
                                getPicFromSysAlbums();
                            }
                            if (i == 1) {
                                getPicFromSysCamera();
                            }
                        });
        dialog.setCancelable(true);
        dialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, 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);
        }
    }

    private WaterMarkParams getWaterMarkParams() {
        WaterMarkParams params = null;
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null) {
            params = new WaterMarkParams();
            params.mbNeedGps = 0;
            params.mUser = userBean.getRealName();
            params.mCompany = userBean.getCompany_name();
            String time = DateUtils.getDate(new Date().getTime());
            params.mReportTime = time;
        }
        return params;
    }

    private void getPicFromSysAlbums() {
        if (photoHelper == null)
            photoHelper = new PhotoHelper(this, permissionHelper);
        photoHelper.requestImagePhoto(true, new PhotoHelper.GetWatermarkParams() {
            @Override
            public WaterMarkParams onGetWatermarkParams() {
                return getWaterMarkParams();
            }
        }, new PhotoHelper.PhotoListener() {
            @Override
            public void getPhoto(boolean success, String errStr, TroublePictureBean pictureBean) {
                if (success) {
                    if (pictureBean != null) {
                        mPicturesUpload.add(pictureBean);//本地缓存
                        layoutAddpicArea.setVisibility(View.VISIBLE);
                        View view = getPhotoViewFromPath(pictureBean);
                        pictureGallery.addView(view);
                    }
                } else {
                    toast(errStr);
                }
            }
        });
    }

    private void getPicFromSysCamera() {
        if (photoHelper == null)
            photoHelper = new PhotoHelper(this, permissionHelper);
        photoHelper.requestCameraPhoto(true, new PhotoHelper.GetWatermarkParams() {
            @Override
            public WaterMarkParams onGetWatermarkParams() {
                return getWaterMarkParams();
            }
        }, new PhotoHelper.PhotoListener() {
            @Override
            public void getPhoto(boolean success, String errStr, TroublePictureBean pictureBean) {
                if (success) {
                    if (pictureBean != null) {
                        mPicturesUpload.add(pictureBean);//本地缓存
                        layoutAddpicArea.setVisibility(View.VISIBLE);
                        View view = getPhotoViewFromPath(pictureBean);
                        pictureGallery.addView(view);
                    }
                } else {
                    toast(errStr);
                }
            }
        });
    }

    private View getPhotoViewFromPath(TroublePictureBean pictureBean) {
        View rootView = photoHelper.getPhotoViewFromPath(pictureBean,
                (view, picture) -> {
                    pictureGallery.removeView(view);
                    mPicturesUpload.remove(picture);
                });
        return rootView;
    }

    private View getRecordViewFromAudio(Record record) {
        View rootView = audioRecordHelper.getRecordViewFromAudio(record,
                mAudiosUpload, (view, record1) -> {
                    mAudiosUpload.remove(record1);
                    audioRecordGallery.removeView(view);
                });

        return rootView;
    }

    private void showUploadFinishedDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.message_send_ok);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                removeCacheFile();
                finish();
            }
        });
        builder.show();
    }

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

    @Override
    protected void onDestroy() {
        BaseApp.cancelAllRequest(getClass().getName());
        EventBusUtil.unregister(this);
        super.onDestroy();
    }
}
