package com.ydl.ydlcommon.view.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DialogFragment
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.util.Base64
import android.view.*
import android.widget.LinearLayout
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.umeng.socialize.bean.SHARE_MEDIA
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydlcommon.R
import com.ydl.ydlcommon.actions.share.ShareActionCallBack
import com.ydl.ydlcommon.actions.share.ShareUtils
import com.ydl.ydlcommon.utils.ImageUtil
import com.ydl.ydlcommon.utils.ScreenUtil
import com.yidianling.common.tools.RxImageTool
import kotlinx.android.synthetic.main.platform_dialog_share.*
import java.util.concurrent.Executors


/**
 * @author yuanWai
 * @描述:分享弹窗
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/2/19
 */
class YDLShareDialog : DialogFragment {

    private var mActivity: Activity? = null
    private var shareTitle: String? = null
    private var shareUrl: String? = null
    private var shareContent: String? = null
    private var base64DataStr: String? = null
    private var shareHead: String? = null
    private var mCallback: ICallBack? = null
    private var mShareCallBack: IShareCallBack? = null

    //小程序页面地址
    private var path: String? = null
    //小程序id
    private var minProgramId: String? = null

    private var dp55 = 0
    private var dp7 = 0
    private var llmargin = 0

    @SuppressLint("ValidFragment")
    constructor(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?) : super() {
        this.mActivity = activity
        this.shareTitle = shareTitle
        this.shareUrl = shareUrl
        this.shareContent = shareContent
        this.shareHead = shareHead
    }

    //传递小程序参数
    @SuppressLint("ValidFragment")
    constructor(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?, path: String?, minProgramId: String?) : super() {
        this.mActivity = activity
        this.shareTitle = shareTitle
        this.shareUrl = shareUrl
        this.shareContent = shareContent
        this.shareHead = shareHead
        this.path = path
        this.minProgramId = minProgramId
    }

    constructor() : super() {}

    init {
        dp55 = RxImageTool.dip2px(55f)
        llmargin = (ScreenUtil.screenWidth - RxImageTool.dip2px(260f)) / 3
        dp7 = RxImageTool.dip2px(7.5f)
    }

    companion object {
        var typeStyle: Int = 0
        /**
         * 1.为显示1排(5个) 2.为显示2排（隐藏动态和举报）3.为显示2排（隐藏动态和删除） 4.为显示1排（4个）隐藏动态按钮  5:生成海报按钮、隐藏动态  6：保存海报按钮、隐藏动态  7.为显示1排（4个）隐藏动态按钮
         */
        const val TYPE1 = 1
        const val TYPE2 = 2
        const val TYPE3 = 3
        const val TYPE4 = 4
        const val TYPE5 = 5
        const val TYPE6 = 6
        const val TYPE7 = 7
        /**
         * 点击事件类型 1.动态 2.删除 3.举报 4.返回首页 5:生成海报 6：保存本地 7:分享纯图片
         */
        const val CLICK_DYNAMIC = 1
        const val CLICK_DELETE = 2
        const val CLICK_REPORT = 3
        const val CLICK_BACKHOME = 4
        const val CLICK_POSTER = 5
        const val CLICK_SAVE = 6
        const val CLICK_SHARE_IMAGE = 7

        fun style1(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?): YDLShareDialog {
            typeStyle = TYPE1
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead)
        }

        //支持分享小程序
        fun style1(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?, minProgramPath: String? = "", minProgramId: String? = ""): YDLShareDialog {
            typeStyle = TYPE1
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead, minProgramPath, minProgramId)
        }

        fun style2(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?): YDLShareDialog {
            typeStyle = TYPE2
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead)
        }

        fun style3(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?): YDLShareDialog {
            typeStyle = TYPE3
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead)
        }

        fun style4(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?): YDLShareDialog {
            typeStyle = TYPE4
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead)
        }

        fun style5(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?): YDLShareDialog {
            typeStyle = TYPE5
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead)
        }

        fun style6(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?): YDLShareDialog {
            typeStyle = TYPE6
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead)
        }

        //支持分享小程序
        fun style7(activity: Activity, shareTitle: String?, shareUrl: String?, shareContent: String?, shareHead: String?, minProgramPath: String? = "", minProgramId: String? = ""): YDLShareDialog {
            typeStyle = TYPE7
            return YDLShareDialog(activity, shareTitle, shareUrl, shareContent, shareHead, minProgramPath, minProgramId)
        }
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        //去掉dialog的标题，需要在setContentView()之前
        this.dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        val window = this.dialog.window
        //去掉dialog默认的padding
        window!!.decorView.setPadding(0, 0, 0, 0)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        //设置dialog的位置在底部
        lp.gravity = Gravity.BOTTOM
        //设置dialog的动画
        lp.windowAnimations = R.style.platform_BottomDialogAnimation
        window.attributes = lp
        window.setBackgroundDrawable(ColorDrawable())
        return inflater!!.inflate(R.layout.platform_dialog_share, null)
    }


    /**
     * 设置咨询师海报的图片
     * @param base64DataStr  base64数据
     */
    fun setPosterPicture(base64DataStr: String) {
        this.base64DataStr = base64DataStr
    }

    override fun onResume() {
        super.onResume()
        initView()
        initParams()
    }

    /**
     * 初始化样式
     */
    private fun initParams() {
        when (typeStyle) {
            TYPE1 -> {
                //样式1
                ll_layout2.visibility = View.GONE
            }
            TYPE2 -> {
                //样式2
                ll_dynamic.visibility = View.GONE
                ll_report.visibility = View.GONE
                setStyle()
                val deleteParams = LinearLayout.LayoutParams(dp55, ViewGroup.LayoutParams.WRAP_CONTENT)
                deleteParams.setMargins(dp7, 0, llmargin, 0)
                deleteParams.weight = 0f
                ll_delete.layoutParams = deleteParams
            }
            TYPE3 -> {
                //样式3
                ll_dynamic.visibility = View.GONE
                ll_delete.visibility = View.GONE
                setStyle()
                val reportParams = LinearLayout.LayoutParams(dp55, ViewGroup.LayoutParams.WRAP_CONTENT)
                reportParams.setMargins(dp7, 0, llmargin, 0)
                reportParams.weight = 0f
                ll_report.layoutParams = reportParams
            }
            TYPE4 -> {
                //样式4
                ll_dynamic.visibility = View.GONE
                ll_layout2.visibility = View.GONE
                setStyle()
            }
            TYPE5 -> {
                //样式5
                ll_dynamic.visibility = View.GONE
                ll_poster.visibility = View.VISIBLE
                ll_layout2.visibility = View.GONE
            }
            TYPE6 -> {
                //样式6
                ll_dynamic.visibility = View.GONE
                ll_save.visibility = View.VISIBLE
                ll_layout2.visibility = View.GONE
            }
            TYPE7 -> {
                //样式7
                ll_layout2.visibility = View.GONE
                ll_dynamic.visibility = View.GONE
            }
        }

        showPictureView()
    }


    private fun showPictureView() {
        if (TextUtils.isEmpty(base64DataStr)) {
            return
        }
        cv_pic.visibility = View.VISIBLE

        Executors.newCachedThreadPool().execute {
            var imageByte = Base64.decode(base64DataStr, Base64.DEFAULT)
            mActivity!!.runOnUiThread {
                GlideApp.with(this)
                        .load(imageByte)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(img_pic)
            }
        }

        tv_save_pic.setOnClickListener {
            ImageUtil.savePicture(mActivity, base64DataStr)
        }
    }

    private fun setStyle() {
        val weixinParams = LinearLayout.LayoutParams(dp55, ViewGroup.LayoutParams.WRAP_CONTENT)
        weixinParams.setMargins(dp7, 0, 0, 0)
        weixinParams.weight = 0f
        ll_weixin.layoutParams = weixinParams

        val friendsParams = LinearLayout.LayoutParams(dp55, ViewGroup.LayoutParams.WRAP_CONTENT)
        friendsParams.setMargins(llmargin, 0, 0, 0)
        friendsParams.weight = 0f
        ll_friends.layoutParams = friendsParams

        val qqzoneParams = LinearLayout.LayoutParams(dp55, ViewGroup.LayoutParams.WRAP_CONTENT)
        qqzoneParams.setMargins(llmargin, 0, 0, 0)
        qqzoneParams.weight = 0f
        ll_qqzone.layoutParams = qqzoneParams

        val qqParams = LinearLayout.LayoutParams(dp55, ViewGroup.LayoutParams.WRAP_CONTENT)
        qqParams.setMargins(llmargin, 0, dp7, 0)
        qqParams.weight = 0f
        ll_qq.layoutParams = qqParams
        ll_layout.invalidate()

        val backhomeParams = LinearLayout.LayoutParams(dp55, ViewGroup.LayoutParams.WRAP_CONTENT)
        backhomeParams.setMargins(0, 0, 0, 0)
        backhomeParams.weight = 0f
        ll_backhome.layoutParams = backhomeParams
    }

    fun setCallBack(callback: ICallBack) {
        this.mCallback = callback
    }

    fun setShareCallBack(callBack: IShareCallBack) {
        this.mShareCallBack = callBack
    }

    private fun initView() {
        ll_poster.setOnClickListener {
            //生成海报
            mCallback?.callBack(CLICK_POSTER)
            dismiss()
        }

        ll_save.setOnClickListener {
            //保存本地
            mCallback?.callBack(CLICK_SAVE)
            dismiss()
        }
        ll_dynamic.setOnClickListener {
            //动态
            mCallback?.callBack(CLICK_DYNAMIC)
            dismiss()
        }
        ll_weixin.setOnClickListener {
            //分享海报到微信：直接分享图片到微信
            if (typeStyle == TYPE6) {
                ShareUtils.platform = SHARE_MEDIA.WEIXIN
                mCallback?.callBack(CLICK_SHARE_IMAGE)
            } else {
                //微信
                if (TextUtils.isEmpty(minProgramId)) {
                    share(SHARE_MEDIA.WEIXIN)
                } else {
                    shareMinWeixin()
                }
            }
        }
        ll_friends.setOnClickListener {
            //分享海报到微信朋友圈：直接分享图片到微信朋友圈
            if (typeStyle == TYPE6) {
                ShareUtils.platform = SHARE_MEDIA.WEIXIN_CIRCLE
                mCallback?.callBack(CLICK_SHARE_IMAGE)
            } else {
                //微信朋友圈
                share(SHARE_MEDIA.WEIXIN_CIRCLE)
            }
        }
        ll_qqzone.setOnClickListener {
            //分享海报到qq空间：直接分享图片到qq空间
            if (typeStyle == TYPE6) {
                ShareUtils.platform = SHARE_MEDIA.QZONE
                mCallback?.callBack(CLICK_SHARE_IMAGE)
            } else {
                //qq空间
                share(SHARE_MEDIA.QZONE)
            }
        }
        ll_qq.setOnClickListener {
            //分享海报到qq：直接分享图片到qq
            if (typeStyle == TYPE6) {
                ShareUtils.platform = SHARE_MEDIA.QQ
                mCallback?.callBack(CLICK_SHARE_IMAGE)
            } else {
                //qq
                share(SHARE_MEDIA.QQ)
            }
        }
        if (TYPE2 == typeStyle || TYPE3 == typeStyle) {
            ll_delete.setOnClickListener {
                //删除
                mCallback?.callBack(CLICK_DELETE)
                dismiss()
            }
            ll_report.setOnClickListener {
                //举报
                mCallback?.callBack(CLICK_REPORT)
                dismiss()
            }
            ll_backhome.setOnClickListener {
                //返回首页
                mCallback?.callBack(CLICK_BACKHOME)
                dismiss()
            }
        }
        tv_cancel.setOnClickListener {
            //取消
            dismiss()
        }
        rl_root.setOnClickListener {
            //取消
            dismiss()
        }
    }

    private fun share(platform: SHARE_MEDIA) {
        ShareUtils.shareTo(platform, mActivity!!, shareTitle!!, shareUrl!!, shareContent, shareHead)
        ShareUtils.callBack = object : ShareActionCallBack {
            override fun onShareSuccessed(share_media: SHARE_MEDIA) {
                mShareCallBack?.onShareSuccessed(share_media)
            }

            override fun onShareFailed(share_media: SHARE_MEDIA, throwable: Throwable) {
                mShareCallBack?.onShareFailed(share_media, throwable)
            }
        }
        dismiss()
    }

    /**
     *  分享小程序
     */
    private fun shareMinWeixin() {
        //分享小程序到微信
        ShareUtils.shareSmailWeixin(mActivity!!, shareTitle!!, shareUrl!!, shareContent, shareHead, path, minProgramId, null)
        dismiss()
    }

    interface ICallBack {
        fun callBack(type: Int)
    }

    interface IShareCallBack {
        fun onShareSuccessed(share_media: SHARE_MEDIA)
        fun onShareFailed(share_media: SHARE_MEDIA, throwable: Throwable)
    }
}