package com.zxbw.modulemain.fragment

import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTNativeExpressAd
import com.zx.ad.AdManager
import com.zx.ad.callback.InterertionAdListener
import com.zx.ad.callback.RewardVideoAdListener
import com.zx.ad.platform.csj.CSJAdManager
import com.zxbw.modulemain.R
import com.zxbw.modulemain.view.DialogUtils
import com.zxhl.cms.ad.upload.Utils.AdUpload
import com.zxhl.cms.ad.upload.model.NewsEntity
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseFragment
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.pay.H5PayUtil
import com.zxhl.cms.utils.*
import kotlinx.android.synthetic.main.fragment_layout_user_center.*

/**
 * Created by gaoleichao on 2019/3/12
 */
class UserCenterFragment : BaseFragment(), AdCallback<String> {

    override fun layoutID(): Int = R.layout.fragment_layout_user_center

    override fun init(view: View?) {
        id_ll_member?.setOnClickListener {
            //  JumpUtils.RechargeJump()

        }
        id_img_kefu?.setOnClickListener {
//            JumpUtils.webJump("客服", NetConfig.H5.WEB_URL_CUSTOMER_SERVICE)
//            JumpUtils.UDesk()
            JumpUtils.UserQuestion()
        }
        id_tv_kaitong?.setOnClickListener {
            JumpUtils.MemberOrderJump()
        }
        id_img_setting?.setOnClickListener {
            JumpUtils.SettingJump()
        }
        id_ll_aboutus?.setOnClickListener {
            JumpUtils.AbuoutUsJump()
            // JumpUtils.webJump("关于我们", NetConfig.H5.WEB_URL_ABOUT_US)
        }
        id_ll_login_out?.setOnClickListener {
            DialogUtils.showDeleteUserIdTips(mActivity) {
                deleteUser()
            }
        }
        id_ll_xieyi_zhengze?.setOnClickListener {
            JumpUtils.webJump("隐私政策", NetConfig.H5.WEB_URL_PRIVACY)
        }
        id_ll_yonghu_xieyi?.setOnClickListener {
            JumpUtils.webJump("用户协议", NetConfig.H5.WEB_URL_USER)
        }
        id_ll_my_warehouse?.setOnClickListener {
            JumpUtils.WareHouseJump()
        }
        id_ll_shangwu_hezuo?.setOnClickListener {
            //JumpUtils.WithdrawalJump()
            JumpUtils.MyOrderJump("")
        }
        id_ll_huafeiquan?.setOnClickListener {
            JumpUtils.PhoneVoucherJump()
        }

        id_ll_zaixiankefu?.setOnClickListener {
            JumpUtils.UserQuestion()
        }
        id_tv_daili?.setOnClickListener {
            DialogUtils.showDaili(mActivity)
        }
    }

    private fun showIntriAd() {
        AdManager.loadInterAd(activity!!, object : InterertionAdListener {
            override fun onAdShow() {

            }

            override fun onAdError(errorMsg: String?) {
                Log.e("MXL", "onAdError" + errorMsg)
            }

            override fun onAdClose() {

            }

        })
    }

    private fun loadRewardAd() {
        AdManager.loadRewardAd(activity!!, object : RewardVideoAdListener {
            override fun onRewardVideoAdClose() {
                Log.d("wxw", "onRewardVideoAdClose")
            }

            override fun onRewardVideoAdReward() {
                Log.d("wxw", "onRewardVideoAdReward")
            }

            override fun onRewardVideoAdShow() {
                Log.d("wxw", "onRewardVideoAdShow")
            }

            override fun onRewardVideoAdError(errorMsg: String?) {
                Log.d("wxw", "onRewardVideoAdError${errorMsg}")
            }
        })
    }

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

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

    private var isPause = false
    override fun onPause() {
        super.onPause()
        isPause = true

    }

    override fun onResume() {
        super.onResume()
        if (isPause) {
            UserDataUtils.updateUserInfo(this)
        }
    }

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

    fun updateView() {
        val user = SettingPreference.getUserInfoData()
        if (user == null || activity == null) {
            return
        }
        id_tv_user_number?.text = user.phone
        if (user.member) {
            id_tv_user_type?.visibility = View.GONE
            id_img_vip?.visibility = View.VISIBLE
            id_ll_trip?.visibility = View.GONE
            id_tv_kaitong?.visibility = View.GONE
        } else {
            id_tv_user_type?.text = "普通用户"
            id_img_vip?.visibility = View.GONE
            id_ll_trip?.visibility = View.VISIBLE
            id_tv_kaitong?.visibility = View.VISIBLE
        }
        if (!TextUtils.isEmpty(user.headImage) || activity?.isDestroyed!!) {
            Glide.with(this).load(user.headImage)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .error(R.drawable.icon_default_user_img)
                .into(id_img_user_head)
        } else {
            id_img_user_head.setImageResource(R.drawable.icon_head_defalt)
        }
    }

    fun deleteUser() {
        ApiClient.homeApi.getLoginOut()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<Any>() {
                override fun onSuccess(result: Any?) {
                    if (result != null) {
                        SettingPreference.saveToken("")
                        SettingPreference.saveUserInfo(null)
                        //JumpUtils.loginJump()
                        mActivity.finish()
                        Utils.onExit(mActivity)

                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }
            })
    }

    private fun getAds() {
        var slotId = "bigimage"
        ApiClient.adApi.getAds(slotId)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    if (result != null && result?.isNotEmpty()) {
                        updataAdView(slotId, result?.get(0), 0)

                    } else {
                        updataAdView(slotId, null, 0)
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    updataAdView(slotId, null, 0)
                }
            })
    }

    var mTTAd: TTNativeExpressAd? = null
    private fun updataAdView(slotId: String, data: NewsEntity?, count: Int) {
        if (data == null) {
            id_fragment_user_ad_layout?.visibility = View.GONE
            return
        }

        if (TextUtils.equals(data.adPlatform, "chuanshanjia")) {
            var expressViewWidth =
                (Utils.px2dip(context, PhoneUtils.getScreenWidth(context).toFloat()) - 32).toFloat()
            var expressViewHeight = 0f
            CSJAdManager.requestByteDailyActiveBigImgFeed(data?.codeId
                ?: "",
                expressViewWidth,
                expressViewHeight,
                object : TTAdNative.NativeExpressAdListener {
                    override fun onError(p0: Int, p1: String?) {
                        id_fragment_user_ad_layout?.removeAllViews()
//                    retryAds(slotId, data, count)
                    }

                    override fun onNativeExpressAdLoad(p0: MutableList<TTNativeExpressAd>?) {
                        Log.d("qbs", "onNativeExpressAdLoad")
                        if (p0?.isNotEmpty() == true) {
                            id_fragment_user_ad_layout?.visibility = View.VISIBLE
                            mTTAd = p0.get(0)
                            mTTAd?.setExpressInteractionListener(object :
                                TTNativeExpressAd.ExpressAdInteractionListener {
                                override fun onAdClicked(p0: View?, p1: Int) {
                                    //广告被点击
                                    AdUpload.onAdClick(data)
                                }

                                override fun onAdShow(view: View, type: Int) {
                                    //广告展示
                                    AdUpload.onAdImpression(data)
                                }

                                override fun onRenderFail(p0: View?, p1: String?, p2: Int) {
//                }
                                }

                                override fun onRenderSuccess(p0: View?, p1: Float, p2: Float) {
                                    Log.d("qbs", "onRenderSuccess:" + p1 + "------" + p2)
                                    id_fragment_user_ad_layout?.removeAllViews()
                                    id_fragment_user_ad_layout?.addView(p0)
//                }
                                }

                            })
                            mTTAd?.render()//调用render开始渲染广告
                        }
                    }
                })
        }
    }
}