package com.zxhl.uc.page.fragment

import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
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.zxhl.cms.AppContext
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.net.model.box.AppInEntity
import com.zxhl.cms.net.model.box.HomeBoxListEntity
import com.zxhl.cms.utils.*
import com.zxhl.uc.R
import kotlinx.android.synthetic.main.fragment_user_center.*
import kotlinx.android.synthetic.main.layout_recommend.*

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

    override fun layoutID(): Int = R.layout.fragment_layout_new_usercenter
    private var mAdapter: RecomendAdapter? = null
    override fun init(view: View?) {
        mAdapter = RecomendAdapter(mActivity)
        id_rl_tuijian_box?.layoutManager = GridLayoutManager(mActivity, 2)
        id_rl_tuijian_box?.adapter = mAdapter

        id_rl_address?.setOnClickListener {
            JumpUtils.ReceiveAddressReslutJump("0")
        }
        id_ll_my_coin?.setOnClickListener {
            JumpUtils.payJump("0", "0", "0")
        }
        id_rl_logistics?.setOnClickListener {
            JumpUtils.LogisticsJump()
        }
        id_rl_jiyijan?.setOnClickListener {
            JumpUtils.webJump(mActivity.getString(R.string.customer_service), NetConfig.H5.WEB_URL_CUSTOMER_SERVICE)
        }
        id_rl_lianxikefu?.setOnClickListener {
            JumpUtils.webJump(mActivity.getString(R.string.customerservice), NetConfig.H5.WEB_URL_CUSTOMER_SERVICE)
        }
        id_rl_about_us?.setOnClickListener {
            JumpUtils.webJump(mActivity.getString(R.string.about_us), NetConfig.H5.WEB_URL_ABOUT_US)
        }
////        id_fragment_user_member_btn?.setOnClickListener {
////            JumpUtils.memberJump()
////        }
//        id_tv_lianxi_kefu?.setOnClickListener {
//            JumpUtils.webJump("联系客服", NetConfig.H5.WEB_URL_CUSTOMER_SERVICE)
//        }
        updateView()

//        id_fragment_user_pri?.setOnClickListener {
//            JumpUtils.webJump("隐私协议", NetConfig.H5.WEB_URL_PRIVACY)
//        }

//        id_fragment_user_user?.setOnClickListener {
//            JumpUtils.webJump("用户协议", NetConfig.H5.WEB_URL_USER)
//        }
        id_ll_my_magic_coin?.setOnClickListener {
            //我的魔币
            JumpUtils.MyMagicCoinJump()
        }
        id_rl_my_order?.setOnClickListener {
            //我的订单
            JumpUtils.MyOrderJump()
        }

    }

    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) {
            UserDataUtils.updateUserInfo(this)
        }
        isPause = false
    }

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

    private fun updateView() {
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        id_fragment_user_center_name?.text = user.nickname
        id_fragment_user_center_id?.text = "ID:" + user.uid
        id_tv_lucky_coin_ava?.text = user.ava ?: "0"
        id_tv_magic_num?.text = user.avaMagic ?: "0"
        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)
        }
//        memberEndTime


    }

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

    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()) {
                        if (result?.isNotEmpty()) {
                            updataAdView(slotId, result?.get(0), 0)
                        } else {
                            updataAdView(slotId, null, 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
            AdDataSupport.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开始渲染广告
                        }
                    }
                })
        }
    }

    fun getAppInfo() {
        ApiClient.homeApi.getAppInfo()
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<AppInEntity>() {
                override fun onSuccess(result: AppInEntity?) {
                    if (result != null) {
                        if (result.feedback_open.equals("0")) {
                            //id_rl_logistics.visibility = View.GONE
                        } else {
                            id_rl_logistics.visibility = View.VISIBLE
                        }
                    }
                }

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

                }
            })
    }

    fun getRecomendList() {
        ApiClient.homeApi.getInfoBoxList(1, 16)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<HomeBoxListEntity>>() {
                override fun onSuccess(result: List<HomeBoxListEntity>?) {
                    mAdapter?.clear()
                    mAdapter?.appendToList(result)
                    mAdapter?.notifyDataSetChanged()
                }

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

                }
            })
    }
}