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 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.Constant
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.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 XymhTbGoodsDetailActivity : BaseActivity(), TbGoodsDetailContract.View,
    OnRecycleItemClickListener<TbGoodsItemEntity> {
    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, this)
        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)
        id_tv_open_vip_btn?.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 onResume() {
        super.onResume()
        if (Constant.Switch.isOpenVip) {
            id_ll_not_vip_view_tips.visibility = View.GONE
        } else {
            id_ll_not_vip_view_tips.visibility = View.VISIBLE
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        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?.zk_final_price
        id_tv_tm_buy_price?.text = goodsDetail?.zk_final_price
        id_tv_sale_num?.text = goodsDetail?.volume ?: "0"
        id_tv_not_vip_desc.text = "会员下单，立省${goodsDetail?.coupon_amount?.toDoubleOrNull() ?: 0}元"
        if (goodsDetail?.coupon_amount.isNullOrEmpty()) {
            id_tv_xx_price?.text = "${goodsDetail?.zk_final_price}"
            id_tv_vip_buy_price?.text = "${goodsDetail?.zk_final_price}"
        } else {
            var r_price = goodsDetail?.zk_final_price?.toDoubleOrNull() ?: 0.0
            var c_price = goodsDetail?.coupon_amount?.toDoubleOrNull() ?: 0.0
            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_tv_open_vip_btn -> {
                JumpUtils.MemberOrderJump()
            }
            id_ll_tb_buy_view -> {
                if (!Constant.Switch.isOpenVip) {
                    JumpUtils.MemberOrderJump()
                    return
                }
                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")
                            if(error.contains("跳转淘宝失败")){
                                mLoading?.setResult(false, "购买失败,请安装淘宝APP~", 1000)
                            }else{
                                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)
    }

    override fun onItemClick(view: View?, position: Int, data: TbGoodsItemEntity?) {
        var intent = Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.putExtra("goods", data)
        intent.setClass(this, XymhTbGoodsDetailActivity().javaClass)
        startActivity(intent)
    }



}