package com.zxhl.uc.page.fragment

import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import byc.imagewatcher.ImageWatcher
import byc.imagewatcher.ImageWatcherHelper
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.decoration.GridSpacingItemDecoration
import com.luck.picture.lib.entity.LocalMedia
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.common.base.BaseActivity.OnKeyDownListener
import com.zxhl.cms.common.base.BaseFragment
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.chat.PhotoEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.CustomDotIndexProvider
import com.zxhl.cms.widget.CustomLoadingUIProvider
import com.zxhl.cms.widget.GlideSimpleLoader
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.uc.R
import com.zxhl.uc.page.*
import com.zxhl.uc.page.`interface`.SimpleItemTouchHelperCallback
import kotlinx.android.synthetic.main.fragment_user_center.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


/**
 * Created by gaoleichao on 2019/3/12
 */
class UserCenterFragment : BaseFragment(), AdCallback<String>,
    OnRecycleItemClickListener<String>, UserContract.View, ImageWatcher.OnPictureLongPressListener,
    PhotoMoveListener {
    private var mLoading: LoadingDialog? = null
    private var mAdapter: PublishPhotoAdapter? = null
    private var mPresenter: UserPresenter? = null
    private val COLUMN: Int = 4
    override fun layoutID(): Int = R.layout.fragment_user_center
    private var mPhtoList: MutableList<LocalMedia>? = ArrayList()
    private var chossList: MutableList<String>? = ArrayList()//上传的图片的集合
    private var photoList: MutableList<PhotoEntity>? = ArrayList()//显示的图片的集合
    private var iwHelper: ImageWatcherHelper? = null
    var isTranslucentStatus = false
    override fun init(view: View?) {
        mLoading = LoadingDialog.getLoadingDialog(
            mActivity,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        mPresenter = UserPresenter(this)
        iwHelper =
            ImageWatcherHelper.with(mActivity, GlideSimpleLoader()) // 一般来讲， ImageWatcher 需要占据全屏的位置
                .setTranslucentStatus(if (!isTranslucentStatus) Utils.calcStatusBarHeight(AppContext.get()) else 0) // 如果不是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
                .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                .setOnPictureLongPressListener(this)
                .setOnStateChangedListener(object : ImageWatcher.OnStateChangedListener {
                    override fun onStateChangeUpdate(
                        imageWatcher: ImageWatcher,
                        clicked: ImageView,
                        position: Int,
                        uri: Uri,
                        animatedValue: Float,
                        actionTag: Int
                    ) {
                        Log.e(
                            "IW",
                            "onStateChangeUpdate [$position][$uri][$animatedValue][$actionTag]"
                        )
                    }

                    override fun onStateChanged(
                        imageWatcher: ImageWatcher,
                        position: Int,
                        uri: Uri,
                        actionTag: Int
                    ) {
                        if (actionTag == ImageWatcher.STATE_ENTER_DISPLAYING) {
                            //  Toast.makeText(getApplicationContext(), "点击了图片 [" + position + "]" + uri + "", Toast.LENGTH_SHORT).show();
                        } else if (actionTag == ImageWatcher.STATE_EXIT_HIDING) {
                            //  Toast.makeText(getApplicationContext(), "退出了查看大图", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setIndexProvider(CustomDotIndexProvider()) //自定义页码指示器（默认数字）
                .setLoadingUIProvider(CustomLoadingUIProvider()) // 自定义LoadingUI
        mAdapter = PublishPhotoAdapter(mActivity, this, this)
        id_ll_pay_vip?.setOnClickListener {
//            JumpUtils.payJump()
            JumpUtils.becomeVipJump()
        }
        id_ll_star_coin?.setOnClickListener {
//            JumpUtils.starCoinpayJump()
            JumpUtils.coinStoreJump()
        }
        id_rl_voice_room?.setOnClickListener {
            JumpUtils.VoiceRoomJump()
        }
        id_rl_choose_photo?.layoutManager = GridLayoutManager(mActivity, COLUMN)
        id_rl_choose_photo.addItemDecoration(GridSpacingItemDecoration(COLUMN, 10, false))
        id_rl_choose_photo.setAdapter(mAdapter)
        var callback = SimpleItemTouchHelperCallback(mAdapter!!)
        var touchHelper = ItemTouchHelper(callback)
        touchHelper?.attachToRecyclerView(id_rl_choose_photo)
        id_rl_top?.setOnClickListener {
            JumpUtils.UserInfoJump()
        }
        id_rl_zaixiankefu?.setOnClickListener {
            JumpUtils.webJump("Customer Service", NetConfig.H5.WEB_URL_CUSTOMER_SERVICE)
        }
        id_ll_my_follow?.setOnClickListener {
            JumpUtils.MyFollowJump()
        }
        id_ll_fans?.setOnClickListener {
            JumpUtils.MyFansJump()
        }
        id_ll_mylike?.setOnClickListener {
            EventUtils.onEvent("CheckLikedMe", "查看喜欢我")
            JumpUtils.MyLikesJump()
        }
//        id_rl_jiyijan?.setOnClickListener {
//            JumpUtils.FeedBackJump()
//        }
        id_rl_setting?.setOnClickListener {
            JumpUtils.SettingJump()
        }
        id_rl_about_us?.setOnClickListener {
            JumpUtils.AbuoutUsJump()
            //JumpUtils.webJump("About us", NetConfig.H5.WEB_URL_ABOUT_US)
        }


        updateView()
        (mActivity as BaseActivity?)!!.setOnKeyDownListener(OnKeyDownListener { keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (iwHelper!!.handleBackPressed()) {
                    return@OnKeyDownListener true
                }

            }
            false
        })

    }

    override fun data() {
        super.data()
        userVisibleHint = true
    }


    private var isPause = false

    override fun onPause() {
        super.onPause()
        isPause = true

    }


    override fun onResume() {
        super.onResume()
        if (isPause && isVisible && !ifphotoback) {
            UserDataUtils.updateUserInfo(this)
        }
        isPause = false
    }

    override fun lazyLoad() {
        super.lazyLoad()
        if (isInitial && isVisible) {
            UserDataUtils.updateUserInfo(this)
            //  getAds()
        }
    }

    private fun updateView() {
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        id_tv_yu_e_trip?.text = "${user.starBalance}"
        if (user.memberType == 0) {
            id_tv_member_date.visibility = View.GONE
            id_tv_privileage?.visibility = View.VISIBLE
            id_tv_member?.text = "Open VIP to unlock"
            id_tv_privileage?.text = "privilege"
//            id_tv_vip_trip?.setTextColor(AppContext.get().resources.getColor(R.color.white))
//            id_tv_vip_trip.setBackgroundResource(R.drawable.shape_ffa211_r15_stoke)
        } else {
            id_tv_member_date.visibility = View.VISIBLE
            id_tv_privileage?.visibility = View.GONE
            id_tv_member?.text = "VIP Expiration Date"
            id_tv_member_date?.text = "${user.memberEndTime}"
//            id_tv_vip_trip?.setTextColor(AppContext.get().resources.getColor(R.color.ffa211))
//            id_tv_vip_trip.setBackgroundResource(R.drawable.shape_ffffff_ffa211_r15)
        }
//        if (user.noRecharged) {
//            //未充值过
//            id_tv_yu_e_trip?.text = "充值星币获取超多玩法"
//            id_tv_coin_trip?.text = "立即充值"
//            id_tv_coin_trip?.setTextColor(AppContext.get().resources.getColor(R.color.white))
//            id_tv_coin_trip.setBackgroundResource(R.drawable.shape_ffc217_r15)
//        } else {
//            id_tv_yu_e_trip?.text = "星币余额：${user.starBalance}"
//            id_tv_coin_trip?.text = "继续充值"
//            id_tv_coin_trip?.setTextColor(AppContext.get().resources.getColor(R.color.ffc217))
//            id_tv_coin_trip.setBackgroundResource(R.drawable.shape_ffffff_ffc217_r15)
//        }
        id_fragment_user_center_name?.text = user.nickname
        id_fragment_user_center_id?.text = "ID:" + user.uid
        if (!TextUtils.isEmpty(user.headImage)) {
            Glide.with(this).load(user.headImage)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(id_fragment_user_center_photo)
        } else {
            id_fragment_user_center_photo.setImageResource(R.drawable.icon_user_photo_default)
        }
        if (!user.picturesList.isNullOrEmpty()) {
            mImgUrlList?.clear()
            mImgUrlList?.addAll(user.picturesList)
            if (mAdapter != null) {
                mAdapter?.clear()
            }
            mAdapter?.appendToList(user.picturesList)
            mAdapter?.notifyDataSetChanged()
        } else {
            if (mAdapter != null) {
                mAdapter?.clear()
            }
        }
        id_tv_follows?.text = "${user.follows}"
        id_tv_fans?.text = "${user.fans}"
        id_tv_likes?.text = "${user.likes}"
        if (!TextUtils.isEmpty(user.description)) {
            id_tv_description.visibility = View.VISIBLE
            id_tv_description?.text = user.description
        } else {
            id_tv_description.visibility = View.GONE
        }
    }

    override fun onResult(code: Int, result: String?) {
        updateView()
    }

    private val mImgList = ArrayList<LocalMedia>()
    var ifphotoback: Boolean = false
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        ifphotoback = true
        if (data != null && resultCode == -1) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                val selectList = PictureSelector.obtainMultipleResult(data)
                if (mAdapter != null) {
                    //   mPhtoList?.addAll(mAdapter?.list!!)
                }
                if (!selectList.isNullOrEmpty()) {
                    mImgList?.clear()
                    mImgList?.addAll(selectList)
                    checkImgList(0)
//                    for (i in selectList) {
//                        val f = File(i.compressPath)
//                        val requestFile =
//                            RequestBody.create("multipart/form-data".toMediaTypeOrNull(), f)
//                        val fileBody =
//                            MultipartBody.Part.createFormData("file", f.name, requestFile)
//                        mLoading?.setLoading("上传中")
//                        mLoading?.show()
//                        mPresenter?.upload(fileBody)
//                    }
//
//
                }
//                mAdapter?.appendToList(selectList)
//                mAdapter?.notifyDataSetChanged()
            }
        }
    }

    private var mImgUrlList = ArrayList<String>()

    fun checkImgList(num: Int) {
        if (mImgList.size > 0) {
            val data = mImgList[0]
            mImgList?.removeAt(0)
            uploadFile(data, num)
        } else {
            uploadPhotoUrl()
        }
    }

    //上传本地图片获取url
    fun uploadFile(data: LocalMedia, num: Int) {
        Log.e("MXL", "本地路径" + data.compressPath)
        val f = File(data.compressPath)
        val requestFile =
            RequestBody.create("multipart/form-data".toMediaTypeOrNull(), f)
        val fileBody =
            MultipartBody.Part.createFormData("file", f.name, requestFile)
        mLoading?.setLoading("上传中")
        mLoading?.show()
        mPresenter?.upload(fileBody)
        //写上报地址获取url逻辑，成功or失败， 成功调 mImgUrlList.add(url)  checkImgList(0)
        //失败
//        if (num < 3) {
//            val s = num + 1
//            uploadFile(data, s)
//        } else if (num == 3) {
//            //重试了三次失败的。
//            // data 做记录
//            // checkImgList(0)
//        } else {
//            checkImgList(0)
//        }
    }

    fun uploadPhotoUrl() {
        if (mImgUrlList.size > 0) {
            //走打包上报url逻辑
            val sb = StringBuilder()
            for (str in mImgUrlList!!) {
                if (sb.length > 0) {
                    sb.append(",")
                }
                sb.append(str)
            }
            Log.e("MXL", "参数" + sb.toString())
            mPresenter?.pictures(sb.toString())

        } else {
            //删到最后一张了
            mPresenter?.pictures("")
        }
    }

    fun getSize(): Int {
        if (mAdapter == null) {
            return 8
        } else {
            return 9 - mAdapter?.itemCount!!
        }

    }

    override fun uploadSuc(result: String) {
        mImgUrlList.add(result)
        checkImgList(0)
//        chossList?.add(result)
//        if (!chossList.isNullOrEmpty()) {
//            val sb = StringBuilder()
//            for (str in chossList!!) {
//                if (sb.length > 0) {
//                    sb.append(",")
//                }
//                sb.append(str)
//            }
//            mPresenter?.pictures(sb.toString())
//        }
    }

    override fun uploadFail() {

    }

    override fun updatePicSuc() {
        mImgUrlList.clear()
        mLoading?.setResult(true, "成功", 1000)
        UserDataUtils.updateUserInfo(this)

    }

    override fun updatePicFail() {
        mLoading?.setResult(true, "失败", 1000)
    }

    override fun onItemClick(view: View?, position: Int, data: String?) {
        when (view?.id) {
            R.id.id_img_add -> {
                EventUtils.onEvent("UploadAlbumImage", "相册上传图")
                PictureSelector.create(this)
                    .openGallery(PictureConfig.TYPE_IMAGE)
                    .imageSpanCount(4)// 每行显示个数 int
                    .maxSelectNum(getSize())
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .isSingleDirectReturn(true)//PictureConfig.SINGLE模式下是否直接返回
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .setOutputCameraPath(com.zxhl.cms.common.Const.getImgPath())// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .compressSavePath(com.zxhl.cms.common.Const.getImgPath())//压缩图片保存地址
                    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为 false   true or false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为 false    true or false
                    .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                    .forResult(PictureConfig.CHOOSE_REQUEST)//结果回调onActivityResult code
            }
            R.id.id_img_del -> {
                delet(position)
            }
            R.id.id_img_show -> {
                iwHelper?.show(
                    getImageUriList(mImgUrlList), position
                )
            }
        }

    }

    fun getImageUriList(files: List<String?>?): List<Uri>? {
        val imageUriList: MutableList<Uri> = java.util.ArrayList()
        if (files != null && files.size > 0) {
            for (str in files) {
                imageUriList.add(Uri.parse(str))
            }
        }
        return imageUriList
    }

    fun delet(position: Int) {
        mImgUrlList?.removeAt(position)
        mLoading?.setLoading("删除中")
        mLoading?.show()
        uploadPhotoUrl()
    }

    override fun onPictureLongPress(v: ImageView?, uri: Uri?, pos: Int) {

    }

    override fun moveFinish() {
        if (mAdapter != null && !mAdapter?.list.isNullOrEmpty()) {
            mImgUrlList?.clear()
            mImgUrlList.addAll(mAdapter?.list!!)
            uploadPhotoUrl()


        }
    }


}