package com.bc_chat.circle.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.arch.lifecycle.Transformations.map
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.widget.EditText
import com.amap.api.mapcore.util.it
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.circle.adapetr.PhotoAdapter
import com.bc_chat.circle.contract.ReleaseTopicContract
import com.bc_chat.circle.entity.Emoji
import com.bc_chat.circle.presenter.ReleaseTopicPresenter
import com.bc_chat.contacts.R
import com.bc_chat.contacts.adapter.EmojiViewPagerAdapter
import com.bc_chat.contacts.databinding.ActivitySendPostingBinding
import com.bc_chat.contacts.view.PictureDialog1Fragment
import com.zhaohaoting.framework.abs.BaseActivity
import com.zhaohaoting.framework.abs.contract.BaseContract
import com.zhaohaoting.framework.imagepicker.ImagePicker
import com.zhaohaoting.framework.imagepicker.bean.MediaItem
import com.zhaohaoting.framework.imagepicker.ui.ImagePreviewActivity
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.ActivityUtils
import com.zhaohaoting.framework.utils.Check
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.Utils
import java.lang.StringBuilder
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/8/28
 * email：526309416@qq.com
 * desc：
 */
class SendPostingActivity : BaseActivity<ReleaseTopicPresenter>(), ReleaseTopicContract.View {

    companion object {
        const val MAX_IMG_COUNT = 6               //允许选择图片最大数
        const val PHOTO_PREVIEW = 411
    }

    private val mediaItemList = ArrayList<MediaItem>()

    private val binding by lazy {
        rootDataBinding as ActivitySendPostingBinding
    }
    private var photoAdapter: PhotoAdapter? = null

    private var isShowKeyBoard: Boolean = false //当前键盘是否显示

    override fun getLayoutResId(): Int = R.layout.activity_send_posting

    override fun initPresenter(): ReleaseTopicPresenter? {
        return ReleaseTopicPresenter(this)
    }

    private val handler = Handler(Looper.getMainLooper())

    override fun initialize() {
        isTouchHide = false
        initView()
        initEvent()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initEvent() {
        binding.root.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            binding.root.getWindowVisibleDisplayFrame(rect)
            val height = binding.root.rootView.height
            val mainInvisibleHeight = height - rect.bottom
            if (mainInvisibleHeight > height / 4) {
                if (isShowKeyBoard) return@addOnGlobalLayoutListener
                isShowKeyBoard = true

                //显示键盘
                binding.expressioLayout.visible()
                if (binding.ivExpressio.isSelected) { //表情模式
                    binding.emojiView.gone()
                    binding.ivExpressio.isSelected = false
                }
            } else {
                if (!isShowKeyBoard) return@addOnGlobalLayoutListener
                isShowKeyBoard = false

                //键盘隐藏
                if (!binding.ivExpressio.isSelected) {
                    binding.emojiView.gone()
                    binding.expressioLayout.gone()
                }
            }
        }
        binding.ivExpressio.setOnClickListener {
            binding.ivExpressio.isSelected = !binding.ivExpressio.isSelected
            if (binding.ivExpressio.isSelected) {
                Utils.hideInputMethod(this)
                handler.postDelayed({
                    binding.emojiView.visible()
                }, 200)
            } else {
                handler.postDelayed({
                    Utils.showSoftInput(this, currentFocus)
                }, 200)
                binding.emojiView.gone()
            }
        }
        binding.emojiView.setEmojiClickListener(object : EmojiViewPagerAdapter.EmojiClickListener {
            override fun deleteEmoji() {
                if (currentFocus is EditText) {
                    val textView = currentFocus as EditText
                    if (!TextUtils.isEmpty(textView.text)) {
                        val event = KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL)
                        textView.dispatchKeyEvent(event)
                    }
                }
            }

            override fun clickEmoji(emoji: Emoji?) {
                if (currentFocus is EditText) {
                    val textView = currentFocus as EditText
                    val selectionEnd = textView.selectionEnd
                    textView.text.insert(selectionEnd, emoji?.emojiText)
                }
            }
        })
        binding.tvContent.setOnTouchListener { v, event ->
            binding.emojiView.gone()
            binding.ivExpressio.isSelected = false
            handler.postDelayed({
                Utils.showSoftInput(this, v)
            }, 200)
            return@setOnTouchListener false
        }
        binding.tvTitle.setOnTouchListener { v, event ->
            binding.emojiView.gone()
            binding.ivExpressio.isSelected = false
            handler.postDelayed({
                Utils.showSoftInput(this, v)
            }, 200)
            return@setOnTouchListener false
        }
    }

    private fun initView() {
        binding.rvImage.setHasFixedSize(true)
        binding.rvImage.isNestedScrollingEnabled = false
        binding.rvImage.layoutManager = GridLayoutManager(this, 4)
        photoAdapter = PhotoAdapter(this, MAX_IMG_COUNT)
        binding.rvImage.adapter = photoAdapter
        photoAdapter?.addOnItemViewClickListener { vh, view, position ->
            if (view.id == R.id.iv_delete) {
                mediaItemList.removeAt(position)
                photoAdapter?.notifyListDataChanged(mediaItemList, true)
            } else {
                if (photoAdapter?.getItemViewType(position) == 1) {
                    val pictureDialog1Fragment = PictureDialog1Fragment()
                    val bundle = Bundle()
                    bundle.putInt("selectLimit", MAX_IMG_COUNT - photoAdapter?.data!!.size)
                    pictureDialog1Fragment.arguments = bundle
                    pictureDialog1Fragment.show(fragmentManager)
                    pictureDialog1Fragment.setPicturePhotoPathListener { mediaItemList ->
                        this.mediaItemList.addAll(mediaItemList)
                        refreshPhoto()
                    }
                } else {
                    ActivityUtils.newInstance(this)
                            .putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, ArrayList<MediaItem>(photoAdapter!!.data))
                            .putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position)
                            .putExtra(ImagePicker.EXTRA_FROM_ITEMS, true)
                            .navigation(ImagePreviewActivity::class.java, PHOTO_PREVIEW)
                }
            }
        }
        refreshPhoto()

    }

    private fun refreshPhoto() {
        photoAdapter?.notifyListDataChanged(mediaItemList, true)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menu.add(getString(R.string.release)).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        return super.onCreateOptionsMenu(menu)
    }

    private fun getPicUrls(urlList: List<String>?): String {
        val stringBuilder = StringBuilder()
        urlList?.let {
            it.map {
                stringBuilder.append(it).append(",")
            }
        }
        if (stringBuilder.isNotEmpty()) {
            stringBuilder.delete(stringBuilder.length - 1, stringBuilder.length)
        }
        return stringBuilder.toString();
    }

    private fun getPicPathList(): List<String> {
        val paths = mutableListOf<String>()
        mediaItemList.map {
            paths.add(it.path)
        }
        return paths
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val title = binding.tvTitle.text.toString().trim()
        val content = binding.tvContent.text.toString().trim()
        if (Check.isEmpty(title)) {
            ToastUtils.show("请输入标题")
            return true
        }
        if (Check.isEmpty(content)) {
            ToastUtils.show("请输入内容")
            return true
        }

        CustomDialog.Builder(this)
                .setMessage("确定要发布该帖子吗？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定") { dialog, which ->
                    presenter.upload(getPicPathList())
                }.create().show()
        return super.onOptionsItemSelected(item)
    }

    override fun releaseTopicSuccess() {
        setResult(Activity.RESULT_OK)
        finish()
    }

    override fun releaseTopicFailure(exception: Exception) {
    }

    override fun uploadSuccess(paths: MutableList<String>?) {
        val title = binding.tvTitle.text.toString().trim()
        val content = binding.tvContent.text.toString().trim()
        presenter.releaseTopic(title, content, getPicUrls(paths))
    }

    override fun uploadFailure(e: java.lang.Exception?) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            if (requestCode == PHOTO_PREVIEW) {
                if (data != null) {
                    mediaItemList.clear()
                    val mediaItems = data.getParcelableArrayListExtra<MediaItem>(ImagePicker.EXTRA_IMAGE_ITEMS)
                    if (mediaItems != null) {
                        mediaItemList.addAll(mediaItems)
                    }
                    refreshPhoto()
                }
            }
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (Utils.isShouldHideInput(v, ev) && Utils.isShouldHideInput(binding.ivExpressio, ev) && Utils.isShouldHideInput(binding.emojiView, ev)) {
                Utils.hideInputMethod(this)
                if (binding.ivExpressio.isSelected) {
                    binding.ivExpressio.isSelected = false
                    binding.emojiView.gone()
                    binding.expressioLayout.gone()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else onTouchEvent(ev)
    }

}