2020-08-13

这是我第一个标题

我是谁我在哪你们谁能给我打个电话

 package com.unionpay.merchant.ui.home


import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.*
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.ViewSwitcher
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AdaptScreenUtils
import com.bumptech.glide.Glide
import com.unionpay.common.api.ApiObserver
import com.unionpay.common.base.BaseFragment
import com.unionpay.common.base.BasePagerAdapter
import com.unionpay.common.closeProgress
import com.unionpay.common.data.BaseResult
import com.unionpay.common.data.Message
import com.unionpay.common.data.NewVersionInfo
import com.unionpay.common.net.BaseUrl
import com.unionpay.common.net.BaseUrl.KLB_WEB_BASE_HOST
import com.unionpay.common.showProgress
import com.unionpay.common.toast
import com.unionpay.common.ui.UIHelper
import com.unionpay.common.ui.UIHelper.showXDialog
import com.unionpay.common.utils.CacheUtil
import com.unionpay.common.utils.LocationManager
import com.unionpay.common.utils.MerchConst.*
import com.unionpay.common.utils.MyLog
import com.unionpay.common.utils.XUtils
import com.unionpay.common.vmOf
import com.unionpay.merchant.*
import com.unionpay.merchant.api.MerApiManager
import com.unionpay.merchant.data.AuthInfo
import com.unionpay.merchant.data.FunctionControl
import com.unionpay.merchant.data.LsfFirstTxDtoBean
import com.unionpay.merchant.data.VipInfoResBean
import com.unionpay.merchant.databinding.FragmentMerHomeBinding
import com.unionpay.merchant.manager.MerLoginManager
import com.unionpay.merchant.manager.VipManager.getVipOrderId
import com.unionpay.merchant.mpos.util.AppUtil
import com.unionpay.merchant.net.MerHttpClient
import com.unionpay.merchant.storage.Storage
import com.unionpay.merchant.ui.changxiang.ChangXiangInputActivity
import com.unionpay.merchant.ui.home.adapter.RecvCommonNavigatorAdapter
import com.unionpay.merchant.ui.home.fragment.MerPosFragment
import com.unionpay.merchant.ui.home.msg.MerMsgCenterActivity
import com.unionpay.merchant.ui.home.quotacertify.MerBigQuotaCertifyActivity
import com.unionpay.merchant.ui.main.MerMainActivity
import com.unionpay.merchant.ui.web.MerWebActivity
import com.unionpay.merchant.ui.web.MyVipMerWebActivity
import com.unionpay.merchant.widget.SpacesItemDecoration
import com.unionpay.merchant.yeahka.bean.*
import com.unionpay.merchant.yeahka.http.NetWorkAction
import com.unionpay.merchant.yeahka.http.StreamCallBack
import com.unionpay.merchant.yeahka.utils.StatusChecker
import com.unionpay.merchant.yeahka.utils.Util
import com.yeahka.android.lepos.Device
import com.yeahka.module.leloan.LeloanIml
import com.yeahka.module.leloan.info.GpsInfo
import com.youth.banner.loader.ImageLoader
import io.ditclear.bindingadapterx.ItemClickPresenter
import io.ditclear.bindingadapterx.SingleTypeAdapter
import io.reactivex.Observable
import kotlinx.android.synthetic.main.fragment_mer_home.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator


class MerHomeFragment : BaseFragment(), ItemClickPresenter<FunctionControl.AppFunctionControlBean> {

    var lastFrg = 0
    var flashCompantH5Url = ""    // 云闪付优惠券H5 地址
    var isShoFeiQuan = false
    var isCustTradeControSuccess = false       // 判断条件 俩个现程 确保 当一个现程 执行完的倒结果 设置为 true
    var isCustQuerySuccess = false                  // 判断查询商户信息是否 ok

    override fun onItemClick(v: View, item: FunctionControl.AppFunctionControlBean) {
        if (Storage.getStatus()) {
            when (item.functionType) {
//                resources.getString(R.string.terminal_manage) -> MerTerminalListActivity.start(activity)
//                resources.getString(R.string.settle_info) -> MerSettleInfoActivity.start(activity)
//                resources.getString(R.string.quota_rate) -> MerQuotaRateActivity.start(activity)
//                resources.getString(R.string.big_quota_certify) -> MerBigQuotaCertifyActivity.start(activity)
//                resources.getString(R.string.certify_up_amount) -> CertifyUpQuotaActivity.start(activity)
//                功能控制类型: ZDFQ-账单分期,XFGH-消费规划,FXZC-分享注册,CTKRZ-磁条卡认证,SHRW-商户入网,YQHB-邀请伙伴,HBCX-伙伴管理,YJFX-业绩分析,ZDGL-终端管理,SHFX-商户分享,JYTJ-交易统计,SHCX-商户查询
                "CXJY" -> dealtCXXF()
                "CTKRZ" -> MerBigQuotaCertifyActivity.start(activity)
                "SYJ" -> LeloanIml.startLeloanActivity(activity, Util.getAppSetting(XUtils.getApplicationContext()), null)
                "VIP" -> {
                    checkVip(item)
                }
                else -> if (!item.functionUrl.isNullOrEmpty()) MyVipMerWebActivity.start(context, item.functionUrl) else toast("暂未开放")
            }
        } else {
            val merMainActivity = activity as MerMainActivity
            merMainActivity.showCerityfyDialog()
        }
    }

    fun gotoVip(item: FunctionControl.AppFunctionControlBean){
        val bean = CacheUtil.getInstance(XUtils.getApplicationContext()).get(VipInfoResBean::class.java)
        if (bean?.bindPos != null) {
            if (bean.bindPos!!) {
                val info = CacheUtil.getInstance(XUtils.getApplicationContext()).get(AuthInfo::class.java)
                if (info?.custInfoBean != null && info.custInfoBean!!.isBigPos()) {        //电签商户
                    if (!bean.buyVipFlag && bean.bindWay && !bean.posActive) run {
                        val depositTransactionInfo = CacheUtil.getInstance(activity).get(DepositTransactionInfo::class.java)
                        depositTransactionInfo?.let {
                            UIHelper.showXDialog(activity).setTitle("温馨提示")
                                    .setContent("请打开机具先进行一笔≥${it.rechargeAmount}元刷卡交易")
                                    .isTip
                        }
                    } else {
                        /*MerWebActivity.start(context, item.functionUrl)*/
                        MyVipMerWebActivity.start(context, item.functionUrl)
                    }
                } else if (bean.isDeposit() && !bean.buyVipFlag && !bean.bindWay && !bean.posActive) run {
                    UIHelper.showXDialog(activity).setTitle("温馨提示")
                            .setContent(activity?.getString(R.string.quick_pay_forbid_hint))
                            .isTip
                } else {
                    if (!bean.buyVipFlag && bean.bindWay) {          //押金版
                        bean.orderInfoResBean?.rechargeAmount?.let {
                            App.getOrderInfoModel().amount = (it.toDouble() * 100).toInt()
                            getVipOrderId(activity!!, bean.orderInfoResBean?.vipCode, bean.orderInfoResBean?.valiteDate)
                        }
                    } else {
                        /*MerWebActivity.start(context, item.functionUrl)*/
                        MyVipMerWebActivity.start(context, item.functionUrl)
                    }
                }
            } else activity?.resources?.getString(R.string.no_bind_mach_tip)?.let { toast(it) }
        } else MerLoginManager.mVipErrorMsg?.let { toast(it) }

    }

    private fun checkVip(item: FunctionControl.AppFunctionControlBean) {

       val dispose =  Observable.zip(MerApiManager.api.getVipInfo() ,
               MerApiManager.api.queryIfFirstTransaction(),
               object : io.reactivex.functions.BiFunction<BaseResult<VipInfoResBean>,BaseResult<LsfFirstTxDtoBean>,  FunctionControl.AppFunctionControlBean> {
            override fun apply(t1: BaseResult<VipInfoResBean>, t2: BaseResult<LsfFirstTxDtoBean>): FunctionControl.AppFunctionControlBean {
                ApiObserver.getData(t1) // 有异常抛出去
                ApiObserver.getData(t2) // 有异常抛出去
                CacheUtil.getInstance(XUtils.getApplicationContext()).save(t1.data)
                CacheUtil.getInstance(AppUtil.getAppInstance()).save(Util.lsfFirstTxDtoBean2DepositTInfo(t2.data))
                return item
            }

        }).compose(MerHttpClient.switcher()).subscribe({

           gotoVip(it)

        },{
            context.handleThrowable(it)
        })
    }



    /**
     * v 5.2 添加畅享交易方法
     */
    private fun dealtCXXF() {
        // 1 注册商户还是 普通商户  弹框进行实名认证
        if(!Storage.isAuthUser()){
            ( activity as MerMainActivity).showCerityfyDialog()

        }else{//认证商户
            val bean = CacheUtil.getInstance(XUtils.getApplicationContext()).get(VipInfoResBean::class.java)
            val depositTransactionInfo = CacheUtil.getInstance(activity).get(DepositTransactionInfo::class.java)
                // 认证商户  已绑定机具 有首笔交易
            if(depositTransactionInfo != null && depositTransactionInfo.isFirstDeal && bean?.bindPos != null && bean.bindPos!!){ //首笔标识
                depositTransactionInfo?.let {
                    UIHelper.showXDialog(activity).setTitle("温馨提示")
                            .setContent("请先选择刷卡进行充值交易")
                            .setConfirmButtonText("好的")
                            .isTip
            }
            }else { //进入到畅享交易
                val intent = Intent()
                intent.setClass(activity,ChangXiangInputActivity::class.java)
                startActivity(intent)
            }

        }
    }

    private lateinit var mBinding: FragmentMerHomeBinding
    private lateinit var viewModel: MerHomeFragmentVM
    private lateinit var context: MerMainActivity

    companion object {
        fun newInstance(): MerHomeFragment {
            val fragment = MerHomeFragment()
            fragment.arguments = Bundle()
                    .also {

                    }
            return fragment
        }
    }

    val mAdapter by lazy {
        SingleTypeAdapter<FunctionControl.AppFunctionControlBean>(activity!!, R.layout.item_home_function, viewModel.dataSource)
                .apply {
                    itemPresenter = this@MerHomeFragment
                }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = inflate<FragmentMerHomeBinding>(
                inflater,
                R.layout.fragment_mer_home,
                container)
                .also {
                    viewModel = vmOf(MerHomeFragmentVM::class.java)
                    it.data = viewModel
                    it.ui = this
                }

        viewModel.initData()
        initView()
        initObserver()
        onRefresh()
        queryFeiQuanBanner()
        return mBinding.root
    }


    private fun queryFeiQuanBanner() {
       val dispose = MerApiManager.api.queryCooperationActivities()
                .map { ApiObserver.getData(it) }
                .compose(MerHttpClient.switcher())
                .subscribe({
                  it?.let {
                         //云闪付活动卷
                      if(("Y").equals (it.status) && !it.pictureUrl.isNullOrEmpty()){
                             viewModel.isShowFlashCoupon.set(true)
                          //加载图片
                          flashCompantH5Url = it.skipUrl
                          //add
                          mBinding.drView.loadImageView(activity!!,it.pictureUrl)
                      }
                       //webView 加载
                      if(it.showBanner == 1 && !it.bannerPath.isNullOrEmpty()){
                          webView.loadUrl(it.bannerPath)
                          isShoFeiQuan = true
                          //控制显示与隐藏

                          val status = CacheUtil.getInstance(activity).get(MerchantDataBean::class.java)?.merchant_status
                          if(STATUS_CREDIT_PASS.equals(status)){
                              viewModel.isShowFeiQuanBanner.set(true)
                          }

                      }

                  }

                }, {
                   // toast("error message " +it.message)
                })
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        LeloanIml.getDeviceInfo(activity, Util.getAppSetting(XUtils.getApplicationContext()), GpsInfo().setLongitude(LocationManager.getXString())
                .setLatitude(LocationManager.getYString()))
    }

    fun loadMerchantDate() {
        var cacheInstance = CacheUtil.getInstance(activity)
        isCustQuerySuccess = false
        MerApiManager.api.queryCustAllInfo()
                .map { ApiObserver.getData(it) }
                .compose(MerHttpClient.switcher())
                .subscribe({
                     //6.6 add 检查有效期是否ok
                    checkValid(it)
                    cacheInstance.save(Util.AuthInfo2MerchantDataBean(it))
                    cacheInstance.save(it)
                    refreshAuthRl(cacheInstance.get(MerchantDataBean::class.java)?.merchant_status)
                    isCustQuerySuccess = true
                    initViewPager()
                }, {
                })
    }

    private fun checkValid(it: AuthInfo?) {
        it?.queryIDCardExpiredFlagRes?.let {
            if(it.beOverdue()){ // 过期
                UIHelper.showXDialog(activity).setTitle("温馨提示")
                        .setContent(if(!it.msg.isNullOrEmpty())  it.msg else "您的身份证已过期,请立即更新\n" +
                                "身份证信息")
                        .setConfirmButtonText("更新")
                        .setListener {
                            MerWebActivity.Companion.start(activity, BaseUrl.KLB_WEB_BASE_HOST + "cust-app/merchants")
                        }
                        .isTip
            }

            //即将过期去掉
           /* if(it.aboutToexpire()){ // 即将过期
                UIHelper.showXDialog(activity).setTitle("温馨提示")
                        .setContent(if(!it.msg.isNullOrEmpty())  it.msg else "您的身份证即将过期,为避免影响使用,请及时更新身份证信息")
                        .setConfirmButtonText("更新")
                        .setCancelButtonText("取消")
                        .setListener {
                            MerWebActivity.Companion.start(activity, BaseUrl.KLB_WEB_BASE_HOST + "cust-app/merchants")
                        }

            }*/

            if(it.aboutChecking()){ // 审核中
                UIHelper.showXDialog(activity).setTitle("温馨提示")
                        .setContent(if(!it.msg.isNullOrEmpty())  it.msg else "正在审核中,请耐心等待,若审核失败则会再次提醒您提交资料")
                        .setConfirmButtonText("确定")
                        .isTip
            }

        }
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        context = activity as MerMainActivity
    }

    fun isViewModelInitialzed() = ::viewModel.isInitialized

    override fun onRefresh() {
        super.onRefresh()
        if (isViewModelInitialzed()) {
            viewModel.queryBanner()
            viewModel.functionControl()
            MerLoginManager.loadVipInfo()
//            V1.1.0加入商户信息更新 避免多端登录更新不及时
            loadMerchantDate()
//            V1.1.0加入首笔交易刷新
            MerLoginManager.loadFirstTransactionInfo()
        }

    }

    override fun onStart() {
        mBinding.banner.startAutoPlay()
        super.onStart()
    }

    override fun onResume() {
        // 检验下是否有
        App.boundQpayBankCardList?.forEach {
            if(!it.isMyPayCard){ // 非本人卡 解除
                unbind(it)
            }
        }
        startFlipping()
        // 人工审核中 用于刷新
        refreshAuthRl(CacheUtil.getInstance(activity).get(MerchantDataBean::class.java)?.merchant_status)
        super.onResume()
    }

    /**
     * 解除非本人银行卡
     */
     fun unbind ( boundQpayBankCardItem : ReqBoundQpayBankCardBean.BoundQpayBankCardItem) {

         NetWorkAction.unBindQpayBankCard(Device.get(), boundQpayBankCardItem.getModel(), boundQpayBankCardItem.getAuth_mode(), boundQpayBankCardItem.getBind_id(), object : StreamCallBack<BaseBean?>() {

             override fun onSucceed(t: BaseBean?) {
                      // 过滤掉,会产生一个新的集合
                val list =  App.boundQpayBankCardList?.filter{
                     boundQpayBankCardItem.bind_id != it.bind_id
                 }
                 // 重新赋值
                 App.boundQpayBankCardList = list
             }

             override fun onFailure(errorCode: Int, errMsg: String) {

             }
         })

    }


    fun refreshAuthRl(status: String?) {
        val authInfo = CacheUtil.getInstance(AppUtil.getAppInstance())[AuthInfo::class.java]
        when (status) {
            STATUS_NOT_SUMMIT -> {
                if (StatusChecker(activity).isBaseInfoComplete && StatusChecker(activity).isIdInfoComplete) {
                    mBinding.tvStatus.setText("您还未完成银行认证")
                } else {
                    mBinding.tvStatus.setText("您还未完成身份认证")
                }
                mBinding.tvGoToAuth.setText("立即去认证")

                //新增v6.3 处于审核状态
                if(("CHECKING").equals(authInfo?.custInfoBean?.status)){
                    mBinding.tvStatus.setText("信息人工审核中...")
                    mBinding.tvGoToAuth.setText("请等待")
                }
                //审核失败
                if("FAILED".equals(authInfo?.custInfoBean?.status)){
                    mBinding.tvStatus.setText("信息审核失败,请重新提交")
                    mBinding.tvGoToAuth.setText("重新提交")
                }


            }
            STATUS_SK_PASS -> {
                mBinding.tvStatus.setText("您还未完成人脸识别")
                mBinding.tvGoToAuth.setText("立即去认证")

                //新增v6.3 处于审核状态
                if(("CHECKING").equals(authInfo?.custInfoBean?.status)){
                    mBinding.tvStatus.setText("信息人工审核中...")
                    mBinding.tvGoToAuth.setText("请等待")
                }
                //审核失败
                if("FAILED".equals(authInfo?.custInfoBean?.status)){
                    mBinding.tvStatus.setText("信息审核失败,请重新提交")
                    mBinding.tvGoToAuth.setText("重新提交")
                }

            }
            STATUS_CREDIT_PASS -> {

                if( isShoFeiQuan){ //控制显示与隐藏
                    viewModel.isShowFeiQuanBanner.set(true)
                }
                mBinding.tvStatus.setText("恭喜您!已完成所有注册流程")
                mBinding.tvGoToAuth.setText("点击查看如何交易")
            }
        }
    }

    override fun onStop() {
        mBinding.banner.stopAutoPlay()
        stopFlipping();
        super.onStop()
    }

    override fun onDestroy() {
        mBinding.banner.releaseBanner()
        super.onDestroy()
    }

    private fun initObserver() {
        viewModel.navigation.observe(this, Observer {
            when (it.tag) {
                MerHomeFragmentVM.WAIT -> context.showProgress()
                MerHomeFragmentVM.ERROR -> context.handleThrowable(it.obj as Throwable)
                MerHomeFragmentVM.NOTICE -> {
                    context.closeProgress()
                    val notice = it.obj as Message
                    context.showNotificationDialog().setContent(notice.content.toString())
                }

                MerHomeFragmentVM.UPDATE -> {
                    val versionInfo = it.obj as NewVersionInfo
                    context.closeProgress()
                    val versionDiaolg = context.showNewVersionDialog()
                    versionDiaolg.setContent(versionInfo.content)
                            .isForced(versionInfo.isForced())
                            .setOnDownloadClickListener {
                                XUtils.downloadSelf(activity, versionInfo.upUrl)
//                                XUtils.goToMarket(context)
                            }
                    versionDiaolg.setOnCancelClickListener {
                        context.showProgress()
                        viewModel.buildEncryptChannel()
                    }

                }
                MerHomeFragmentVM.BANNER -> if (!it.obj.toString().isNullOrEmpty()) MerWebActivity.start(activity!!, it.obj.toString())
                MerHomeFragmentVM.BUILDCHANNELERROR -> {
                    context.closeProgress()
                    MerMainActivity.isEnctyChannelNormal = false
                    val errorMessage = it.obj.toString()
                    showXDialog(activity).setTitle("提示")
                            .setContent("交易通道构建失败,是否重试?\n" + errorMessage)
                            .setConfirmButtonText("重试")
                            .setCancelButtonText("放弃")
                            .setListener({
                                context.showProgress()
                                viewModel.buildEncryptChannel()
                            }, {
                                activity!!.finish()

                            })
                }
                MerHomeFragmentVM.BUILDCHANNELSUCC -> {
                    context.closeProgress()
                    MerMainActivity.isEnctyChannelNormal = true
                    App.initPayConfigSelectBean(it.obj as QueryAppConfigResultBean)
                    viewModel.loadNotices()
                }
                MerHomeFragmentVM.FUNCTION -> {
                    initFunctionList()
                }
            }
        })

        viewModel.message.observe(this, Observer {
            it?.let {
                mBinding.tvNoticeMsg.visibility = View.VISIBLE
                setTextSwitcherData(it)
            }
        })
    }

    fun checkHideKeyBroad() {
        if (mBinding.viewPager.currentItem != lastFrg) {
            var posfrg: MerPosFragment? = null
            if (viewModel.getRecvType().size == 2) {
                if (lastFrg == 0) {
                    posfrg = viewModel.unionFrg
                } else if (lastFrg == 1) {
                    posfrg = viewModel.quickFrg
                }
            } else {
                if (lastFrg == 0) {
                    posfrg = viewModel.swipeFrg
                } else if (lastFrg == 1) {
                    posfrg = viewModel.unionFrg
                } else if (lastFrg == 2) {
                    posfrg = viewModel.quickFrg
                }
            }
            if (posfrg != null && posfrg.isKeyBoardInit() && posfrg.mSecurityKeyBoardUtil.isVisibility) {
                posfrg.mSecurityKeyBoardUtil.hide()
            }
            lastFrg = mBinding.viewPager.currentItem
        }
    }

    //初始化功能列表
    private fun initFunctionList() {
        if (mBinding.recyclerView.adapter == null) {
            var spanCount = 4
            MyLog.d("sam", "dataSource size :  " + viewModel.dataSource.size)
            if (!viewModel.dataSource.isNullOrEmpty() && viewModel.dataSource.size > 0 && viewModel.dataSource.size < 4) {
                MyLog.d("sam", "spanCount111 ")
                spanCount = viewModel.dataSource.size
            }
            MyLog.d("sam", "spanCount " + spanCount)
            mBinding.recyclerView.adapter =/* FuncAdapter(MerHomeFragmentVM().getFunctions(), viewModel)*/mAdapter
            mBinding.recyclerView.layoutManager = GridLayoutManager(activity, spanCount)
            mBinding.recyclerView.addItemDecoration(SpacesItemDecoration(AdaptScreenUtils.pt2Px(10f)))
        }
    }


    fun  initViewPager() {
             //只要俩个 有一个 不成功 返回
        if(!isCustQuerySuccess || !isCustTradeControSuccess){
            return
        }

        if (mBinding.viewPager.adapter != null) {
            val info = CacheUtil.getInstance(XUtils.getApplicationContext()).get(AuthInfo::class.java)
            val isBigPos = info != null && info.custInfoBean != null && info.custInfoBean!!.isBigPos()
             // 避免重复创建
            if(isBigPos == viewModel.isElectricsign.get()){ //俩个一致 return
                return
            }
          /*  if (isBigPos && mBinding.viewPager.adapter!!.count == TAB_PAY_TYPE_NORMAL_TEXT.size) return
            if (!isBigPos && mBinding.viewPager.adapter!!.count == TAB_PAY_TYPE_NOT_BIG_TEXT.size) return*/
        }
        MyLog.d("sam", "dsfsdfsf")
        mBinding.viewPager.adapter = activity?.supportFragmentManager?.let {
             // 添加几个 fragement
            BasePagerAdapter(viewModel.getRecv(), it)
        }
        mBinding.viewPager.offscreenPageLimit = 0
        val commonNavigator = CommonNavigator(activity)
        // 添加几个 标题
        commonNavigator.adapter = RecvCommonNavigatorAdapter(viewModel.getRecvType(), mBinding.viewPager)
        mBinding.magicIndicator.navigator = commonNavigator
        ViewPagerHelper.bind(mBinding.magicIndicator, mBinding.viewPager)
        mBinding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
                if (state == 2) {
                    checkHideKeyBroad()
                }
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
            }
        })
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        mBinding.banner.setImageLoader(BannerImageLoader())
        mBinding.tvNoticeMsg.setOnClickListener { ActivityUtils.startActivity(MerMsgCenterActivity::class.java) }
        setTextSwitcher()
//        mBinding.tvNoticeMsg.setOnTouchListener { _, event ->
//            // et.getCompoundDrawables()得到一个长度为4的数组,分别表示左右上下四张图片
//            val drawable = mBinding.tvNoticeMsg.getCompoundDrawables()
//
//            //如果不是按下事件,不再处理
//            if (drawable[2] == null) {
//                false
//            } else if (event.action == MotionEvent.ACTION_UP) {
//                if (event.x > (mBinding.tvNoticeMsg.width
//                                - mBinding.tvNoticeMsg.paddingRight
//                                - drawable[2].intrinsicWidth)) {
//
//                    if (View.VISIBLE == mBinding.tvNoticeMsg.visibility) {
//                        mBinding.tvNoticeMsg.visibility = View.GONE
//                    }
//                }
//            }
//            true
//        }

        // 查询功能

        queryCustTradeFunction()

    }

    private fun queryCustTradeFunction() {
        isCustTradeControSuccess = false
        MerApiManager.api.queryCustTradeFunction()
                .map { ApiObserver.getData(it) }
                .compose(MerHttpClient.switcher())
                .subscribe({
                    // 存入到
                    App.listCustTradeControlBean = it
                    // 存储改值
                    isCustTradeControSuccess = true
                    initViewPager()
                }, {
                })

    }

    var index = 0//textview上下滚动下标
    val handler = Handler()
    var isFlipping = false // 是否启用预警信息轮播
    var mWarningTextList = ArrayList<String?>()

    fun setTextSwitcher() {
        mBinding.textSwitcher.setInAnimation(AnimationUtils.loadAnimation(activity, R.anim.text_switcher_in_buttom));
        mBinding.textSwitcher.setOutAnimation(AnimationUtils.loadAnimation(activity, R.anim.text_switcher_in_top));
        mBinding.textSwitcher.setFactory(object : ViewSwitcher.ViewFactory {
            override fun makeView(): View {
                var textView = TextView(activity)
                textView.setSingleLine()
                textView.textSize = 13F
                textView.setTextColor(Color.BLACK)
                textView.setEllipsize(TextUtils.TruncateAt.END)
                textView.setSingleLine()
                textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                textView.setGravity(Gravity.CENTER_VERTICAL)
                var params = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                params.gravity = Gravity.CENTER;
                textView.setLayoutParams(params);
                return textView;
            }

        })
    }

    val runnable = Runnable()
    {
        if (isFlipping) {
            index++
            mBinding.textSwitcher.setText(mWarningTextList.get(index % mWarningTextList.size))
            if (index == mWarningTextList.size) {
                index = 0
            }
            startFlipping()
        }
    }


    //开启信息轮播
    fun startFlipping() {
        if (mWarningTextList.size > 1) {
            handler.removeCallbacks(runnable);
            isFlipping = true;
            handler.postDelayed(runnable, 3000);
        }
    }

    //关闭信息轮播
    fun stopFlipping() {
        if (mWarningTextList.size > 1) {
            isFlipping = false;
            handler.removeCallbacks(runnable);
        }
    }

    //设置数据
    fun setTextSwitcherData(list: ArrayList<String?>) {
        mWarningTextList = list
        if (mWarningTextList.size == 1) {
            mBinding.textSwitcher.setText(mWarningTextList.get(0));
            index = 0;
        }
        if (mWarningTextList.size > 1) {
            handler.postDelayed({
                mBinding.textSwitcher.setText(mWarningTextList.get(0))
                index = 0
            }, 1000)


            mBinding.textSwitcher.setInAnimation(AnimationUtils.loadAnimation(activity, R.anim.text_switcher_in_buttom));
            mBinding.textSwitcher.setOutAnimation(AnimationUtils.loadAnimation(activity, R.anim.text_switcher_in_top));
            startFlipping()
        }

        webView.setOnTouchListener { v, event ->
            if (event.action === MotionEvent.ACTION_DOWN) {
                val parent: ViewParent? = v.parent
                if (parent != null) {
                    parent.requestDisallowInterceptTouchEvent(true)
                }
                return@setOnTouchListener true
            } else if (event.action === MotionEvent.ACTION_UP) {
                gotoShangYiJie()
            }
            false
        }
    }


    private inner class BannerImageLoader : ImageLoader() {

        override fun displayImage(context: Context, path: Any, imageView: ImageView) {
            val value = path as String
//            ImageManager                //sam 有问题,待研究
//                    .load(value)
//                    .transform(RoundedCornersTransformation(ConvertUtils.dp2px(6f), 0))
//                    .into(imageView)
            Glide.with(context).load(value).into(imageView)
        }
    }

    /**
     * 云闪付优惠卷  6.2.1
     */
    fun gotoFlashCoupon() {

        if(flashCompantH5Url.isNullOrEmpty()){
            toast("跳转失败,从服务器获取路径为空...")

        }else{
            MerWebActivity.start(activity, flashCompantH5Url)
        }

    }

    /**
     * 隐藏 6.2.1
     */
    fun hideFlashCoupon() {
        viewModel.isShowFlashCoupon.set(false)
    }


    fun gotoShangYiJie() {
        LeloanIml.startLeloanActivity(activity, Util.getAppSetting(XUtils.getApplicationContext()), null)
    }

    fun creditApply() {
        MerWebActivity.start(activity, KLB_WEB_BASE_HOST + "cust-app/card")
    }

    fun loanMarket() {
        MerWebActivity.start(activity, KLB_WEB_BASE_HOST + "cust-app/loan")
    }

    fun noticeList() {
        MerMsgCenterActivity.startActivity(activity)
    }

    fun authClick() {
        val status = CacheUtil.getInstance(activity).get(MerchantDataBean::class.java)?.merchant_status
        if (status.equals(STATUS_CREDIT_PASS)) {
            MerWebActivity.start(activity, KLB_WEB_BASE_HOST + "cust-app/video-index")
        } else {
            val authInfo = CacheUtil.getInstance(AppUtil.getAppInstance())[AuthInfo::class.java]
             // v6.3 1 进行拦截 如果处于审核时 弹框提示 如果 用户点击了 2 传一个desc 过去
            if("CHECKING".equals(authInfo?.custInfoBean?.status)){
               // toast("人工审核中,请等待")
                (activity as MerMainActivity).showCerityfyDialog()
            }else if("FAILED".equals(authInfo?.custInfoBean?.status)) {
                StatusChecker(activity).goCompleteInfo(status, authInfo?.custInfoBean?.desc)
            }else { //传空
                StatusChecker(activity).goCompleteInfo(status, "")
            }
        }
    }
    /*
    V1.1.0
    绑定机具成功
    更新功能列表 跟 入网信息
     */
    fun bindPOSSuc(){
        if (isViewModelInitialzed()) {
            viewModel.queryBanner()
            viewModel.functionControl()
        }
//      V1.1.0加入商户信息更新 避免多端登录更新不及时
        queryCustTradeFunction()  //查询一遍
        loadMerchantDate()
        // 调用接口看看是否显示
    }
}


1596073997(1).jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,922评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,591评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,546评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,467评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,553评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,580评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,588评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,334评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,780评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,092评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,270评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,925评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,573评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,194评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,437评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,154评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,127评论 2 352