package com.zxhl.main.page.fragment

import android.graphics.Paint
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.zxhl.cms.common.FragmentAdapter
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseFragment
import com.zxhl.cms.down.UpdateVersionManager
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.HomeBoxListEntity
import com.zxhl.cms.net.model.box.TabEntity
import com.zxhl.cms.utils.AdCallback
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.UpdateCallback
import com.zxhl.cms.utils.UserDataUtils.updateUserInfo
import com.zxhl.main.R
import com.zxhl.main.page.contract.NewPeopleContract
import com.zxhl.main.page.presenter.NewPeoplePresenter
import com.zxhl.main.page.view.BaseViewPagerFragment
import com.zxhl.main.page.view.DialogUtils
import com.zxhl.main.page.view.DiscountDialog
import com.zxhl.main.page.view.FreeGoodsDialog
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.layout_home_top.*
import kotlinx.android.synthetic.main.layout_new_people.*
import kotlinx.android.synthetic.main.layout_top_box.*


/**
 * Created by gaoleichao on 2021/10/25
 */
class HomeFragment : BaseFragment(), NewPeopleContract.View, UpdateCallback {
    private var mPresenter: NewPeoplePresenter? = null
    private var boxId: String? = ""
    private var price: String? = ""
    private var titles: MutableList<String>? = ArrayList()
//    override val createTitles = ArrayList<String>().apply {
//        add("全部")
//        add("数码")
//        add("生活")
//        add("护肤")
//        add("美食")
//    }

//     val createFragments: Array<BaseFragment> = arrayOf(
//        AllFragment.newInstance(),
//        DigitalFragment.newInstance(),
//        LifeFragment.newInstance(),
////            MemberCardFragment.newInstance(),
//        SkincareFragment.newInstance(),
//        FoodFragment.newInstance()
//    )

    //private var mAdapter: HomeAdapter? = null
    override fun layoutID(): Int {

        return R.layout.fragment_home
    }

    override fun lazyLoad() {
        super.lazyLoad()
        if (isInitial && isVisible) {
            updateUserInfo(AdCallback { code, result ->
                //  UpdateUserInfo()
            })
        }

    }

    override fun init(view: View?) {
        //showGuide()
        val updateVersionManager = this?.let { it1 -> UpdateVersionManager(mActivity, this) }
        updateVersionManager?.checkUpdate(true)
        mPresenter = NewPeoplePresenter(this)

        mPresenter?.getBoxTab()
        viewPager?.currentItem = 1
        id_tv_customer_service?.setOnClickListener {
            JumpUtils.webJump(
                getString(R.string.customer_service),
                NetConfig.H5.WEB_URL_CUSTOMER_SERVICE
            )
        }
//        id_ll_top_coin?.setOnClickListener {
//            JumpUtils.payJump("0", "0", "0")
//        }
        id_rl_new_people?.setOnClickListener {
            if (!TextUtils.isEmpty(boxId)) {
                JumpUtils.goodsDetailJump(boxId)
            } else {
                JumpUtils.goodsDetailJump(SettingPreference.getHomeBoxId())
            }
        }
        id_img_open_box?.setOnClickListener {
            if (!TextUtils.isEmpty(boxId)) {
                JumpUtils.goodsDetailJump(boxId)
            } else {
                JumpUtils.goodsDetailJump(SettingPreference.getHomeBoxId())
            }

        }
        id_img_open_box?.animation =
            AnimationUtils.loadAnimation(context, R.anim.scale_anim)


//        UpdateUserInfo()
    }

    fun initVeiwPager(result: List<TabEntity>) {
        val adapter = FragmentAdapter(childFragmentManager)
        viewPager?.adapter = adapter

        for (i in 0 until (result?.size ?: 0)) {
            val title = result[i].name ?: ""
            adapter?.addFrag(AllFragment.newInstance(title), title)
        }
        adapter?.notifyDataSetChanged()
        id_fragment_home_tab?.setViewPager(viewPager)
        id_fragment_home_tab?.setOverScrollMode(View.OVER_SCROLL_NEVER)
    }

    override fun data() {
        super.data()
        //  UpdateUserInfo()
    }

    private fun UpdateUserInfo() {
        Log.e("MXL", "首页更新用户余额信息")

        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
//        if (user.isNewUserV2 == true) {
//            Log.e("MXL", "ss" + user.isNewUserV2)
//            FreeGoodsDialog.showFreeGoosDialog(mActivity)
//        }else{
////            if(user.isNewUserV3==true){
////            DiscountDialog.showDiscountDialog(mActivity)
////            }
//        }
//        id_tv_user_name?.text = user.nickname
//        id_tv_coin_num?.text = user.ava
//        if (!TextUtils.isEmpty(user.headImage)) {
//            Glide.with(this).load(user.headImage)
//                .apply(RequestOptions.bitmapTransform(CircleCrop()))
//                .into(id_img_head)
//        } else {
//            id_img_head.setImageResource(R.drawable.icon_user_photo_default)
//        }

        if (!user.isNewUser) {
            id_rl_new_people?.visibility = View.GONE
            boxId = ""
        } else {
            Log.e("MXL", "新人" + user.isNewUser)
            mPresenter?.getNewBox()
//            id_rl_new_people?.visibility = View.VISIBLE
        }

    }


    companion object {

        fun newInstance() = HomeFragment()
    }

    override fun setTab(result: List<TabEntity>?) {
        if (result != null && result?.size > 0) {
//            for (i in result) {
//                titles?.add(i.name!!)
//                fragments?.add(AllFragment.newInstance())
//            }
            initVeiwPager(result)
        }
    }

    override fun setNewPeopleData(result: HomeBoxListEntity?) {
        Log.e("MXl", "新手item数据")
        boxId = result?.boxId
        id_tv_box_title?.text = result?.boxName
        id_tv_desc?.text = result?.description
        id_img_main?.setLoadImageUrl(result?.mainImage, false)
        id_img1?.setLoadImageUrl(result?.imageList2?.get(0), false)
        id_img2?.setLoadImageUrl(result?.imageList2?.get(1), false)
        id_img3?.setLoadImageUrl(result?.imageList2?.get(2), false)
        id_img4?.setLoadImageUrl(result?.imageList2?.get(3), false)
        id_img5?.setLoadImageUrl(result?.imageList2?.get(4), false)
        //
        if (boxId?.toInt() == -11) {
            price = result?.onePrice?.toInt()?.minus(20).toString()
            id_one_price?.text = "${result?.onePriceStr?.toInt()?.minus(20)}"
            id_tv_two_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG) //中划线
            id_tv_two_price?.text = result?.onePriceStr
            id_new_user_box_tips.text = "已减20元幸运币"
        } else if (boxId?.toInt() == -12) {
            price = result?.onePrice?.toInt()?.minus(5).toString()
            id_one_price?.text = "${result?.onePriceStr?.toInt()?.minus(5)}"
            id_tv_two_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG) //中划线
            id_tv_two_price?.text = result?.onePriceStr
            id_new_user_box_tips.text = "已减5元幸运币"
        } else {
            price = result?.onePrice?.toInt()?.minus(10).toString()
            id_one_price?.text = "${result?.onePriceStr?.toInt()?.minus(10)}"
            id_tv_two_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG) //中划线
            id_tv_two_price?.text = result?.onePriceStr
            id_new_user_box_tips.text = "已减10元幸运币"
        }

        id_tv_kai_dai_times?.text = "已开袋${result?.numbersStr ?: "0"}次"
        id_tv_min_max_price?.text = "${result?.minPriceStr}～${result?.maxPriceStr}元"
        id_rl_new_people?.visibility = View.VISIBLE
    }

    fun showGuide() {
        if (SettingPreference.getshowGuide()) {
            DialogUtils.showFirstGuide(mActivity, View.OnClickListener {

            })
        }

    }


    private var isPause = false

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

    override fun onResume() {
        super.onResume()
        if (isPause && isVisible) {
            updateUserInfo(AdCallback { code, result ->
                // UpdateUserInfo()
            })
        }
        isPause = false
    }

    override fun CheckUpate(boolean: Boolean) {
        Log.e("MXL", "判断完更新")
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        if (user.isNewUserV2 == true) {
            FreeGoodsDialog.showFreeGoosDialog(mActivity)
        }
    }
}