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.Constant
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.net.model.other.IsWeChatLoginEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.IsLoginCallBack
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>, WeChatLoginSuccessCallBall {

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

        id_rl_address?.setOnClickListener {
            wechatutil?.isWechatLogin(object : IsLoginCallBack<IsWeChatLoginEntity> {
                override fun onResult(result: IsWeChatLoginEntity?) {
                    if (result?.status.equals("0")) {
                        JumpUtils.ThirdPardLoginJump()
                    } else {
                        JumpUtils.ReceiveAddressReslutJump("0")
                    }
                }

                override fun onError(code: String?, errorMsg: String?) {

                }

            })


        }
        id_ll_my_coin?.setOnClickListener {
            wechatutil?.isWechatLogin(object : IsLoginCallBack<IsWeChatLoginEntity> {
                override fun onResult(result: IsWeChatLoginEntity?) {
                    if (result?.status.equals("0")) {
                        JumpUtils.ThirdPardLoginJump()
                    } else {
                        JumpUtils.payJump("0", "0", "0")
                    }
                }

                override fun onError(code: String?, errorMsg: String?) {

                }

            })

        }
        id_rl_logistics?.setOnClickListener {
            JumpUtils.LogisticsJump()
        }
        id_rl_jiyijan?.setOnClickListener {
            wechatutil?.isWechatLogin(object : IsLoginCallBack<IsWeChatLoginEntity> {
                override fun onResult(result: IsWeChatLoginEntity?) {
                    if (result?.status.equals("0")) {
                        JumpUtils.ThirdPardLoginJump()
                    } else {
                        JumpUtils.webJump(
                            mActivity.getString(R.string.customer_service),
                            NetConfig.H5.WEB_URL_CUSTOMER_SERVICE
                        )
                    }
                }

                override fun onError(code: String?, errorMsg: String?) {

                }

            })

        }
        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)
//        }
        if (Constant.Switch.isOpenShop) {
            id_ll_my_magic_coin.visibility = View.VISIBLE
        } else {
            id_ll_my_magic_coin.visibility = View.GONE
        }
        id_ll_my_magic_coin?.setOnClickListener {
            //我的魔币

            wechatutil?.isWechatLogin(object : IsLoginCallBack<IsWeChatLoginEntity> {
                override fun onResult(result: IsWeChatLoginEntity?) {
                    if (result?.status.equals("0")) {
                        JumpUtils.ThirdPardLoginJump()
                    } else {
                        JumpUtils.MyMagicCoinJump()
                    }
                }

                override fun onError(code: String?, errorMsg: String?) {

                }

            })

        }
        id_rl_my_order?.setOnClickListener {
            //我的订单
            wechatutil?.isWechatLogin(object : IsLoginCallBack<IsWeChatLoginEntity> {
                override fun onResult(result: IsWeChatLoginEntity?) {
                    if (result?.status.equals("0")) {
                        JumpUtils.ThirdPardLoginJump()
                    } else {
                        JumpUtils.MyOrderJump()
                    }
                }

                override fun onError(code: String?, errorMsg: String?) {

                }

            })
        }

    }

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


    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) {
            getAppInfo()
            UserDataUtils.updateUserInfo(this)
            //  getAds()
        }
    }

    fun isLogin() {
        wechatutil?.isWechatLogin(object : IsLoginCallBack<IsWeChatLoginEntity> {
            override fun onResult(result: IsWeChatLoginEntity?) {
                if (result?.status.equals("1")) {

                }
            }

            override fun onError(code: String?, errorMsg: String?) {

            }

        })
    }

    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?) {
//                    Log.e("wxw","code "+code+" msg"+errorMsg)
//                    Log.e("wxw","e "+e?.message)
                }
            })
    }

    override fun loginSuccess(lottery: String?) {

    }
}