package com.zxhl.main.page.fragment

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.umeng.socialize.UMShareAPI
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.base.BaseFragment
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.AppInEntity
import com.zxhl.cms.net.model.box.DepotEntity
import com.zxhl.cms.net.model.box.NoticeEntity
import com.zxhl.cms.utils.*
import com.zxhl.main.R
import com.zxhl.main.page.`interface`.PopupWidowCloseCallBack
import com.zxhl.main.page.activity.OrderDetailActivity
import com.zxhl.main.page.adapter.PickUpAdapter
import com.zxhl.main.page.contract.WareHouseContract
import com.zxhl.main.page.presenter.WareHousePresenter
import com.zxhl.main.page.view.RecycleDialog
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_warehouse_layout.*
import kotlinx.android.synthetic.main.layout_empty.*
//待提货
class TobePickUpFragment: BaseFragment(), WareHouseContract.View,
    OnRecycleItemClickListener<Boolean>, AdCallback<String>, PopupWidowCloseCallBack,
    WeChatLoginSuccessCallBall {
    private var mPresenter: WareHousePresenter? = null
    private var mAdapter: PickUpAdapter? = null
    private var status: Int? = 0
    private var type: Int? = 0
    private var chooseStatus: Int = 0
    private var mUpdateDataObservable: Observable<Int>? = null
    private var depotlist: MutableList<DepotEntity>? = ArrayList()
    private var wechatutil: WeChatUtils? = null
    private var recoveType: String = ""
    override fun layoutID(): Int {
        return R.layout.fragment_warehouse_layout
    }

    override fun init(view: View?) {
        wechatutil = WeChatUtils(mActivity, this)
        id_ll_tihuo_bottom?.visibility = View.VISIBLE
         id_rl_xianshi?.visibility = View.VISIBLE
        id_tv_fahuo?.visibility = View.VISIBLE

        id_img_xianshi?.setOnClickListener {
            id_rl_xianshi?.visibility = View.GONE
        }
        id_tv_warehouse_pick_up_goods?.setOnClickListener {
            id_tv_fahuo?.visibility = View.VISIBLE
            id_tv_warehouse_pick_up_goods?.setBackgroundResource(R.drawable.shape_ff2e31_r12_bg)
            id_tv_warehouse_pick_up_goods.setTextColor(getResources().getColor(R.color.color_ff2e31))
            id_tv_warehouse_card?.setBackgroundResource(R.drawable.shape_ffffff_r12_bg)
            id_tv_warehouse_card.setTextColor(getResources().getColor(R.color.color_666666))
            type = 0
            mChoosList?.clear()
            mAdapter?.setCancelAllSelect(true)
            mAdapter?.setTihuo(type)
            mPresenter?.getDepot(status, type, true)
        }
        id_tv_warehouse_card?.setOnClickListener {
            id_tv_fahuo?.visibility = View.GONE
            id_tv_warehouse_pick_up_goods?.setBackgroundResource(R.drawable.shape_ffffff_r12_bg)
            id_tv_warehouse_pick_up_goods.setTextColor(getResources().getColor(R.color.color_666666))
            id_tv_warehouse_card?.setBackgroundResource(R.drawable.shape_ff2e31_r12_bg)
            id_tv_warehouse_card.setTextColor(getResources().getColor(R.color.color_ff2e31))
            type = 1
            mChoosList?.clear()
            mAdapter?.setCancelAllSelect(true)
            mAdapter?.setTihuo(type)
            mPresenter?.getDepot(status, type, true)
        }
        id_tv_huishou?.setOnClickListener {
            if (mChoosList.isEmpty()) {
                Utils.showToast(mActivity, "请选择要回收的物品")
            } else {

                val sb = StringBuilder()
                for (dataBean in mChoosList) {
                    if (sb.length > 0) {
                        sb.append(",")
                    }
                    sb.append(dataBean)
                }
                var spentList: MutableList<Double> = ArrayList()
                var recovertList: MutableList<Double> = ArrayList()
                var spentprice: Double = 0.0
                var recoverprice: Double = 0.0
                depotlist?.clear()
                if (mAdapter?.list?.size!! > 0) {
                    for (i in mAdapter?.list!!) {
                        for (j in mChoosList) {
                            if (j == i.id) {
                                depotlist?.add(i)
                                spentList.add(i.amountSpent?.toDoubleOrNull()!!)
                                recovertList.add(i.recoverPriceStr?.toDoubleOrNull()!!)
                                Log.e(
                                    "MXL",
                                    "选择的数量：" + mChoosList.size + i.amountSpent?.toDoubleOrNull()
                                )
                                Log.e(
                                    "MXL",
                                    "商品：" + i.recoverPriceStr.toString() + i.products?.productName + i.id
                                )
                            }
                        }

                    }
                    spentprice = spentList.sum()
                    recoverprice = recovertList.sum()
                }

                RecycleDialog.showRecycleDialog(mActivity,sb.toString(),"3", recoverprice.toString(), recoveType,this)
//                RecoverPopupWindow().init(
//                    mActivity,
//                    sb.toString(),
//                    spentprice.toString(),
//                    "3",
//                    recoverprice.toString(),
//                    mChoosList.size.toString(), this,
//                    null,
//                    depotlist,
//                    recoveType
//                )
                //   mPresenter?.recoverGoods(sb.toString())
            }
        }
        id_tv_fahuo?.setOnClickListener {
            if (mChoosList.isEmpty()) {
                Utils.showToast(mActivity, "请选择要发货的物品")
            } else {
                if (wechatutil!!.isWechatLogin() == true) {
                    val intent = Intent(mActivity, OrderDetailActivity::class.java)
                    intent.putStringArrayListExtra(
                        "stringList",
                        mChoosList as java.util.ArrayList<String>?
                    )
                    startActivity(intent)
                } else {
                    wechatutil!!.wechatLogin(mActivity, Constant.Key.FIVE_LOTTERY)
                }

            }
            //  JumpUtils.OrderDetailJump()
        }
        id_ll_all_choose?.setOnClickListener {
            if (chooseStatus == 0) {
                chooseStatus = 1
                id_img_xuanze?.setImageResource(R.drawable.icon_xuanzhong)
                mAdapter?.setAllSelect(true)
                mAdapter?.setCancelAllSelect(false)
                mAdapter?.notifyDataSetChanged()

            } else {
                chooseStatus = 0
                mChoosList?.clear()
                id_img_xuanze?.setImageResource(R.drawable.icon_xuanze)
                mAdapter?.setCancelAllSelect(true)
                mAdapter?.setAllSelect(false)
                mAdapter?.notifyDataSetChanged()
            }

        }
        mPresenter = WareHousePresenter(this)
//        mPresenter?.getDepot(status, type, true)

        mAdapter = PickUpAdapter(mActivity, this)
        recyclerView.layoutManager = LinearLayoutManager(mActivity)
        recyclerView?.adapter = mAdapter
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (isSlideToBottom(recyclerView)) {
                    Log.e("MXL", "上拉加载")
                    if (mAdapter?.getLoadMore() == true) {
                        mPresenter?.getDepot(status, type, false)
                    }
                }
            }
        })
//        Utils.setOnScrollBottomListener(recyclerView) { _, _ ->
//            Log.e("MXL","仓库页上啦加载")
//            if (mAdapter?.getLoadMore() == true) {
//                mPresenter?.getDepot(status, type, false)
//            }
//        }
        refreshLayout?.setColorSchemeColors(resources.getColor(com.zxhl.cms.R.color.color_3A95FD))
        refreshLayout?.setOnRefreshListener {
            chooseStatus = 0
            id_img_xuanze?.setImageResource(R.drawable.icon_xuanze)
            mChoosList?.clear()
            mAdapter?.setCancelAllSelect(true)
            mPresenter?.clearPage()
            mPresenter?.getDepot(status, type, true)
        }


        mUpdateDataObservable = RxBus.get().register(Constant.order_data_update, Int::class.java)
        mUpdateDataObservable?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<Int?> { s ->
                chooseStatus = 0
                id_img_xuanze?.setImageResource(R.drawable.icon_xuanze)
                mChoosList?.clear()
                mAdapter?.setCancelAllSelect(true)
                mPresenter?.clearPage()
                mPresenter?.getDepot(status, type, true)
            }, Consumer<Throwable?> { })

        lazyLoad()
    }

    fun isSlideToBottom(recyclerView: RecyclerView): Boolean {
        if (recyclerView == null) return false
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
            return true
        return false
    }

    override fun lazyLoad() {
        super.lazyLoad()
        if (isInitial && isVisible) {
            Log.e("MXL", "仓库代替货")
            chooseStatus = 0
            id_img_xuanze?.setImageResource(R.drawable.icon_xuanze)
            mChoosList?.clear()
            mAdapter?.setCancelAllSelect(true)
            mPresenter?.clearPage()
            mPresenter?.getDepot(status, type, true)
            mPresenter?.getAppInfo()
            mPresenter?.getNotice()
        }

    }

    companion object {

        fun newInstance() = TobePickUpFragment()
    }

    override fun setWareHouseData(boolean: Boolean, reslut: List<DepotEntity>?) {
        if (boolean) {
            mAdapter?.clear()
            refreshLayout?.isRefreshing = false
        }
        if (reslut?.isEmpty() == true) {
            id_ll_empty?.visibility = View.VISIBLE
            id_rl_xianshi?.visibility = View.GONE
            id_tv_dixian?.visibility = View.GONE
        } else {
            chooseStatus = 0
            id_img_xuanze?.setImageResource(R.drawable.icon_xuanze)
            id_ll_empty?.visibility = View.GONE
            if (reslut?.size == 1) {
                if (reslut[0].boxId.equals("-2")) {
                    id_rl_xianshi?.visibility = View.GONE
                    id_tv_dixian?.visibility = View.VISIBLE
                } else {
                    id_rl_xianshi?.visibility = View.VISIBLE
                    id_tv_dixian?.visibility = View.VISIBLE
                }
            } else {
                id_rl_xianshi?.visibility = View.VISIBLE
                id_tv_dixian?.visibility = View.VISIBLE
            }
        }
        mAdapter?.appendToList(reslut)
        mAdapter?.notifyDataSetChanged()
    }

    override fun setLoadMore(isBoolean: Boolean) {
        mAdapter?.setLoadMore(isBoolean)
    }

    override fun recoverSuccess() {
        //回收成功刷新数据
        Utils.showToast(mActivity, "回收成功")
        chooseStatus = 0
        id_img_xuanze?.setImageResource(R.drawable.icon_xuanze)
        mChoosList?.clear()
        mAdapter?.setCancelAllSelect(true)
        mPresenter?.getDepot(status, type, true)
        UserDataUtils.updateUserInfo(this)
    }

    override fun loadError() {
        refreshLayout?.isRefreshing = false
        id_tv_dixian?.visibility = View.GONE
    }

    override fun setAppInfo(reslut: AppInEntity?) {
        id_tv_depot_text?.text = "${reslut?.depots_text}"
        recoveType = reslut?.recover_type.toString()
        SettingPreference.setRecoveType(reslut?.recover_type)
    }

    override fun setNotice(reslut: NoticeEntity?) {
        if (!TextUtils.isEmpty(reslut?.text)) {
            id_ll_notice?.visibility = View.VISIBLE
            id_tv_notice_content?.text = reslut?.text
        } else {
            id_ll_notice?.visibility = View.GONE
        }
    }

    var mChoosList: MutableList<String> = ArrayList()
    override fun onItemClick(view: View?, position: Int, data: Boolean?) {
        val entity = mAdapter?.getItem(position)
        if (data == true) {
            if (!mChoosList.contains(entity?.id)) {
                mChoosList.add(entity?.id!!)
            }
            if (mChoosList.size > 0 && mChoosList.size == (mAdapter?.itemCount)) {
                chooseStatus = 1
                id_img_xuanze?.setImageResource(R.drawable.icon_xuanzhong)
            }
        } else {
            mAdapter?.setAllSelect(false)
            chooseStatus = 0
            id_img_xuanze?.setImageResource(R.drawable.icon_xuanze)
            mChoosList.remove(entity?.id)
        }

        Log.d("glc", mChoosList.toString())
        (recyclerView?.itemAnimator as SimpleItemAnimator).setSupportsChangeAnimations(false);
    }


    override fun onResult(code: Int, result: String?) {

    }

    private var isPause = false

    override fun onPause() {
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        super.onResume()
//        if (isPause) {
//            mPresenter?.getDepot(status, type, true)
//        }
        isPause = false
    }

    override fun onClosePopupWindow() {
        recoverSuccess()
    }

    override fun loginSuccess(lottery: String?) {
        val intent = Intent(mActivity, OrderDetailActivity::class.java)
        intent.putStringArrayListExtra(
            "stringList",
            mChoosList as java.util.ArrayList<String>?
        )
        startActivity(intent)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            UMShareAPI.get(mActivity).onActivityResult(requestCode, resultCode, data)
        } catch (ex: Exception) {
        }
    }

}