package com.zxhl.cms.widget

import android.app.Activity
import android.app.Dialog
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.umeng.analytics.MobclickAgent
import com.umeng.socialize.bean.SHARE_MEDIA
import com.zxhl.cms.AppContext
import com.zxhl.cms.R
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.other.ExitData
import com.zxhl.cms.umeng.UmengCountConfig
import com.zxhl.cms.umeng.UmengShareUtils
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.PhoneUtils
import com.zxhl.cms.utils.Utils
import com.zxhl.cms.utils.cache.UserCacheUtils

/**
 * Created by gaoleichao on 2018/8/17.
 */
object CenterDialog {

    fun showBottomDialog(
        layout: Int,
        activity: Context,
        setHeadDialog: Dialog,
        animation: Int,
        gravity: Int
    ): View {

        // AlertDialog setHeadDialog = new AlertDialog.Builder(activity).create();
        // setHeadDialog.show();

        val mDialogView = View.inflate(activity, layout, null)
        setHeadDialog.setContentView(mDialogView)
        val window = setHeadDialog.window
        // window.setContentView(mDialogView);
        window?.setGravity(gravity)
//        window.setWindowAnimations(R.style.AnimBottom)
        // WindowManager windowManager = activity.getWindowManager();
        // Display display = windowManager.getDefaultDisplay();
        val lp = window?.attributes
        window?.decorView?.setPadding(0, 0, 0, 0)
        // 设置宽度
        //Point size = new Point();
        //display.getSize(size);
        //lp.width = size.x;
        lp?.width = PhoneUtils.getScreenWidth(AppContext.get())
        if (gravity == Gravity.TOP) {
            lp?.height = PhoneUtils.getScreenHeight(AppContext.get())
        }
        //lp.width = (int) (display.getWidth()); // 设置宽度方式二: @过时
        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,0);
        window?.attributes = lp
        if (animation > 0)
            window?.setWindowAnimations(animation)//设置动画
        return mDialogView
    }


    private fun checkCode(code: String, observer: BaseObserver<Any>) {
        if (TextUtils.isEmpty(code)) {
            Utils.showToast(AppContext.get(), "")
            return
        }

    }

    fun showDialogLogin(activity: Activity) {
        val setHeadDialog = Dialog(activity, R.style.CenterCompatDialogTheme)
        val mDialogView = showBottomDialog(
            R.layout.dialog_open_login,
            activity,
            setHeadDialog,
            R.style.AnimTop,
            Gravity.TOP
        )
        hideSystemUI(mDialogView)
        mDialogView.setOnClickListener { setHeadDialog.dismiss() }

        mDialogView.findViewById<ImageView>(R.id.id_dialog_login_close).setOnClickListener {
            setHeadDialog.dismiss()
        }
        mDialogView.findViewById<ImageView>(R.id.id_dialog_login_img).setOnClickListener {
            Utils.isLogin(true)
            setHeadDialog.dismiss()
        }
        setHeadDialog.show()
    }

    //盖在状态栏上
    fun hideSystemUI(view: View) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        }
    }

    fun showDialogAdShare(
        activity: Activity,
        title: String?,
        icon: String?,
        url: String?,
        sid: String,
        slot_id: String?,
        desc: String
    ) {
        val setHeadDialog = Dialog(activity, R.style.CenterCompatDialogTheme)
        val mDialogView = showBottomDialog(
            R.layout.dialog_ad_share,
            activity,
            setHeadDialog,
            R.style.AnimBottom,
            Gravity.BOTTOM
        )
//        val entity = NewsEntity()
//        entity.type = 3
//        entity.slot_id = slot_id
//        entity.sid = sid.toInt()
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_wx).setOnClickListener {
            //            toShare(activity, SHARE_MEDIA.WEIXIN, title, icon, url, desc)
//            addCoins(sid, slot_id)
//            report(entity)
            setHeadDialog.dismiss()
        }
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_wx_circle)
            .setOnClickListener {
                //            toShare(activity, SHARE_MEDIA.WEIXIN_CIRCLE, title, icon, url, desc)
//            addCoins(sid, slot_id)
//            report(entity)
                setHeadDialog.dismiss()
            }
        mDialogView.setOnClickListener { setHeadDialog.dismiss() }
//        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_qq).setOnClickListener { Utils.showToast(Appli.getContext(), "暂不支持") }
//        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_qzone).setOnClickListener { Utils.showToast(Appli.getContext(), "暂不支持") }
        setHeadDialog.show()
    }

    fun showDialogExit(activity: Activity, result: ExitData) {
        val mExitDialog = Dialog(activity, R.style.CenterCompatDialogTheme)
        val mDialogView =
            showBottomDialog(R.layout.dialog_exit, activity, mExitDialog, 0, Gravity.CENTER)

        mDialogView.findViewById<TextView>(R.id.id_dialog_exit_confirm).setOnClickListener {
            Utils.onExit(activity)
        }
        mDialogView.findViewById<TextView>(R.id.id_dialog_exit_cancel).setOnClickListener {
            mExitDialog.dismiss()
        }

        mDialogView.findViewById<TextView>(R.id.id_dialog_exit_content).text = Html.fromHtml(
            result?.content
                ?: ""
        )
        mDialogView.findViewById<TextView>(R.id.id_dialog_exit_title).text = Html.fromHtml(
            result?.title
                ?: ""
        )
        mExitDialog.show()
    }

    fun showDialogInviteSuc(activity: Activity) {
        val mDialog = Dialog(activity, R.style.CenterCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_invite_code_suc,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )
        mDialogView.findViewById<TextView>(R.id.id_dialog_invite_code_suc_text).text =
            Html.fromHtml(
                "<font color=\"#f7403b\">500金币</font>，已发放到您的+" + AppContext.get()
                    .getString(R.string.app_name) + "账户"
            )
        mDialogView.findViewById<ImageView>(R.id.id_dialog_invite_code_suc_ok).setOnClickListener {
            mDialog.dismiss()
            activity.finish()
        }
        mDialog.show()
    }


    fun showDialogChangeCoinsSuc(activity: Activity, cash: Float?, coins: Int?) {
        val mDialog = Dialog(activity, R.style.CenterCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_change_coins_suc,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )
        mDialogView.setOnClickListener {
            mDialog.dismiss()
        }
        mDialogView.findViewById<TextView>(R.id.id_dialog_change_coins_suc_cash).text =
            cash.toString()
        mDialogView.findViewById<TextView>(R.id.id_dialog_change_coins_text).text =
            coins.toString() + "金币成功兑换"
        mDialog.show()
    }

    fun showDialogUpdateVersion(
        activity: Activity,
        title: String,
        desc: String,
        isCancel: Boolean,
        isShowLoginDialog: Boolean,
        listener: View.OnClickListener,
        listener2: View.OnClickListener,
    ) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(R.layout.dialog_update_viersion, activity, mDialog, 0, Gravity.CENTER)
        val tvcance = mDialogView.findViewById<TextView>(R.id.id_tv_cance)
        if (isCancel) {
            tvcance.visibility = View.VISIBLE
            mDialog?.setCanceledOnTouchOutside(false)
            mDialog?.setCancelable(false)
            mDialog?.setOnDismissListener {
                SettingPreference.setCancelUpdateDate(AppContext.get(), Utils.getNowDate())
                Constant.Switch.isShowUpdateDialoging = false

            }
        } else {
            tvcance.visibility = View.GONE
            mDialog?.setCanceledOnTouchOutside(false)
            mDialog?.setCancelable(false)

        }
        tvcance?.setOnClickListener {
            mDialog?.dismiss()
            listener?.onClick(it)
        }
        mDialogView.findViewById<TextView>(R.id.id_dialog_update_version_title).text =
            "发现新版本${title}"
        mDialogView.findViewById<TextView>(R.id.id_dialog_update_version_desc).text = desc
        mDialogView.findViewById<TextView>(R.id.id_dialog_update_version_btn).setOnClickListener {
            listener2?.onClick(it)
        }


        mDialog.show()
    }


    fun showDialogNewsShare(
        activity: Activity,
        dialogTitle: String,
        url: String,
        title: String,
        icon: String,
        isShowTitle: Int
    ) {
        val mDialog = Dialog(activity, R.style.CenterCompatDialogTheme)
        val mDialogView = showBottomDialog(
            R.layout.dialog_news_share,
            activity,
            mDialog,
            R.style.AnimBottom,
            Gravity.BOTTOM
        )
        if (TextUtils.isEmpty(dialogTitle) || isShowTitle == 0) {
            mDialogView.findViewById<TextView>(R.id.id_dialog_news_share_title).visibility =
                View.GONE
        } else {
            mDialogView.findViewById<TextView>(R.id.id_dialog_news_share_title).visibility =
                View.VISIBLE
            mDialogView.findViewById<TextView>(R.id.id_dialog_news_share_title).text = dialogTitle
        }
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_wechat_layout)
            .setOnClickListener {
                onNewsShareClick(it.id, activity, url, title, icon)
                mDialog.dismiss()
            }
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_wechat_crile_layout)
            .setOnClickListener {
                onNewsShareClick(it.id, activity, url, title, icon)
                mDialog.dismiss()
            }
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_qq_layout)
            .setOnClickListener {
                onNewsShareClick(it.id, activity, url, title, icon)
                mDialog.dismiss()
            }
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_qzone_layout)
            .setOnClickListener {
                onNewsShareClick(it.id, activity, url, title, icon)
                mDialog.dismiss()
            }
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_sms_layout)
            .setOnClickListener {
                onNewsShareClick(it.id, activity, url, title, icon)
                mDialog.dismiss()
            }
        mDialogView.findViewById<LinearLayout>(R.id.id_dialog_news_share_link_layout)
            .setOnClickListener {
                onNewsShareClick(it.id, activity, url, title, icon)
                mDialog.dismiss()
            }
        mDialogView.findViewById<TextView>(R.id.id_dialog_news_share_cancel)
            .setOnClickListener { mDialog.dismiss() }
        mDialogView.setOnClickListener { mDialog.dismiss() }
        mDialog.show()
    }

    private fun onNewsShareClick(
        vId: Int,
        activity: Activity,
        url: String,
        title: String,
        icon: String
    ) {
        if (!Utils.isLogin(true)) {
            return
        }
        var share_media: SHARE_MEDIA? = null
        when (vId) {
            R.id.id_dialog_news_share_link_layout -> {
                val cm = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                cm.text = url
                Utils.showToast(activity, "复制成功")
                MobclickAgent.onEvent(AppContext.get(), UmengCountConfig.NEWS_SHARE_COPY_LINK)
                return
            }
            R.id.id_dialog_news_share_sms_layout -> {
                Utils.sendSMS(title + url)
                MobclickAgent.onEvent(AppContext.get(), UmengCountConfig.NEWS_SHARE_SMS)
                return
            }
            R.id.id_dialog_news_share_wechat_layout -> {
                share_media = SHARE_MEDIA.WEIXIN
                MobclickAgent.onEvent(AppContext.get(), UmengCountConfig.SHARE_WX_FRIENDS)
            }
            R.id.id_dialog_news_share_wechat_crile_layout -> {
                share_media = SHARE_MEDIA.WEIXIN_CIRCLE
                MobclickAgent.onEvent(AppContext.get(), UmengCountConfig.SHARE_WX_CIRCLE)
            }
            R.id.id_dialog_news_share_qq_layout -> {
                share_media = SHARE_MEDIA.QQ
                MobclickAgent.onEvent(AppContext.get(), UmengCountConfig.SHARE_QQ)
            }
            R.id.id_dialog_news_share_qzone_layout -> {
                share_media = SHARE_MEDIA.QZONE
                MobclickAgent.onEvent(AppContext.get(), UmengCountConfig.SHARE_QZONE)
            }
        }
        var image: String
        if (!TextUtils.isEmpty(UserCacheUtils.getMiniProgramImageUrl())) {
            image = UserCacheUtils.getMiniProgramImageUrl()
        } else {
            image = icon
        }

        UmengShareUtils.toShare(
            activity,
            UmengShareUtils.NEWS_SHARE,
            share_media,
            url,
            SettingPreference.getShareInfoDesc() + title,
            "",
            image
        )
    }

    fun showCoins(context: Activity, rewardCoins: Int) {
        val mDialog = Dialog(context, R.style.CenterCompatDialogTheme)
        val mDialogView: View
        val mCoinsText: TextView?
        if (Constant.Param.isLocal) {
            mDialogView =
                showBottomDialog(
                    R.layout.dialog_local_coins,
                    context,
                    mDialog,
                    0,
                    Gravity.CENTER
                )
            mCoinsText = mDialogView.findViewById(R.id.id_dialog_coins_num)
        } else {
            mDialogView =
                showBottomDialog(R.layout.dialog_coins, context, mDialog, 0, Gravity.CENTER)
            mCoinsText = mDialogView.findViewById(R.id.id_dialog_coins_num)
            val tf = Typeface.createFromAsset(context.getAssets(), "progress_num.ttf")
            mCoinsText.typeface = tf
        }
        mDialog?.getWindow()?.setDimAmount(0f)

        mCoinsText?.text = rewardCoins.toString()
        mCoinsText?.postDelayed(Runnable {
            if (mDialog?.isShowing()) {
                mDialog?.dismiss()
            }
        }, 2000)
        mDialog?.show()
    }

    fun showSelectPhotoDialog(context: Activity, onClick: View.OnClickListener) {
        val mDialog = Dialog(context, R.style.CenterCompatDialogTheme)
        val mDialogView = showBottomDialog(
            R.layout.dialog_select_photo,
            context,
            mDialog,
            0,
            Gravity.CENTER
        )

        mDialogView?.findViewById<ImageView>(R.id.id_dialog_select_photo_close)
            .setOnClickListener { mDialog?.dismiss() }
        mDialogView?.findViewById<TextView>(R.id.id_dialog_select_photo_take).setOnClickListener {
            onClick?.onClick(it)
            mDialog?.dismiss()
        }
        mDialogView?.findViewById<TextView>(R.id.id_dialog_select_photo_album).setOnClickListener {
            onClick?.onClick(it)
            mDialog?.dismiss()
        }

        mDialog?.setCancelable(false)
        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.show()

    }

    /**
     * 隐私协议弹窗
     */
    fun showPrivacyProtocol(
        activity: Activity,
        listener: View.OnClickListener?,
        listener2: View.OnClickListener?
    ) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_privacy_protocol_view,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )
        val desc = mDialogView.findViewById<TextView>(R.id.id_dialog_privacy_protocol_desc)

        mDialogView.findViewById<TextView>(R.id.cancel_button).setOnClickListener {
//            val toast = Toast.makeText(AppContext.get(), "您继续同意提示内容方可使用本软件", Toast.LENGTH_LONG)
//            toast?.setGravity(Gravity.BOTTOM, 0, 0)
//            toast?.show()
            mDialog.dismiss()
            listener2?.onClick(it)
            //Utils.onExit(activity)
        }
        val clickUa: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
//                if(TextUtils.isEmpty(Constant.Param.phoneLogin)){
//                    JumpUtils.h5Jump("用户协议", Constant.Param.NuserAgreementUrl)
//                }else{
                JumpUtils.webJump(R.string.UserAgreement.toString(), NetConfig.H5.WEB_URL_USER)
//                }

            }
        }
        val clickPrivat: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                JumpUtils.webJump(
                    R.string.PrivacyAgreement.toString(),
                    NetConfig.H5.WEB_URL_PRIVACY
                )
            }
        }
        val descStr = SpannableStringBuilder("你可阅读《隐私政策》及《用户协议》了解详细信息。如你同意，请点击“同意”开始接收我们的服务。")
        descStr.setSpan(
            clickPrivat, 4, 10,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        descStr.setSpan(
            clickUa, 11, 17,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        descStr.setSpan(
            ForegroundColorSpan(Color.parseColor("#AA60FF")), 4, 10,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        descStr.setSpan(
            ForegroundColorSpan(Color.parseColor("#AA60FF")), 11, 17,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        desc.text = descStr
        desc.setMovementMethod(LinkMovementMethod.getInstance());

        mDialogView.findViewById<TextView>(R.id.privacy_protocol_button).setOnClickListener {
            mDialog.dismiss()
            listener?.onClick(it)
        }
        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.show()
    }

    /**
     * 隐私协议弹窗
     */
    fun showDisagreeDialog(
        activity: Activity,
        listener: View.OnClickListener?,
        listener2: View.OnClickListener?
    ) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_layout_disagree,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )

        mDialogView.findViewById<TextView>(R.id.id_tv_agree).setOnClickListener {
            mDialog.dismiss()
            listener?.onClick(it)
        }

        mDialogView.findViewById<TextView>(R.id.id_tv_disagree).setOnClickListener {
            mDialog.dismiss()
            listener2?.onClick(it)
        }
        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.show()
    }

    fun showCancellationDialog(activity: Activity, listener: View.OnClickListener?) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_layout_cancellation,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )

        mDialogView.findViewById<TextView>(R.id.id_tv_agree).setOnClickListener {
            mDialog.dismiss()
        }

        mDialogView.findViewById<TextView>(R.id.id_tv_disagree).setOnClickListener {
            mDialog.dismiss()
            listener?.onClick(it)
        }
        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.show()
    }

    fun showWinterBox(activity: Activity, listener: View.OnClickListener?) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_layout_winter_box,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )

        mDialogView.findViewById<ImageView>(R.id.id_img_close).setOnClickListener {
            mDialog.dismiss()
        }

        mDialogView.findViewById<TextView>(R.id.id_tv_open_box).setOnClickListener {
            mDialog.dismiss()
            listener?.onClick(it)
        }
        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.show()
    }

    fun showWinterReward(activity: Activity, reward: String?) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_layout_winter_reward,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )
        val tvreward = mDialogView.findViewById<TextView>(R.id.id_tv_reward)
        tvreward?.text = "星币x${reward}"
        mDialogView.findViewById<TextView>(R.id.id_tv_happy_get).setOnClickListener {
            mDialog.dismiss()
        }

        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.show()
    }

    fun showOwnerNoticeactivity(activity: Activity) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_layout_owner,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )
        mDialogView.findViewById<TextView>(R.id.id_tv_i_know).setOnClickListener {
            mDialog.dismiss()
        }

        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.show()
    }

    //支付成功弹窗
    fun showPaySuccessDialog(activity: Activity) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_layout_pay_success,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )
        mDialogView.findViewById<ImageView>(R.id.id_img_close_dialog).setOnClickListener {
            mDialog.dismiss()
        }
        mDialogView.findViewById<TextView>(R.id.id_tv_confirm_btn).setOnClickListener {
            mDialog.dismiss()
        }

        mDialog.setCanceledOnTouchOutside(false)
        mDialog.show()
    }

    //支付页挽留弹窗
    fun showPayExitDialog(activity: Activity, cancelClick: View.OnClickListener) {
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_layout_pay_exit,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )

        mDialogView.findViewById<TextView>(R.id.id_tv_cancel_btn).setOnClickListener {
            mDialog.dismiss()
            cancelClick.onClick(it)
        }

        mDialogView.findViewById<TextView>(R.id.id_tv_continue_btn).setOnClickListener {
            mDialog.dismiss()
        }

        mDialog.setCanceledOnTouchOutside(false)
        mDialog.show()
    }

}