package com.zxbw.modulemain.activity

import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.util.Log
import android.view.View
import android.webkit.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.zxbw.modulemain.R
import com.zxbw.modulemain.adapter.DetailBannerAdapter
import com.zxbw.modulemain.adapter.GoodsListAdapter
import com.zxbw.modulemain.contract.TbGoodsDetailContract
import com.zxbw.modulemain.presenter.TbGoodsDetailPresenter
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.model.qy.ConvertLinkEntity
import com.zxhl.cms.net.model.qy.TbGoodsItemEntity
import com.zxhl.cms.net.model.shop.ShopListEntity
import com.zxhl.cms.utils.EventUtils
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.OnRecycleItemClickListener
import com.zxhl.cms.utils.Utils
import com.zxhl.cms.widget.LoadingDialog
import kotlinx.android.synthetic.main.activity_layout_tb_goods_detail.*
import me.jessyan.autosize.utils.ScreenUtils

/**
 * @author (wangXuewei)
 * @datetime 2022-05-24 17:12 GMT+8
 * @detail : 淘宝商品详情
 */
class TbGoodsDetailActivity : BaseActivity(), TbGoodsDetailContract.View {
    private var mLoading: LoadingDialog? = null
    private var mGoodsAdapter: GoodsListAdapter? = null;
    private var mPresenter: TbGoodsDetailPresenter? = null;
    private var goodsDetail: TbGoodsItemEntity? = null

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_tb_goods_detail
    }

    override fun init() {
        var statusBarHeight = ScreenUtils.getStatusBarHeight()
        if (statusBarHeight <= 0) {
            statusBarHeight = 40;
        }
        id_tb_goods_detail_title_sys_bar_view.layoutParams.height = statusBarHeight

        goodsDetail = intent.getSerializableExtra("goods") as TbGoodsItemEntity
        refreshData()
//        mPresenter?.getGoodsDetail(goodsDetail?.item_id ?: "")
    }

    private fun refreshData(){
        mPresenter = TbGoodsDetailPresenter(this)
        mGoodsAdapter = GoodsListAdapter(this,
            OnRecycleItemClickListener<TbGoodsItemEntity> { view, position, data ->
                var intent = Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.putExtra("goods", data)
                intent.setClass(this, TbGoodsDetailActivity().javaClass)
                startActivity(intent)
            })
        id_rcl_recommend_goods_list?.layoutManager = LinearLayoutManager(this)
        id_rcl_recommend_goods_list.adapter = mGoodsAdapter

        id_img_close_btn?.setOnClickListener(this)
        id_ll_tb_buy_view?.setOnClickListener(this)

        initView()

        var link = ""
        if (!goodsDetail?.item_url.isNullOrEmpty()) {
            link = goodsDetail?.item_url!!
        } else if (!goodsDetail?.item_id.isNullOrEmpty()) {
            link = goodsDetail?.item_id!!
        }
        mPresenter?.getConvertLink(link)
        mPresenter?.getTjGoodsList()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Log.d("wxw","newIntent")
        if (intent!=null){
            goodsDetail = intent.getSerializableExtra("goods") as TbGoodsItemEntity
            refreshData()
        }
    }

    private fun initView() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            true,
            true
        )
        if (goodsDetail == null) {
            return
        }

        id_tv_goods_name?.text = goodsDetail?.title
        id_tv_tm_price?.text = goodsDetail?.reserve_price
        id_tv_tm_buy_price?.text = goodsDetail?.reserve_price
        id_tv_sale_num?.text = goodsDetail?.volume ?: "0"

        if (goodsDetail?.coupon_amount.isNullOrEmpty()) {
            id_tv_xx_price?.text = "${goodsDetail?.reserve_price}"
            id_tv_vip_buy_price?.text = "${goodsDetail?.reserve_price}"
        } else {
            var r_price = goodsDetail?.reserve_price?.toDoubleOrNull() ?: 0 as Double
            var c_price = goodsDetail?.coupon_amount?.toDoubleOrNull() ?: 0 as Double
            var vipPrice = Utils.getNoMoreThanTwoDigits(
                Utils.sub(
                    r_price,
                    c_price
                )
            )
            id_tv_xx_price?.text = vipPrice
            id_tv_vip_buy_price?.text = vipPrice
        }
        if (!goodsDetail?.small_images.isNullOrEmpty()) {
            var mPagerAdapter = DetailBannerAdapter(goodsDetail?.small_images!!)
            id_detail_top_banner.adapter = mPagerAdapter
            id_tv_vp_index.text = "${1}/${goodsDetail?.small_images?.size ?: 0 + 1}"
            id_detail_top_banner.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    id_tv_vp_index.text =
                        "${position + 1}/${goodsDetail?.small_images?.size ?: 0 + 1}"
                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
        }

    }

    override fun onClick(v: View?) {
        when (v) {
            id_img_close_btn -> {
                finish()
            }
            id_ll_tb_buy_view -> {
                if (tbLink == "") {
                    showToast("未获取到信息，请重试")
                } else {
                    mLoading?.setLoading("请稍后")
                    mLoading?.show()
                    jumpTbWeb(tbLink, object : JumpTbCallBack {
                        override fun jumpSuccess() {
                            mLoading?.setResult(true, "成功", 1000)
                        }

                        override fun jumpError(error: String) {
                            Log.d("wxw", "error:$error")
                            mLoading?.setResult(false, "购买失败,请重试", 1000)
                            EventUtils.onEvent("JumpTbError", error)
                        }
                    })
                }
            }
        }
    }

    private var tbLink = "";
    override fun setConvertLink(result: ConvertLinkEntity?) {
        tbLink = result?.data?.coupon_short_url ?: ""
    }

    override fun setGoodsDetail() {

    }

    override fun setTjGoodsList(isRefresh: Boolean, result: List<TbGoodsItemEntity>?) {
        if (!result.isNullOrEmpty()){
            mGoodsAdapter?.clear()
            mGoodsAdapter?.appendToList(result)
        }
    }

    private interface JumpTbCallBack {
        fun jumpSuccess();
        fun jumpError(error: String);
    }

    private fun jumpTbWeb(sortUrl: String, callBack: JumpTbCallBack) {
//        id_tb_web_view.visibility = View.VISIBLE
        val webSettings = id_tb_web_view.settings
        webSettings.javaScriptEnabled = true
        //其他细节操作
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE //关闭webview中缓存
        webSettings.allowFileAccess = true //设置可以访问文件
        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
        webSettings.loadsImagesAutomatically = true //支持自动加载图片
        webSettings.defaultTextEncodingName = "utf-8" //设置编码格式
        webSettings.domStorageEnabled = true
        webSettings.allowFileAccessFromFileURLs = true;
        webSettings.allowUniversalAccessFromFileURLs = true;

        id_tb_web_view?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.e("WXW", "dURL" + url.toString())
                if (url == null) return false
                try {
                    if (url.startsWith("dianping://") //大众点评
                        || url.startsWith("tbopen://") //淘宝
                        || url.startsWith("openapp.jdmobile://") //京东
                        || url.startsWith("tmast://") //淘宝
                        || url.startsWith("pinduoduo://") //拼多多
                    //其他自定义的scheme
                    ) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                        callBack.jumpSuccess()
                        return true
                    }
                } catch (e: Exception) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    callBack.jumpError("跳转淘宝失败:${e.message}")
                    return true //没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                return false
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                super.onReceivedSslError(view, handler, error)
                callBack.jumpError("onReceivedSslError:" + error.toString())
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    callBack.jumpError("onReceivedError:" + error?.description)
                } else {
                    callBack.jumpError("onReceivedError:null")
                }
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
                callBack.jumpError("onReceivedHttpError:" + errorResponse.toString())
            }
        }
        id_tb_web_view.loadUrl(sortUrl)
    }

}