package com.cheng.blzb.ui.fragment.bid.detail

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Base64
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.cheng.blzb.R
import com.cheng.blzb.bean.BidDetailEntity
import com.cheng.blzb.bean.UploadFileEntity
import com.cheng.blzb.bean.WxShareEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentBidDetailBinding
import com.cheng.blzb.event.FavoriteEvent
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.ShareManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.dialog.DownloadAttachmentDialog
import com.cheng.blzb.utils.BidTypeUtils
import com.example.base.browser.BrowserActivity
import com.example.base.common.RxBus
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.AppUtils
import com.example.base.utils.ClipboardUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.umeng.socialize.bean.SHARE_MEDIA

class BidDetailFragment: BaseFragment<FragmentBidDetailBinding, BidDetailViewModel>() {
    private lateinit var api: IWXAPI
    private val id by lazy { arguments?.getString("id") ?: "" }
    private val infoSource by lazy { arguments?.getString("info_source") ?: "" }

    private val contactsAdapter by lazy { ContactsAdapter() }
    private val imageAdapter by lazy { BidImageAdapter() }

    private var detail: BidDetailEntity? = null

    private var isFavorite: Boolean = false

    override fun initView() {
        super.initView()
        binding.rvContacts.adapter = contactsAdapter

        binding.rvImage.adapter = imageAdapter

        initWebView()
    }

    private fun initWebView() {
        val settings = binding.webView.settings
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true

        binding.webView.isVerticalScrollBarEnabled = false
        binding.webView.isHorizontalScrollBarEnabled = false
        binding.webView.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                return true
            }
        })
    }

    override fun initData() {
        super.initData()
        api = WXAPIFactory.createWXAPI(requireContext(), Constants.WechatAppId)
        mViewModel.getBidDetail(id, infoSource)
        mViewModel.sendAuth()
        EventReportManager.eventReport(EventConstants.JUMP_TO_BID_DETAIL, "", "{\"id\": $id}")
    }

    override fun initListener() {
        super.initListener()
        binding.ivShare.onClick {
            if (!api.isWXAppInstalled) {
                toast("您没有安装微信客户端,请先下载安装")
                return@onClick
            }
            val shareEntity = WxShareEntity()
            shareEntity.title = detail!!.origin_title
            shareEntity.link = UserConfigManager.getShareEntity()?.link ?: detail!!.share_url
            shareEntity.content = UserConfigManager.getShareEntity()?.content ?: detail!!.origin_title
            ShareManager.shareUrl(requireActivity(), SHARE_MEDIA.WEIXIN, shareEntity) {}
        }

        binding.ivDownload.onClick {
            if (detail!!.origin_attachment.isNotEmpty()) {
                val f = DownloadAttachmentDialog.newInstance(detail!!.origin_attachment)
                f.show(childFragmentManager, DownloadAttachmentDialog::class.java.simpleName)
            } else {
                toast("不可下载")
            }
        }

        binding.ivFavorite.onClick {
            if (!isFavorite) {
                mViewModel.favorite(detail!!.id, detail!!.info_source)
            } else {
                mViewModel.favoriteCancel(detail!!.id)
            }
        }

        binding.ivView.onClick {
            BrowserActivity.start(requireContext(), "原文", detail!!.origin_url)
            ClipboardUtils.copyText(detail!!.origin_url)
            toast("原文链接已复制")
        }

        contactsAdapter.setOnItemChildClickListener { _, view, i ->
            val item = contactsAdapter.getItem(i)
            when(view.id) {
                R.id.iv_call -> {
                    val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:${item.phone}"))
                    startActivity(intent)
                }
            }

        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.detailLiveData.observe(this) {
            detail = it
            setData()
        }

        mViewModel.favoriteLiveData.observe(this) {
            isFavorite = true
            setFavoriteStyle()
            RxBus.defaultInstance.post(FavoriteEvent())
            toast("收藏成功")
        }

        mViewModel.cancelLiveData.observe(this) {
            isFavorite = false
            setFavoriteStyle()
            RxBus.defaultInstance.post(FavoriteEvent())
            toast("取消收藏")
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun setData() {
        if (detail != null) {
            binding.tvTitle.text = detail!!.origin_title
            binding.tvTag.text = BidTypeUtils.getShortName(detail!!.type_name)
            binding.tvTag.setBgColor(BidTypeUtils.getTypeColor(detail!!.type_name))
            binding.tvAmount.text = detail!!.project_amount
            binding.tvLocation.text = detail!!.city_name
            binding.tvTime.text = detail!!.tips_time
            contactsAdapter.setList(detail!!.contact)

            if (TextUtils.isEmpty(detail!!.content_type) || detail!!.content_type == "1") {
                val encodedHtml: String = Base64.encodeToString(detail!!.origin_content.toString().toByteArray(), Base64.NO_PADDING)
                binding.webView.loadData(encodedHtml,"text/html","base64")
                binding.webView.visible()
                binding.rvImage.gone()
            } else {
                val imageList = Gson().fromJson<List<UploadFileEntity>>(Gson().toJson(detail!!.origin_content), object : TypeToken<List<UploadFileEntity>>() {}.type)
                imageAdapter.setList(imageList)
                binding.rvImage.visible()
                binding.webView.gone()
            }

            isFavorite = detail!!.is_fav
            setFavoriteStyle()

            if (TextUtils.isEmpty(detail?.project_amount)) {
                binding.tvAmount.gone()
            }
            if (detail!!.contact.isEmpty()) {
                binding.layoutContacts.gone()
            }
            if (detail!!.origin_attachment.isEmpty()) {
                binding.ivDownload.setImageResource(R.mipmap.ic_bid_download_disable)
            }
        }
    }

    private fun setFavoriteStyle() {
        if (isFavorite) {
            binding.ivFavorite.setImageResource(R.mipmap.ic_bid_favorited)
        } else {
            binding.ivFavorite.setImageResource(R.mipmap.ic_bid_favorite)
        }
    }

    override fun onDestroyView() {
        binding.webView.destroy()
        super.onDestroyView()
    }
}