package com.yidianling.user.mine

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.ydl.ydlcommon.actions.imagepicker.BrowsePicturesActivity
import com.ydl.ydlcommon.actions.imagepicker.ImageCompress
import com.ydl.ydlcommon.actions.imagepicker.YDLImagePicker
import com.ydl.ydlcommon.adapter.custom.PublishImageAdapter
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.ui.ParcelableImage
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.R
import com.yidianling.user.UserHelper
import com.yidianling.user.mine.data.AppDataManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_mine_activity_feed_back.*
import java.io.File
import kotlin.properties.Delegates


/**
 * 意见反馈
 * Created by softrice on 15/12/1.
 */
@Route(path = "/mine/FeedBackActivity")
class FeedBackActivity : BaseActivity(), View.OnClickListener {
    private val PUBLISH_PIC_BROW = 21009

    private var adapter: PublishImageAdapter? = null
    private var imags: ArrayList<ParcelableImage>? = ArrayList()
    private var phone = UserHelper.getUserInfo()?.userInfo?.phone?:""
    private var isPhoneNull = true
    private var imgFiles: MutableList<File>? = null

    internal var work_time = if (PlatformDataManager.getRam().getGlobalInfo() == null) "早8:30-凌晨2:00" else PlatformDataManager.getRam().getGlobalInfo()?.info?.work_time
    internal var tel = if (PlatformDataManager.getRam().getGlobalInfo() == null) "400-765-1010" else PlatformDataManager.getRam().getGlobalInfo()?.info?.tel
    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(true, true)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.user_mine_activity_feed_back)
        init()
    }

    internal fun init() {
        adapter = PublishImageAdapter(imags, this)
        feedback_img_rcv!!.layoutManager = GridLayoutManager(this, 3) as RecyclerView.LayoutManager?
        feedback_img_rcv!!.adapter = adapter
        if (!TextUtils.isEmpty(phone)) {
            isPhoneNull = false
            et_input_phone!!.setText(phone!!)
            et_input_phone!!.setSelection(et_input_phone!!.text.length)
            et_input_phone!!.clearFocus()
        }
        et_input_phone!!.onFocusChangeListener = View.OnFocusChangeListener { _, _ ->
            if (et_input_phone!!.text.toString().contains("*")) {
                et_input_phone!!.setText("")
            }
        }
        et_input_phone!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                LogUtil.d("s: $s start: $start count: $count after: $after")

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                LogUtil.d("s: $s start: $start before: $before count: $count")


            }

            override fun afterTextChanged(s: Editable) {
                phone = s.toString()
                LogUtil.d("final edit phone: $phone")
            }
        })
        tb_title!!.setLeftTextColor(resources.getColor(R.color.platform_main_theme))
        tb_title!!.setRightTextColor(resources.getColor(R.color.platform_main_theme))
        tv_commit.setOnClickListener {
            if (TextUtils.isEmpty(et_input_phone!!.text.toString())) {
                ToastUtil.toastShort("请输入联系手机，以便我们及时反馈")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(et_feed_back!!.text.toString())) {
                ToastUtil.toastShort("请输入内容哦")
                return@setOnClickListener
            }
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            if (imags != null && imags!!.size > 0) {
                dealFile(imags)
            } else {
                upLoadFeedBack()
            }
        }
        setUpEvent()


//        var listener = KeyboardChangeListener(this)
//        listener.setKeyBoardListener { isShow, _ ->
//            if (!isShow) {
//                et_input_phone.clearFocus()
//            }
//        }
    }

    private fun setUpEvent() {
        adapter!!.setOnItemClickLister(object : PublishImageAdapter.OnItemClickLister {
            override fun onItemClick(view: View, position: Int) {
                if (imags!!.size > 0) {
                    try {
                        val intent = Intent()
                        intent.setClass(
                            this@FeedBackActivity,
                            BrowsePicturesActivity::class.java
                        )
                        intent.putExtra("browse_type", "preview")
                        intent.putExtra("position", position)
                        val bd = Bundle()
                        bd.putParcelableArrayList("allTrendImages", imags as ArrayList<out Parcelable>?)
                        intent.putExtra("allTrendImages_bd", bd)
                        startActivityForResult(intent, PUBLISH_PIC_BROW)
                    }catch (e: Exception) {}
                }

            }

            override fun onItemLongClick(view: View, position: Int) {

            }
        })
        adapter!!.setOnDeleteClickLister(object : PublishImageAdapter.OnDeleteClickLister {
            override fun onDeleteClick(view: View, position: Int) {
                deleteImg(position)
            }

            override fun onDeleteLongClick(view: View, position: Int) {

            }
        })
        adapter!!.setOnAddClickLister(object : PublishImageAdapter.OnAddClickLister {
            override fun OnAddClick(view: View, position: Int) {
                if (imags!!.size < 3) {
                    showSelector()
                } else {
                    if ("default" == imags!![2].image_url) {
                        showSelector()
                    } else {
                        Toast.makeText(this@FeedBackActivity, "最多选择9张照片", Toast.LENGTH_SHORT).show()
                    }
                }
            }

            override fun OnAddLongClick(view: View, position: Int) {

            }
        })
        iv_add_imag.setOnClickListener(this)
        tv_phone.setOnClickListener(this)
    }

    /**
     * 删除照片
     */
    private fun deleteImg(position: Int) {
        if (imags!!.size > 0) {
            imags!!.removeAt(position)
            adapter!!.updateDate(imags)
        }
        if (imags!!.size <= 0) {
            iv_add_imag!!.visibility = View.VISIBLE
            feedback_img_rcv!!.visibility = View.GONE
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_add_imag -> showSelector()
            R.id.tv_phone -> CommonDialog(this@FeedBackActivity)
                    .setMessage("欢迎致电壹点灵客服热线\n$tel\n服务时间:$work_time")
                    .setLeftOnclick("取消") { }.setRightClick("拨打") {
                        val phoneIntent = Intent(Intent.ACTION_DIAL,
                                Uri.parse("tel:$tel"))
                        this@FeedBackActivity.startActivity(phoneIntent)
                    }.show()
        }
    }

    private fun showSelector() {
        YDLImagePicker.startPicker(this as BaseActivity, object : OnResultCallbackListener {
            override fun onResult(list: List<LocalMedia>) {
                if (list.isEmpty()) {
                    return
                }
                for (i in list.indices) {
                    addImag(list[i].path)
                }
            }

            override fun onCancel() {

            }
        })
    }

    /**
     * 添加照片
     */
    private fun addImag(pic_path: String) {
        LogUtil.d("PATH: $pic_path")
        val trendImage = ParcelableImage(pic_path)
        if (imags!!.size >= 1) {
            ToastUtil.toastShort("最多上传一张图片")
        } else {
            imags!!.add(trendImage)
        }
        adapter!!.updateDate(imags)
        if (feedback_img_rcv!!.visibility != View.VISIBLE) {
            feedback_img_rcv!!.visibility = View.VISIBLE
        }
        if (iv_add_imag!!.visibility == View.VISIBLE) {
            iv_add_imag!!.visibility = View.GONE
        }
    }


    @SuppressLint("WrongConstant")
    private fun dealFile(publishTrendImgs: MutableList<ParcelableImage>?) {
        imgFiles = ArrayList()
        if (publishTrendImgs!!.size > 1 && publishTrendImgs.size <= 3) {
            publishTrendImgs.removeAt(publishTrendImgs.size - 1)
        }
        Observable.fromIterable(publishTrendImgs)
                .subscribeOn(Schedulers.io())
                .map { parcelableImage ->
                    LogUtil.d("url: " + parcelableImage.image_url)
                    DealFile2(parcelableImage.image_url, 1500 / publishTrendImgs.size)
                }
                .subscribe { file ->
                    if (file != null) {
                        LogUtil.d("xyutest", "图片压缩后大小: ==>" + file.length() + " file path: " + file.absolutePath)
                        imgFiles!!.add(file)
                        if (imgFiles!!.size == publishTrendImgs.size) {
                            upLoadFeedBack()
                        }
                    } else {
                        runOnUiThread { Toast.makeText(this@FeedBackActivity, "有图片已被删除", Toast.LENGTH_SHORT).show() }
                    }
                }

    }

    @Synchronized
    private fun DealFile2(path: String, size: Int): File {
        var deal_file: File by Delegates.notNull()
        try {
            deal_file = ImageCompress.scal(this@FeedBackActivity, path, size)
        }catch (e:Exception){

        }
        try {
            Thread.sleep(100)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        return deal_file
    }

    private fun upLoadFeedBack() {
        showProgressDialog("")
        val cmd = FeedBackParam(et_feed_back!!.text.toString(), phone)
        var files: Array<File>? = emptyArray()
        if (imgFiles != null && imgFiles!!.size > 0) {
            files = Array(imgFiles!!.size) { i: Int -> imgFiles!![i] }
//            for (i in imgFiles!!.indices) {
//                files[i] = imgFiles!![i]
//            }
        }
        AppDataManager.getHttp().feedBack(cmd, files)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ resp ->
                    dismissProgressDialog()
                    if (resp.code === 0) {
                        startActivity(Intent(this@FeedBackActivity, FeedBackSuccessActivity::class.java))
                        finish()
                    } else {
                        ToastUtil.toastShort(resp.msg)
                    }
                }, { throwable ->
                    HttpErrorUtils.handleError(this@FeedBackActivity, throwable)
                    dismissProgressDialog()
                })
    }

    override fun layoutResId(): Int {
        return 0
    }

    override fun initDataAndEvent() {

    }

    companion object {

        private val PICK_IMAGE_COUNT = 9
        private val PORTRAIT_IMAGE_WIDTH = 720
        val JPG = ".jpg"

        fun newIntent(activity: Activity): Intent {
            return Intent(activity, FeedBackActivity::class.java)
        }
    }
}
