package com.zj365.health.act

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.core.view.isVisible
import com.alibaba.android.arouter.facade.annotation.Route
import com.alipay.sdk.app.PayTask
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadSampleListener
import com.liulishuo.filedownloader.FileDownloader
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.xty.base.act.BaseVmAct
import com.xty.common.BuildConfig
import com.xty.common.LogUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.WxPayEvent
import com.xty.common.getImageUrl
import com.xty.common.setImage
import com.xty.common.util.SpannableUtils
import com.zj365.health.R
import com.zj365.health.adapter.AnswerAdapter
import com.zj365.health.databinding.ActPreventCancerBinding
import com.zj365.health.model.PayResult
import com.zj365.health.vm.PayCancerVm
import com.zj365.health.weight.CancerDialog
import com.xty.network.model.WeixinPayBean
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager
import java.io.File


/**
 * 已填问卷列表
 */
@Route(path = ARouterUrl.PRVENT_CANCER)
class PreventCancertAct : BaseVmAct<PayCancerVm>() {
    val tipDialog by lazy {
        CancerDialog(this, false, "温馨提示", {
            bottomSheetDialog?.show()
        }, {
            bundle.clear()
            RouteManager.goAct(ARouterUrl.ESTIMATE_RECORD, bundle)
        })
    }
    val mAdapter by lazy { AnswerAdapter() }
    val binding by lazy { ActPreventCancerBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root
    override fun initData() {
        super.initData()
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = "AI防癌预警"
        binding.title.mIvBack.setOnClickListener { finish() }


        binding.title.mTvRight.apply {
            visibility = View.VISIBLE
            text = "评估记录"
            setTextColor(resources.getColor(R.color.col_02c))
            setOnClickListener {
                bundle.clear()
                RouteManager.goAct(ARouterUrl.ESTIMATE_RECORD, bundle)
            }
        }

        binding.videoPlayer.apply {
            titleTextView.visibility = View.GONE
            backButton.visibility = View.GONE
            fullscreenButton.visibility = View.GONE
            fullscreenButton.setOnClickListener {
                this.startWindowFullscreen(this@PreventCancertAct,false,true)
            }
            isAutoFullWithSize = false
            isShowFullAnimation = true
        }
        PlayerFactory.setPlayManager(Exo2PlayerManager::class.java)

        //获取文件对象
//        val assets = assets?.open("cancer.mp4")
//        保存到手机的路劲
//        val appDir = File(FileUtils.getCacheFile(this) + "/asset")
//        if (!appDir.exists()) {
//            appDir.mkdir()
//        }
//        val file = File(appDir, "cancer.mp4")
//        val fos = FileOutputStream(file)
//        var bytes = ByteArray(1024)
//        var byteCount: Int = assets!!.read(bytes)
//        while (byteCount !== -1) {
//            fos.write(bytes, 0, byteCount)
//            byteCount = assets.read(bytes)
//        }
//        fos.flush()
//        assets.close()
//        if (file.exists()) {
//            //如果文件存在,则指定要播放的视频
//            videoView.setVideoPath(file.getAbsolutePath());
//        } else {
//            Toast.makeText(this, "要播放的视频文件不存在", Toast.LENGTH_SHORT).show();
//        }
        /**
         * 控制视频的播放 主要通过MediaController控制视频的播放
         */
        //创建MediaController对象
        var mediaController = MediaController(this)

//        videoView.setMediaController(mediaController); //让videoView 和 MediaController相关联
//        videoView.setFocusable(true); //让VideoView获得焦点
//        videoView.seekTo(10) //防止不播放时videoview黑屏
//        videoView.start(); //开始播放视频
//        //给videoView添加完成事件监听器，监听视频是否播放完毕
//        videoView.setOnCompletionListener {
//            Toast.makeText(this, "该视频播放完毕！", Toast.LENGTH_SHORT).show();
//        }
        mViewModel.getPayGood()
        mViewModel.getEstimateRecord()
        val tvPrchase = findViewById<TextView>(R.id.tv_purchase)
        tvPrchase.setOnClickListener {
//            Toast.makeText(this,"功能即将上线，敬请期待",Toast.LENGTH_SHORT).show()
            if (isShowTip) {
                tipDialog.show()
            } else {
                bottomSheetDialog?.show()
            }
        }
    }

    var bottomSheetDialog: BottomSheetDialog? = null
    fun initBottomDialog() {
        price?.let {
            if (bottomSheetDialog == null) {
                bottomSheetDialog = BottomSheetDialog(this,R.style.Theme_ChartDialogManager)
                bottomSheetDialog?.let { dialog ->
                    val view = LayoutInflater.from(this).inflate(R.layout.bottom_cancer, null)
                    dialog.setContentView(view)

                    val tvprice = view.findViewById<TextView>(R.id.tvPrice)
                    tvprice.text = SpannableUtils.setSpanMoney(it)
                    val ivClose = view.findViewById<ImageView>(R.id.close_button)
                    ivClose.setOnClickListener {
                        dialog.dismiss()
                    }
                    val tvZhifubao = view.findViewById<TextView>(R.id.tv_gouxuan_zhifubao)
                    val tvWeixin = view.findViewById<TextView>(R.id.tv_gouxuan_weixin)
                    tvWeixin.isSelected = true
                    val tvDuihuanma = view.findViewById<TextView>(R.id.tv_gouxuan_duihuanma)
                    val llWeixin = view.findViewById<LinearLayout>(R.id.llWeixin)
                    val llZhifu = view.findViewById<LinearLayout>(R.id.llZhifu)
                    val tvZhifu = view.findViewById<TextView>(R.id.tvZhifu)
                    llZhifu.setOnClickListener {
                        tvZhifubao.isSelected = true
                        tvDuihuanma.isSelected = false
                        tvWeixin.isSelected = false
                        tvZhifu.text = "确认支付"
                    }
                    llWeixin.setOnClickListener {
                        tvZhifubao.isSelected = false
                        tvDuihuanma.isSelected = false
                        tvWeixin.isSelected = true
                        tvZhifu.text = "确认支付"
                    }
                    val llDuihuan = view.findViewById<LinearLayout>(R.id.llDuihuan)
                    llDuihuan.setOnClickListener {
                        tvWeixin.isSelected = false
                        tvZhifubao.isSelected = false
                        tvDuihuanma.isSelected = true
                        tvZhifu.text = "去兑换"
                    }

                    tvZhifu.setOnClickListener {
                        //支付
                        if (tvZhifubao.isSelected) {
                            //支付宝
                            mViewModel.payUrl(goodsId, "ALIPAY_APP", "")
                        } else if (tvWeixin.isSelected) {
                            //微信
                            mViewModel.payUrl(goodsId, "WEIXIN_APP", "")
                        } else {
                            //跳转兑换
//                        bundle.clear()
//                        bundle.putString("id",goodsId)
//                        RouteManager.goAct(ARouterUrl.DUIHUAN, bundle)

                            bundle.clear()
                            bundle.putString("id", goodsId)
                            bundle.putString("orderNo", orderNo)
                            RouteManager.goAct(ARouterUrl.DUIHUAN, bundle)
                        }
                        dialog.dismiss()
                    }
                }
            }
        }

    }

    private val SDK_PAY_FLAG = 1
    private val WEIXIN_PAY_FLAG = 2
    var price:Float? = null
    var goodsId = ""
    var orderNo = ""
    var filePath = ""
    var isShowTip = false

    private fun createDownloadTask(position: Int, url: String): BaseDownloadTask? {
        var isDir = false
        when (position) {
            1 -> {

//                path = filePath!!

            }

            2 -> {
//                url = Constant.LIULISHUO_APK_URL
//                tag = com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder(
//                    WeakReference<com.liulishuo.filedownloader.demo.SingleTaskTestActivity>(this),
//                    progressBar2,
//                    null,
//                    speedTv2,
//                    2
//                )
//                path = llsApkDir
//                isDir = true
//                tag.setFilenameTv(filenameTv2)
            }

        }
        return FileDownloader.getImpl().create(url)
            .setPath(filePath!!, false)
            .setCallbackProgressTimes(300)
            .setMinIntervalUpdateSpeed(400)
            .setListener(object : FileDownloadSampleListener() {
                override fun pending(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.pending(task, soFarBytes, totalBytes)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updatePending(
//                        task
//                    )
                }

                override fun progress(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.progress(task, soFarBytes, totalBytes)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateProgress(
//                        soFarBytes, totalBytes,
//                        task.speed
//                    )
                }

                override fun error(task: BaseDownloadTask, e: Throwable) {
                    super.error(task, e)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateError(
//                        e,
//                        task.speed
//                    )
                }

                override fun connected(
                    task: BaseDownloadTask,
                    etag: String,
                    isContinue: Boolean,
                    soFarBytes: Int,
                    totalBytes: Int
                ) {
                    super.connected(task, etag, isContinue, soFarBytes, totalBytes)
//
                }

                override fun paused(task: BaseDownloadTask, soFarBytes: Int, totalBytes: Int) {
                    super.paused(task, soFarBytes, totalBytes)
//
                }

                override fun completed(task: BaseDownloadTask) {
                    super.completed(task)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateCompleted(
//                        task
//                    )

                    //播放视频

                    val file = File(filePath)
                    if (file.exists()) {
                        //如果文件存在,则指定要播放的视频
//                        binding.videoView.setVideoPath(file.getAbsolutePath())
                    } else {
                        Toast.makeText(
                            this@PreventCancertAct,
                            "要播放的视频文件不存在",
                            Toast.LENGTH_SHORT
                        )
                            .show();
                    }
                }

                override fun warn(task: BaseDownloadTask) {
                    super.warn(task)
//                    (task.tag as com.liulishuo.filedownloader.demo.SingleTaskTestActivity.ViewHolder).updateWarn()
                }
            })
    }

    private var downloadId1 = 0
    override fun liveObserver() {
        mViewModel.payGoodsObservable.observe(this) {
            val data = it.data
            if (data == null) {
                binding.llCommodity.isVisible = false
                binding.tvPurchase.isVisible = false
                binding.llSoldOut.isVisible = true
                return@observe
            } else {
                binding.llCommodity.isVisible = true
                binding.tvPurchase.isVisible = true
                binding.llSoldOut.isVisible = false
            }

            data?.let {
                price = data.price!!
//                binding.tvPurchase.text = "￥${data.price} 立即购买"
                binding.tvPurchase.text = "立即购买"
                goodsId = data.id.toString()
                if (!TextUtils.isEmpty(it.advUrl)) {
                    binding.ivBg.setImage(this, getImageUrl(it.advUrl))
                    binding.ivBg.isVisible = true
                } else {
                    binding.ivBg.isVisible = false
                }
//                binding.ivCover.getThumbVideo(this,it.videoUrl)
                val videoUrl = it.videoUrl
                if (!TextUtils.isEmpty(videoUrl)) {
                    binding.videoPlayer.isVisible = true
                    binding.videoPlayer.setUpLazy(it.videoUrl, false, null, null, "")
                } else {
                    binding.videoPlayer.isVisible = false
                }
//                filePath =
//                    FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "video" + File.separator + "report.mp4"
//                var file = File(filePath)
//                if (file.exists()) {
//                    file.delete()
//                }
//                videoUrl?.let {F
//                    downloadId1 = createDownloadTask(1, it)!!.start()
//                }
            }
            initBottomDialog()
        }
        mViewModel.cancerGoodsBeanObservable.observe(this) {
            val data = it.data ?: return@observe
            data?.let {
                for (cancerGoodsBean in it) {
                    val status = cancerGoodsBean.status
                    if (status != 5) {
                        isShowTip = true
                        return@observe
                    }
                }
            }
            initBottomDialog()
        }
        mViewModel.payObservable.observe(this) {
            it.data?.let {
                orderNo = it.orderNo!!
                val orderInfo: String? = it.alipayOrderInfo // 支付宝订单信息
                val wxmodel: WeixinPayBean? = it.wxmodel // 微信订单信息
                if (wxmodel != null) {
                    startWechatPay(wxmodel)
                } else if (orderInfo != null) {
                    LogUtils.i("start Alipay")
                    val orderInfo: String = it.alipayOrderInfo!! // 订单信息
                    val payRunnable = Runnable {
                        val alipay = PayTask(this@PreventCancertAct)
                        val result = alipay.payV2(orderInfo, true)
                        val msg = Message()
                        msg.what = SDK_PAY_FLAG
                        msg.obj = result
                        mHandler.sendMessage(msg)
                    }
                    // 必须异步调用
                    val payThread = Thread(payRunnable)
                    payThread.start()
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getWxPayResult(event: WxPayEvent) {
        val msg = mHandler.obtainMessage()
        msg.what = WEIXIN_PAY_FLAG
        msg.obj = event
        mHandler.sendMessage(msg)
    }

    /**
     * 微信支付
     */
    fun startWechatPay(wxModel: WeixinPayBean) {
        LogUtils.i("startWechatPay")
        val appId = wxModel.appId
        val partnerId = wxModel.partnerid
        val prepayId = wxModel.prepayId
        val packageValue = wxModel.packageName
        val nonceStr = wxModel.noncestr
        val timeStamp = wxModel.timestamp
        val sign = wxModel.sign

        val api = WXAPIFactory.createWXAPI(this, BuildConfig.appid)
        api.registerApp(appId)

        //以下这些都应该从服务器去获取
        val payRequest = PayReq()
        payRequest.appId = appId//你的微信appid
        payRequest.partnerId = partnerId//微信支付分配的商户号
        payRequest.prepayId = prepayId//微信返回的支付交易会话ID
        payRequest.packageValue = packageValue//固定值
        payRequest.nonceStr = nonceStr//随机字符串
        payRequest.timeStamp = timeStamp//时间戳
        payRequest.sign = sign//签名
        //传入一个标识，以便区分回调
        payRequest.extData = "AICancelPay"
        //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        //发起请求，调起微信前去支付
        api.sendReq(payRequest);
    }

    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(this@PreventCancertAct,"支付成功"+payResult,Toast.LENGTH_SHORT).show()
//                        com.alipay.sdk.pay.demo.PayDemoActivity.showAlert(
//                            this@PayDemoActivity,
//                            getString(R.string.pay_success) + payResult
//                        )
                        bundle.clear()
                        bundle.putString("orderNo", orderNo)
                        bundle.putString("orderType", "1")
                        RouteManager.goAct(ARouterUrl.PAY_SUCCESS, bundle)
                    } else {
                        Toast.makeText(
                            this@PreventCancertAct,
                            "支付失败,请联系客服",
                            Toast.LENGTH_SHORT
                        )
                            .show()

                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        com.alipay.sdk.pay.demo.PayDemoActivity.showAlert(
//                            this@PayDemoActivity,
//                            getString(R.string.pay_failed) + payResult
//                        )
                    }
                }

                WEIXIN_PAY_FLAG -> {
                    val event = msg.obj as WxPayEvent
                    when (event.code) {
                        BaseResp.ErrCode.ERR_OK -> {
                            bundle.clear()
                            bundle.putString("orderNo", orderNo)
                            bundle.putString("orderType", "1")
                            RouteManager.goAct(ARouterUrl.PAY_SUCCESS, bundle)
                        }

                        BaseResp.ErrCode.ERR_USER_CANCEL -> {

                        }

                        else -> {
                            Toast.makeText(
                                this@PreventCancertAct,
                                "支付失败,请联系客服",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }

}