package cn.muchinfo.rma.view.base.future.trade

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.MutableLiveData
import androidx.viewpager.widget.ViewPager
import cn.muchinfo.rma.R
import cn.muchinfo.rma.business.future.adapter.ChannelOrderReqData
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.account.loginQeruy.GoodsInfo
import cn.muchinfo.rma.global.data.futureOrders.FutureHoldData
import cn.muchinfo.rma.global.database.AppDatabase
import cn.muchinfo.rma.global.database.DataBase
import cn.muchinfo.rma.global.room.Builder
import cn.muchinfo.rma.global.toPercentage
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.autoWidget.utils.NumberUtils
import cn.muchinfo.rma.view.autoWidget.view.MangeNumberEditText2
import cn.muchinfo.rma.view.base.BaseActivity
import cn.muchinfo.rma.view.base.app.FutureConstent
import cn.muchinfo.rma.view.base.future.SearchActivity
import cn.muchinfo.rma.view.base.future.deals.DealFragment
import cn.muchinfo.rma.view.base.future.entrusts.EntrustFragment
import cn.muchinfo.rma.view.base.future.holds.HoldFragment
import cn.muchinfo.rma.view.base.home.contract.emptyView
import cn.muchinfo.rma.view.eventbus.EventConstent
import cn.muchinfo.rma.view.eventbus.MessageEvent
import cn.muchinfo.rma.view.eventbus.QuoteMessageEvent
import cn.muchinfo.rma.view.eventbus.TradeMessageEvent
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator
import com.qmuiteam.qmui.widget.tab.QMUITabSegment
import mtp.polymer.com.autowidget.dialog.creatSelectAccountDialog
import mtp.polymer.com.autowidget.dialog.createCustomDialog
import mtp.polymer.com.autowidget.dialog.createLoadingDialog
import mtp.polymer.com.autowidget.utils.bindTaskStatus
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.viewPager

/**
 * 期货交易页面
 */
class GoodsTradeActivity : BaseActivity<GoodsTradeViewModel>() {

    /** 价格输入框 **/
    lateinit var priceInputEdittext: MangeNumberEditText2

    /** 数量输入框 **/
    lateinit var amountInputEdittext: MangeNumberEditText2

    /** 买多价 **/
    lateinit var buy_more_text: TextView

    /** 卖空 **/
    lateinit var sort_selling_text: TextView

    /** 平仓操作textview */
    lateinit var unwind_text: TextView

    /** 价格成交类型 **/
    lateinit var numImage: ImageView

    lateinit var segment: QMUITabSegment
    var selectedTabIndex: Int = 0
    private lateinit var viewPager: ViewPager

    /** 用于订阅行情的唯一标识 */
    val thisTag by lazy {
        "goodtradeorder"
    }

    /** 当前页面的goodsid **/
    val goodsId by lazy {
        intent.getStringExtra("goodsId")
    }

    val outGoodsCode by lazy {
        intent.getStringExtra("outGoodsCode")
    }

    /** 当前页面的商品信息 **/
    val goodsInfoData: MutableLiveData<GoodsInfo> = MutableLiveData()

    /** 所选择的持仓单单据 **/
    var futureHoldData : FutureHoldData? = null

    /** 暂存一个价格用于提交订单 **/
    var orderPrice: String = ""

    private val tabsArray: List<String> by lazy {
        arrayListOf(
            "持仓",
            "委托",
            "成交"
        )
    }

    private var loadingDialog: Dialog? = null

    private val tabFragments: ArrayList<Fragment> = arrayListOf(
        HoldFragment.getInstance(), // 持仓
        EntrustFragment.getInstance(), // 委托
        DealFragment.getInstance() // 成交
    )

    private val pagerAdapter: FragmentPagerAdapter by lazy {
        object : FragmentPagerAdapter(
            supportFragmentManager,
            BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {

            override fun getPageTitle(position: Int): CharSequence? {
                return tabsArray[position]
            }

            override fun getItem(position: Int): Fragment {
                return tabFragments[position]
            }

            override fun getCount(): Int {
                return tabsArray.size
            }
        }
    }

    //价格取价方式
    private val priceOrderTypePopWindow by lazy {
        ListPopWindow.Builder(
            attachView = numImage,
            backgroundColor = Color.WHITE,
            textColor = "#333333",
            isShowMark = false
        )
            .addMenuItem(
                ListPopWindow.IconParam(
                    iconImg = this.getTintDrawable(
                        R.drawable.rma_check_backgrond,
                        "#159dfd"
                    ), title = "对手价", onItemClickListener = {
                        viewModel.priceOrderType.postValue(FutureConstent.eOrderPriceSelectType_Opposite)
                        viewModel.tradeMode.postValue(FutureConstent.PriceMode_PRICEMODE_LIMIT)
                    })
            )
            .addMenuItem(
                ListPopWindow.IconParam(
                    iconImg = this.getTintDrawable(
                        R.drawable.rma_check_backgrond,
                        "#159dfd"
                    ), title = "最新价", onItemClickListener = {
                        viewModel.priceOrderType.postValue(FutureConstent.eOrderPriceSelectType_Last)
                        viewModel.tradeMode.postValue(FutureConstent.PriceMode_PRICEMODE_LIMIT)
                    })
            )
//            .addMenuItem(ListPopWindow.IconParam(iconImg = this.getTintDrawable(R.drawable.rma_check_backgrond, "#159dfd"), title = "市价", onItemClickListener = {
//                viewModel.priceOrderType.postValue(FutureConstent.eOrderPriceSelectType_Market)
//                viewModel.tradeMode.postValue(FutureConstent.PriceMode_PRICEMODE_MARKET)//只有市价时
//            }))
            .addMenuItem(
                ListPopWindow.IconParam(
                    iconImg = this.getTintDrawable(
                        R.drawable.rma_check_backgrond,
                        "#159dfd"
                    ), title = "超价", onItemClickListener = {
                        viewModel.priceOrderType.postValue(FutureConstent.eOrderPriceSelectType_OppositeOne)
                        viewModel.tradeMode.postValue(FutureConstent.PriceMode_PRICEMODE_LIMIT)
                    })
            )
            .addMenuItem(
                ListPopWindow.IconParam(
                    iconImg = this.getTintDrawable(
                        R.drawable.rma_check_backgrond,
                        "#159dfd"
                    ), title = "限价", onItemClickListener = {
                        viewModel.priceOrderType.postValue(FutureConstent.eOrderPriceSelectType_BidPrice)
                        viewModel.tradeMode.postValue(FutureConstent.PriceMode_PRICEMODE_LIMIT)
                        priceInputEdittext.setText(viewModel.quoteDayData.value?.last?.toString())//选择指定价后给输入框设置一个最新价
                    })
            )
            .build()
    }

    /** 初始化当前选择的商品信息 **/
    fun initData(goodsId: String, outGoodsCode: String = "",buyOrSell: Int = -1,isShowLoading : Boolean = true) {
        //当buyorsell不为-1时则设置当前选择的持仓单
        if (buyOrSell != -1){
            futureHoldData = viewModel.getNowSelectHoldData(goodsId = goodsId,buyorsell = buyOrSell)
        }
        viewModel.priceOrderType.postValue(FutureConstent.eOrderPriceSelectType_Last)//默认交易价格取价方式为最新价
        viewModel.tradeMode.postValue(FutureConstent.PriceMode_PRICEMODE_LIMIT)//通道下单类型默认为限价
        goodsInfoData.postValue(Builder.getDatabase<AppDatabase>().goodsInfoDao.getGoodsInfo(goodsId.toInt()))//获取商品详情
        viewModel.queryQuoteDay(tag = thisTag,goodsCodes = outGoodsCode,isShowLoading = isShowLoading)//请求盘面
        viewModel.initAccountData()//拿到当前的资金账号

    }

    //通用的消息更新通知
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(messageEvent : MessageEvent) {
        if (messageEvent.messageType == EventConstent.USERACCOUNTCHANGE){//接到通知更新当前的资金账号
            viewModel.initAccountData()
        }
    }
    //持仓单点击消息通知
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMeesageChangeTradeId(tradeMessageEvent: TradeMessageEvent){
        initData(goodsId = tradeMessageEvent.goodsId,buyOrSell = tradeMessageEvent.buyOrSell,outGoodsCode = tradeMessageEvent.outGoodsCode,isShowLoading = false)
    }

    //行情推送通知
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onQuoteMessageEvent(quoteMessageEvent: QuoteMessageEvent) {
        val goodsids = quoteMessageEvent.goodsid
        //如果推送的goodsid包含当前页面的goodsid，则进行页面刷新
        if (goodsids.contains(goodsId?.toInt())){
            val goodsInfo = Builder.getDatabase<AppDatabase>().goodsInfoDao.getGoodsInfo(goodsId?.toInt() ?: 0)
            val quote = GlobalDataCollection.instance?.goodsInfoAndQuotesList?.find { goodsInfo?.outgoodscode == it.outgoodscode }?.quoteDayData
            if (quote != null){
                viewModel.quoteDayData.postValue(quote)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.removeSubscriptQuote(thisTag)
        EventBus.getDefault().unregister(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 10086) {
            val goodsid = data?.getIntExtra("goodsId", 0)
            val outGoodsCode = data?.getStringExtra("outGoodsCode")
            initData(goodsId = goodsid.toString(),outGoodsCode = outGoodsCode ?: "",buyOrSell = -1)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /**
         * 页面ui
         */
        initData(goodsId = goodsId ?: "0", outGoodsCode = outGoodsCode ?: "")
        viewModel.calculateMoney()
        EventBus.getDefault().register(this)
        verticalLayout {
            loadingDialog = createLoadingDialog(hintStr = "请求中")
            loadingDialog?.bindTaskStatus(context, viewModel.loadingDialogStatus)
            background = resources.getDrawable(R.color.white)
            //头部标题

            linearLayout {
                background = resources.getDrawable(R.color.main_title_bg_color)
                gravity = Gravity.CENTER_VERTICAL
                imageView {
                    imageResource = R.mipmap.back
                    onThrottleFirstClick {
                        finish()
                    }
                }.lparams(autoSize(48), autoSize(48)) {
                    marginStart = autoSize(36)
                }

                emptyView()

                verticalLayout {
                    /** 资金账户选择 **/
                    onThrottleFirstClick {
                        (context as AppCompatActivity).creatSelectAccountDialog {
                            EventBus.getDefault()
                                .post(MessageEvent(EventConstent.USERACCOUNTCHANGE))
                        }.show()
                    }
                    textView {
                        text = "交易"
                        textColorInt = R.color.white
                        textSizeAuto = 36
                    }.lparams(wrapContent, wrapContent) {
                        gravity = Gravity.CENTER_HORIZONTAL
                    }
                    textView {
                        viewModel.usedAccountData.bindOptional(context){
                            text = it?.accountname + "(" + it?.accountid + ")"
                        }
                        textColorStr = "#AED6F0"
                        textSizeAuto = 29
                    }.lparams(wrapContent, wrapContent) {
                        gravity = Gravity.CENTER_HORIZONTAL
                    }
                }.lparams(wrapContent, autoSize(90))

                emptyView()

                view {

                }.lparams(autoSize(48), autoSize(48)) {
                    marginEnd = autoSize(36)
                }
            }.lparams(matchParent, autoSize(120))

            linearLayout {
                gravity = Gravity.CENTER_VERTICAL
                background = resources.getDrawable(R.color.rma_details_status)
                emptyView()
                textView {
                    viewModel.allWorth.bindOptional(context){
                        text = "权益:$it"
                    }
                    textSizeAuto = 31
                    textColorInt = R.color.rma_yellow_text_color
                }.lparams(wrapContent, wrapContent)

                emptyView()
                textView {
                    viewModel.canUseWorth.bindOptional(context){
                        text = "可用:" + NumberUtils.roundNum(it,2)
                    }
                    textSizeAuto = 31
                    textColorInt = R.color.rma_yellow_text_color
                }.lparams(wrapContent, wrapContent)

                emptyView()
            }.lparams(matchParent, autoSize(70))

            verticalLayout {
                nestedScrollView {
                    verticalLayout {
                        linearLayout {
                            verticalLayout {
                                linearLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent(context, SearchActivity::class.java)
                                        startActivityForResult(intent, 1)
                                    }
                                    gravity = Gravity.CENTER_VERTICAL
                                    textView {
                                        text = "品种"
                                        textSizeAuto = 34
                                        textColorInt = R.color.hint_text_color
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = autoSize(30)
                                    }
                                    emptyView()

                                    textView {
                                        goodsInfoData.bindOptional(context) {
                                            text = it?.goodsname
                                        }
                                        textSizeAuto = 34
                                        textColorInt = R.color.rma_black_33
                                    }

                                    emptyView()

                                    imageView {
                                        imageResource = R.mipmap.rma_file_image
                                    }.lparams(autoSize(48), autoSize(48)) {
                                        marginEnd = autoSize(30)
                                    }

                                }.lparams(matchParent, autoSize(90))
                                itemView()
                                /** 价格/涨跌幅 **/
                                linearLayout {
                                    gravity = Gravity.CENTER_VERTICAL
                                    textView {
                                        viewModel.quoteDayData.bindOptional(context) {
                                            text = it?.last.toString()
                                        }
                                        textSizeAuto = 31
                                        textColorInt = R.color.rma_red_color
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = autoSize(30)
                                    }

                                    emptyView()

                                    textView {
                                        viewModel.quoteDayData.bindOptional(context) {
                                            text = it?.last?.minus(it.preclose).toString()
                                        }
                                        textSizeAuto = 31
                                        textColorInt = R.color.rma_red_color
                                    }.lparams(wrapContent, wrapContent)

                                    emptyView()

                                    textView {
                                        viewModel.quoteDayData.bindOptional(context) {
                                            if (it != null){
                                                text = it?.last?.minus(it.preclose)?.div(it.last)
                                                    .toString().toPercentage()
                                            }
                                        }
                                        textSizeAuto = 31
                                        textColorInt = R.color.rma_red_color
                                    }.lparams(wrapContent, wrapContent) {
                                        marginEnd = autoSize(30)
                                    }
                                }.lparams(matchParent, autoSize(90))
                                itemView()
                                /** 输入的价格 **/
                                linearLayout {
                                    gravity = Gravity.CENTER_VERTICAL
                                    textView {
                                        text = "价格"
                                        textSizeAuto = 34
                                        textColorInt = R.color.text_hit_color
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = autoSize(30)
                                    }
                                    emptyView()
                                    numberEditText {
                                        priceInputEdittext = this
                                        setOnTextChangeListener { view, value ->
//                                            if (value.isNotEmpty()){
//                                                viewModel.priceOrderType.postValue(FutureConstent.eOrderPriceSelectType_BidPrice)
//
//                                            }
                                        }
                                        //拿到商品信息后对输入框进行初始化
                                        goodsInfoData.bindOptional(context) {
                                            setDecimal(it?.decimalplace ?: 2)
                                            val limitRangeMin = if (it?.decimalplace == 0) {
                                                1.0
                                            } else {
                                                Math.pow(10.0, -it?.decimalplace?.toDouble()!!)
                                            }//限价范围最小值
                                            val limitRangeMax =
                                                1000000000 - limitRangeMin // 限价范围最大值
                                            setMax(limitRangeMax)
                                            setMin(limitRangeMin)
                                            setStep(Math.pow(10.0, -it.decimalplace.toDouble()))
                                        }
                                        //行情变化后根据不同的价格类型分别对赋值
                                        viewModel.quoteDayData.bindOptional(context) {
                                            if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                setText(it?.last.toString())
                                                setCll(true)
                                            } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价
                                                setText("对手价")
                                                setCll(true)
                                            } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价1
                                                setText("超价")
                                                setCll(true)
                                            } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价
                                                setCll(false)
                                            }
                                        }
                                        //选择不同价格取价类型后对输入框进行赋值12e
                                        viewModel.priceOrderType.bindOptional(context) {
                                            val quoteData = viewModel.quoteDayData.value
                                            if (it == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                setText(quoteData?.last.toString())
                                                setCll(true)
                                            } else if (it == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价
                                                setText("对手价")
                                                setCll(true)
                                            } else if (it == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价
                                                setText("超价")
                                                setCll(true)
                                            } else if (it == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价
                                                setCll(false)
                                            }
                                        }

                                    }.lparams(autoSize(320), autoSize(72))
                                    emptyView()

                                    imageView {
                                        numImage = this
                                        onThrottleFirstClick {
                                            priceOrderTypePopWindow.show()
                                        }
                                        imageResource = R.mipmap.rma_positioning_select
                                    }.lparams(autoSize(48), autoSize(48)) {
                                        marginEnd = autoSize(15)
                                    }
                                }.lparams(matchParent, autoSize(90))
                                itemView()
                                /** 数量 **/
                                linearLayout {
                                    gravity = Gravity.CENTER_VERTICAL
                                    textView {
                                        text = "手数"
                                        textSizeAuto = 34
                                        textColorInt = R.color.text_hit_color
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = autoSize(30)
                                    }
                                    emptyView()
                                    numberEditText {
                                        amountInputEdittext = this
                                        setText("0")
                                    }.lparams(autoSize(320), autoSize(72))
                                    emptyView()

                                    imageView {
                                        imageResource = R.mipmap.rma_positioning_select
                                    }.lparams(autoSize(48), autoSize(48)) {
                                        marginEnd = autoSize(15)
                                    }
                                }.lparams(matchParent, autoSize(90))
                            }.lparams(0, autoSize(366), 7f)

                            view {
                                background = resources.getDrawable(R.color.rma_hint_line_color_eee)
                            }.lparams(autoSize(1), autoSize(366))

                            verticalLayout {
                                verticalLayout {
                                    /** 卖价 **/
                                    linearLayout {
                                        gravity = Gravity.CENTER_VERTICAL
                                        textView {
                                            gravity = Gravity.CENTER
                                            background = createRoundRectDrawable("#1DC089", 5)
                                            text = "卖"
                                            textColorInt = R.color.white
                                            textSizeAuto = 31
                                        }.lparams(autoSize(36), autoSize(36)) {
                                            marginStart = autoSize(20)
                                        }

                                        textView {
                                            viewModel.quoteDayData.bindOptional(context) {
                                                text = NumberUtils.roundNum(
                                                    it?.ask.toString(),
                                                    goodsInfoData.value?.decimalplace ?: 2
                                                )
                                            }
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_red_color
                                        }.lparams(wrapContent, wrapContent) {
                                            marginStart = autoSize(20)
                                        }

                                        emptyView()

                                        textView {
                                            viewModel.quoteDayData.bindOptional(context) {
                                                text = it?.askvolume.toString()
                                            }
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent) {
                                            marginEnd = autoSize(20)
                                        }

                                    }.lparams(matchParent, autoSize(70))
                                    /** 买价 **/
                                    linearLayout {
                                        gravity = Gravity.CENTER_VERTICAL
                                        textView {
                                            gravity = Gravity.CENTER
                                            background = createRoundRectDrawable("#FF5C6F", 5)
                                            text = "买"
                                            textColorInt = R.color.white
                                            textSizeAuto = 31
                                        }.lparams(autoSize(36), autoSize(36)) {
                                            marginStart = autoSize(20)
                                        }

                                        textView {
                                            viewModel.quoteDayData.bindOptional(context) {
                                                text = NumberUtils.roundNum(
                                                    it?.bid.toString(),
                                                    goodsInfoData.value?.decimalplace ?: 2
                                                )
                                            }
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_green_color
                                        }.lparams(wrapContent, wrapContent) {
                                            marginStart = autoSize(20)
                                        }

                                        emptyView()

                                        textView {
                                            viewModel.quoteDayData.bindOptional(context) {
                                                text = it?.bidvolume.toString()
                                            }
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent) {
                                            marginEnd = autoSize(20)
                                        }

                                    }.lparams(matchParent, autoSize(70))
                                }.lparams(matchParent, autoSize(140))
                                itemView()
                                verticalLayout {
                                    /** 成交量 ***/
                                    linearLayout {
                                        gravity = Gravity.CENTER_VERTICAL
                                        textView {
                                            text = "成交量"
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_gray_color
                                        }.lparams(wrapContent, wrapContent) {
                                            marginStart = autoSize(25)
                                        }

                                        emptyView()

                                        textView {
                                            viewModel.quoteDayData.bindOptional(context) {
                                                text = it?.lastvolume.toString()
                                            }
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent) {
                                            marginEnd = autoSize(20)
                                        }
                                    }.lparams(matchParent, autoSize(60))
                                    /** 涨停价 ***/
                                    linearLayout {
                                        textView {
                                            text = "涨停价"
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_gray_color
                                        }.lparams(wrapContent, wrapContent) {
                                            marginStart = autoSize(25)
                                        }

                                        emptyView()

                                        textView {
                                            viewModel.quoteDayData.bindOptional(context) {
                                                text = it?.limitup.toString()
                                            }
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_red_color
                                        }.lparams(wrapContent, wrapContent) {
                                            marginEnd = autoSize(20)
                                        }
                                    }.lparams(matchParent, autoSize(60))
                                    /** 跌停价 ***/
                                    linearLayout {
                                        textView {
                                            text = "跌停价"
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_gray_color
                                        }.lparams(wrapContent, wrapContent) {
                                            marginStart = autoSize(25)
                                        }

                                        emptyView()

                                        textView {
                                            viewModel.quoteDayData.bindOptional(context) {
                                                text = it?.limitdown.toString()
                                            }
                                            textSizeAuto = 31
                                            textColorInt = R.color.rma_green_color
                                        }.lparams(wrapContent, wrapContent) {
                                            marginEnd = autoSize(20)
                                        }
                                    }.lparams(matchParent, autoSize(60))
                                }.lparams(matchParent, autoSize(220))
                            }.lparams(0, autoSize(366), 4f)
                        }.lparams(matchParent, autoSize(366))

                        verticalLayout {
                            background = resources.getDrawable(R.color.main_hit_bg_color)
                            gravity = Gravity.CENTER_VERTICAL
                            linearLayout {
                                visibility = View.GONE
                                gravity = Gravity.CENTER_VERTICAL
                                textView {
                                    text = "订单保证金"
                                    textSizeAuto = 31
                                    textColorInt = R.color.rma_gray_color
                                }.lparams(wrapContent, wrapContent) {
                                    marginStart = autoSize(34)
                                }
                                textView {
                                    text = "231231"
                                    textSizeAuto = 31
                                    textColorInt = R.color.rma_black_33
                                }.lparams(wrapContent, wrapContent) {
                                    marginStart = autoSize(20)
                                }

                                emptyView()

                                textView {
                                    text = "最大可买"
                                    textSizeAuto = 31
                                    textColorInt = R.color.rma_gray_color
                                }.lparams(wrapContent, wrapContent)
                                textView {
                                    text = "12"
                                    textSizeAuto = 31
                                    textColorInt = R.color.main_title_bg_color
                                }.lparams(wrapContent, wrapContent) {
                                    marginStart = autoSize(20)
                                }

                                emptyView()

                                textView {
                                    text = "最大可卖"
                                    textSizeAuto = 31
                                    textColorInt = R.color.rma_gray_color
                                }.lparams(wrapContent, wrapContent)
                                textView {
                                    text = "12"
                                    textSizeAuto = 31
                                    textColorInt = R.color.p_price_red
                                }.lparams(wrapContent, wrapContent) {
                                    marginStart = autoSize(20)
                                }

                                emptyView()

                            }.lparams(matchParent, autoSize(84))

                            linearLayout {
                                verticalLayout {
                                    background = createRoundRectDrawable("#FF5C6F", 5)
                                    onThrottleFirstClick {
                                        if (buy_more_text.text.toString() == "--" || buy_more_text.text.toString()
                                                .isNullOrEmpty()
                                        ) {
                                            ToastUtils.showLong("价格错误")
                                            return@onThrottleFirstClick
                                        }

                                        if (amountInputEdittext.text.toString() == "0"){
                                            ToastUtils.showLong("数量不能为0")
                                            return@onThrottleFirstClick
                                        }

                                        creatOrderDetailsDialog(
                                            type = "1",
                                            orderPrice = buy_more_text.text.toString()
                                        )
                                    }
                                    linearLayout {
                                        gravity = Gravity.CENTER
                                        textView {
                                            buy_more_text = this
                                            //行情变化后根据不同的价格类型分别对赋值
                                            viewModel.quoteDayData.bindOptional(context) {
                                                if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                    setText(it?.last.toString())

                                                } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价/买多取卖一价
                                                    setText(it?.ask.toString())
                                                } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价1/买多取卖一价(参照ios)
                                                    setText(it?.ask.toString())
                                                } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价--限价只需要在选择限价时赋值，其他行情推送不赋值
//                                                    setText(it?.last.toString())
                                                }
                                            }
                                            //选择不同价格取价类型后对输入框进行赋值12e
                                            viewModel.priceOrderType.bindOptional(context) {
                                                val quoteData = viewModel.quoteDayData.value
                                                if (it == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                    setText(quoteData?.last.toString())
                                                } else if (it == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价/买多取卖一价
                                                    setText(quoteData?.ask.toString())
                                                } else if (it == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价/买多取卖一价(参照ios)
                                                    setText(quoteData?.ask.toString())
                                                } else if (it == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价
                                                    setText(quoteData?.last.toString())
                                                }
                                            }
                                            textSizeAuto = 38
                                            textColorInt = R.color.white
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, autoSize(71))
                                    view {
                                        background = resources.getDrawable(R.color.white)
                                    }.lparams(matchParent, autoSize(2)) {
                                        marginStart = autoSize(30)
                                        marginEnd = autoSize(30)
                                    }
                                    linearLayout {
                                        gravity = Gravity.CENTER
                                        textView {
                                            text = "买多"
                                            textSizeAuto = 34
                                            textColorInt = R.color.white
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, autoSize(71))
                                }.lparams(0, matchParent, 1f) {
                                    marginStart = autoSize(34)
                                }

                                verticalLayout {
                                    background = createRoundRectDrawable("#1DC089", 5)
                                    onThrottleFirstClick {
                                        if (sort_selling_text.text.toString() == "--" || sort_selling_text.text.toString()
                                                .isNullOrEmpty()
                                        ) {
                                            ToastUtils.showLong("价格错误")
                                            return@onThrottleFirstClick
                                        }

                                        if (amountInputEdittext.text.toString() == "0"){
                                            ToastUtils.showLong("数量不能为0")
                                            return@onThrottleFirstClick
                                        }

                                        creatOrderDetailsDialog(
                                            type = "2",
                                            orderPrice = sort_selling_text.text.toString()
                                        )
                                    }
                                    linearLayout {
                                        gravity = Gravity.CENTER
                                        textView {
                                            sort_selling_text = this
                                            //行情变化后根据不同的价格类型分别对赋值
                                            viewModel.quoteDayData.bindOptional(context) {
                                                if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                    setText(it?.last.toString())
                                                } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价/卖多取买一价
                                                    setText(it?.ask.toString())
                                                } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价1/卖多取买一价(参照ios)
                                                    setText(it?.ask.toString())
                                                } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价--限价只需要在选择限价时赋值，其他行情推送不赋值
//                                                    setText(it?.last.toString())
                                                }
                                            }
                                            //选择不同价格取价类型后对输入框进行赋值12e
                                            viewModel.priceOrderType.bindOptional(context) {
                                                val quoteData = viewModel.quoteDayData.value
                                                if (it == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                    setText(quoteData?.last.toString())
                                                } else if (it == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价/卖多取买一价
                                                    setText(quoteData?.bid.toString())
                                                } else if (it == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价/卖多取买一价(参照ios)
                                                    setText(quoteData?.bid.toString())
                                                } else if (it == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价
                                                    setText(quoteData?.last.toString())
                                                }
                                            }
                                            textSizeAuto = 38
                                            textColorInt = R.color.white
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, autoSize(71))
                                    view {
                                        background = resources.getDrawable(R.color.white)
                                    }.lparams(matchParent, autoSize(2)) {
                                        marginStart = autoSize(30)
                                        marginEnd = autoSize(30)
                                    }
                                    linearLayout {
                                        gravity = Gravity.CENTER
                                        textView {
                                            text = "卖空"
                                            textSizeAuto = 34
                                            textColorInt = R.color.white
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, autoSize(71))
                                }.lparams(0, matchParent, 1f) {
                                    marginStart = autoSize(20)
                                }

                                verticalLayout {
                                    background = createRoundRectDrawable("#2794FF", 5)
                                    onThrottleFirstClick {
                                        if (futureHoldData == null) {
                                            ToastUtils.showLong("没有选择持仓单单据")
                                            return@onThrottleFirstClick
                                        }

                                        if (amountInputEdittext.text.toString() == "0"){
                                            ToastUtils.showLong("数量不能为0")
                                            return@onThrottleFirstClick
                                        }

                                        if (futureHoldData?.buyorsell == 1){
                                            creatOrderDetailsDialog(type = "3",orderPrice = unwind_text.text.toString())
                                        }else if (futureHoldData?.buyorsell == 0){
                                            creatOrderDetailsDialog(type = "4",orderPrice = unwind_text.text.toString())
                                        }
                                    }
                                    linearLayout {
                                        gravity = Gravity.CENTER
                                        textView {
                                            unwind_text = this
                                            //行情变化后根据不同的价格类型分别对赋值
                                            viewModel.quoteDayData.bindOptional(context) {
                                                if (futureHoldData == null) {
                                                    text = "优先平今"
                                                } else {
                                                    if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                        setText(it?.last.toString())

                                                    } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价/卖多取买一价
                                                        setText(it?.ask.toString())
                                                    } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价1/卖多取买一价(参照ios)
                                                        setText(it?.ask.toString())
                                                    } else if (viewModel.priceOrderType.value == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价--限价只需要在选择限价时赋值，其他行情推送不赋值
//                                                    setText(it?.last.toString())
                                                    }

                                                }
                                            }
                                            //选择不同价格取价类型后对输入框进行赋值12e
                                            viewModel.priceOrderType.bindOptional(context) {
                                                if (futureHoldData == null) {
                                                    text = "优先平今"
                                                } else {
                                                    val quoteData = viewModel.quoteDayData.value
                                                    if (it == FutureConstent.eOrderPriceSelectType_Last) {//最新价
                                                        setText(quoteData?.last.toString())
                                                    } else if (it == FutureConstent.eOrderPriceSelectType_Opposite) {//对手价/卖多取买一价
                                                        setText(quoteData?.bid.toString())
                                                    } else if (it == FutureConstent.eOrderPriceSelectType_OppositeOne) {//超价/卖多取买一价(参照ios)
                                                        setText(quoteData?.bid.toString())
                                                    } else if (it == FutureConstent.eOrderPriceSelectType_BidPrice) {//指定价就是限价
                                                        setText(quoteData?.last.toString())
                                                    }
                                                }
                                            }
                                            text = "优先平今"
                                            textSizeAuto = 38
                                            textColorInt = R.color.white
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, autoSize(71))
                                    view {
                                        background = resources.getDrawable(R.color.white)
                                    }.lparams(matchParent, autoSize(2)) {
                                        marginStart = autoSize(30)
                                        marginEnd = autoSize(30)
                                    }
                                    linearLayout {
                                        gravity = Gravity.CENTER
                                        textView {
                                            //行情变化后根据不同的价格类型分别对赋值
                                            viewModel.quoteDayData.bindOptional(context) {
                                                if (futureHoldData == null) {
                                                    text = "平仓"
                                                } else {
                                                    if (futureHoldData?.buyorsell == 0){
                                                        text = "平卖"
                                                    }else if (futureHoldData?.buyorsell == 1){
                                                        text = "平买"
                                                    }
                                                }
                                            }
                                            viewModel.priceOrderType.bindOptional(context) {
                                                if (futureHoldData == null) {
                                                    text = "平仓"
                                                } else {
                                                    if (futureHoldData?.buyorsell == 0){
                                                        text = "平卖"
                                                    }else if (futureHoldData?.buyorsell == 1){
                                                        text = "平买"
                                                    }
                                                }
                                            }
                                            text = "平仓"
                                            textSizeAuto = 34
                                            textColorInt = R.color.white
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, autoSize(71))
                                }.lparams(0, matchParent, 1f) {
                                    marginStart = autoSize(20)
                                    marginEnd = autoSize(34)
                                }

                            }.lparams(matchParent, autoSize(144))

                        }.lparams(matchParent, autoSize(178))

                        itemView()

                        // 分页框
                        tabSegment {
                            segment = this
                            background = resources.getDrawable(R.color.white)
                            addOnTabSelectedListener(object :
                                QMUITabSegment.OnTabSelectedListener {
                                override fun onDoubleTap(index: Int) {}
                                override fun onTabReselected(index: Int) {}
                                override fun onTabUnselected(index: Int) {}
                                override fun onTabSelected(index: Int) {
                                    selectedTabIndex = index
                                }
                            })
                            setIndicator(
                                QMUITabIndicator(
                                    QMUIDisplayHelper.dp2px(context, 2),
                                    false,
                                    true
                                )
                            )
                            setDefaultTextSize(ConvertUtils.sp2px(16f), ConvertUtils.sp2px(16f))
                        }.lparams(matchParent, autoSize(100))

                        view {
                            background = resources.getDrawable(R.color.main_hit_bg_color)
                        }.lparams(matchParent, autoSize(1)) {
                            marginStart = autoSize(32)
                            marginEnd = autoSize(32)
                        }
                        // 内容
                        viewPager {
                            background = resources.getDrawable(R.color.white)
                            viewPager = this
                            id = R.id.view_pager
                        }.lparams(matchParent, autoSize(2000))
                        //真的是，不搞个id就不行
                        findViewById<ViewPager>(R.id.view_pager).adapter = pagerAdapter
                        segment.setupWithViewPager(viewPager)
                        segment.selectTab(selectedTabIndex)

                    }
                }
            }
        }
    }

    /**
     * 操作请求
     * @param buyOrSell Int 0买1卖
     * @param isClose Boolean 是否是平仓单
     * @param orderPrice String 价格
     */
    private fun commitDealData(buyOrSell: Int, isClose: Boolean, orderPrice: String) {
        val datas = ChannelOrderReqData()
        datas.setAccountID(GlobalDataCollection.instance?.accountId ?: 0) // 交易账号
        if (isClose) {
            if (buyOrSell == 0) {
                //平仓---平买单，方向是卖
                datas.setBuyOrSell(0)
            } else {
                //平仓---平卖单，方向是买
                datas.setBuyOrSell(1)
            }
        } else {
            datas.setBuyOrSell(buyOrSell)
        }
        datas.clientOrderTime = TimeUtils.getNowString() // 客户端委托时间  当前时间
        datas.clientType = 3 // 客户端类型: 1客户端  3 手机端 android
        datas.goodsID = goodsInfoData.value?.goodsid ?: 0//商品id
        datas.loginID = GlobalDataCollection.instance?.loginRsp?.loginID ?: 0 //登录账号

        datas.marketID = goodsInfoData.value?.marketid ?: 0
        datas.validType = 1 // 有效类型-1当日有效
        datas.channelOperateType = FutureConstent.ChannelOperateType_ORDER // 操作类型  1:正常类型  默认写死？？？
        datas.channelOrderSrc = 1 // 单据来源委托来源-1:客户端  //默认写死？
        datas.hedgeFlag = 0 // 投机套保标志-0:无

        datas.orderPrice = orderPrice.toDouble()
        datas.orderQty = amountInputEdittext.text.toString().toLong()

        if (isClose) {
            // 平仓
            datas.closeType = 2
            datas.channelBuildType = FutureConstent.eChannelBuildType_CLOSE // 下单类型  建仓还是平仓
        } else {
            // 买卖建仓
            datas.closeType = 1
            datas.channelBuildType = FutureConstent.eChannelBuildType_OPEN // 下单类型  建仓还是平仓
        }
        datas.priceMode = viewModel.tradeMode.value ?: 2 // 取价方式-1:市价 (现在默认先市价和限价)
        datas.setCloseTodayQty(amountInputEdittext.text.toString().toLong())
//        if (goodsInfo.getInnerDealMode() === 3) {
//            if (mTradeSummaryData != null) {
//                val todayAvailQty: String =
//                    java.lang.String.valueOf(mTradeSummaryData.getTodayAvailQty())
//                if (mTradeSummaryData.getTodayAvailQty() > 0) { //
//                    if (mTradeSummaryData.getTodayAvailQty() > tradeNum) { // 如果平今的大于输入的数量，那就不要使用平今数量，直接赋值tradeNum给CloseTodayQty
//                        datas.setCloseTodayQty(java.lang.Double.valueOf(tradeNum).toLong())
//                    } else {
//                        datas.setCloseTodayQty(
//                            java.lang.Double.valueOf(todayAvailQty.trim { it <= ' ' }).toLong()
//                        )
//                    }
//                } else {
//                    datas.setCloseTodayQty(0)
//                }
//            }
//        }
        datas.setTimeValidType(FutureConstent.ValidTypeEnum_VALIDTYPE_DR) // 时间有效类型   默认写死当日有效
        datas.setRelatedID(0) // 关联单号 默认写死
        datas.setServiceTime("") //服务端时间string
        //        datas.setIp(PolApplication.getIPAddress(getContext()));B
//        val bbb: String = Utils.getCommonIp()
//        datas.setIp(bbb)
        datas.setValidtime("") // 有效时间string
        viewModel.tradeRequest(data = datas) { isCompleted ->
            if (isCompleted){
                if (selectedTabIndex == 0){
                    (tabFragments.get(selectedTabIndex) as HoldFragment).onRefresh()
                }else if (selectedTabIndex == 1){

                }else if (selectedTabIndex == 2){

                }
            }
        }
    }


    /**
     * 订单详情弹出提示
     * type : 1 买多，2卖空 3平买 4平卖
     */
    @SuppressLint("SetTextI18n")
    fun creatOrderDetailsDialog(type: String, orderPrice: String) {
        createCustomDialog(cancelable = false) { dialog ->
            backgroundColor = Color.parseColor("#5f000000")

            verticalLayout {
                backgroundDrawable = createRoundRectDrawable("#ffffff", 24)

                linearLayout {
                    gravity = Gravity.CENTER
                    textView {
                        text = "订单详情"
                        textSizeAuto = 31
                        textColorInt = R.color.rma_black_33
                    }.lparams(wrapContent, wrapContent)
                }.lparams(matchParent, autoSize(100))
                itemView()
                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL
                    linearLayout {
                        emptyView()
                        textView {
                            text = "账户："
                            textColorInt = R.color.rma_black_33
                            textSizeAuto = 28
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 2f)
                    linearLayout {
                        textView {
                            text = GlobalDataCollection.instance?.accountId.toString()
                            textSizeAuto = 28
                            textColorInt = R.color.rma_black_33
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 5f)
                }.lparams(matchParent, autoSize(90))

                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL
                    linearLayout {
                        emptyView()
                        textView {
                            text = "类型："
                            textColorInt = R.color.rma_black_33
                            textSizeAuto = 28
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 2f)
                    linearLayout {
                        textView {
                            if (type == "1") {
                                text = "买多"
                            } else if (type == "2") {
                                text = "卖空"
                            } else if (type == "3") {
                                text = "平买"
                            } else if (type == "4") {
                                text = "平卖"
                            }
                            textSizeAuto = 28
                            textColorInt = R.color.rma_black_33
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 5f)
                }.lparams(matchParent, autoSize(90))

                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL
                    linearLayout {
                        emptyView()
                        textView {
                            text = "名称代码："
                            textColorInt = R.color.rma_black_33
                            textSizeAuto = 28
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 2f)
                    linearLayout {
                        textView {
                            text =
                                goodsInfoData.value?.goodsname + "(" + goodsInfoData.value?.goodscode + ")"
                            textSizeAuto = 28
                            textColorInt = R.color.rma_black_33
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 5f)
                }.lparams(matchParent, autoSize(90))

                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL
                    linearLayout {
                        emptyView()
                        textView {
                            text = "价格："
                            textColorInt = R.color.rma_black_33
                            textSizeAuto = 28
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 2f)
                    linearLayout {
                        textView {
                            text = orderPrice
                            textSizeAuto = 28
                            textColorInt = R.color.rma_black_33
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 5f)
                }.lparams(matchParent, autoSize(90))

                linearLayout {
                    gravity = Gravity.CENTER_VERTICAL
                    linearLayout {
                        emptyView()
                        textView {
                            text = "数量："
                            textColorInt = R.color.rma_black_33
                            textSizeAuto = 28
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 2f)
                    linearLayout {
                        textView {
                            text = amountInputEdittext.text.toString()
                            textSizeAuto = 28
                            textColorInt = R.color.rma_black_33
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, wrapContent, 5f)
                }.lparams(matchParent, autoSize(90))

                itemView()

                linearLayout {
                    linearLayout {
                        gravity = Gravity.CENTER
                        onThrottleFirstClick {
                            dialog.dismiss()
                        }
                        textView {
                            text = "取消"
                            textSizeAuto = 31
                            textColorInt = R.color.rma_hint_title_text_color
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, autoSize(100), 1f)

                    linearLayout {
                        gravity = Gravity.CENTER
                        onThrottleFirstClick {
                            var buyOrSell = 0
                            var isClose = false
                            if (type == "1" || type == "2") {//1为买 2为卖
                                isClose = false
                            } else if (type == "3" || type == "4") { //3是平卖，4是平买
                                isClose = true
                            }
                            if (type == "1" || type == "3") {
                                buyOrSell = 0
                            } else if (type == "2" || type == "4") {
                                buyOrSell = 1
                            }

                            commitDealData(
                                buyOrSell = buyOrSell,
                                isClose = isClose,
                                orderPrice = orderPrice
                            )
                            dialog.dismiss()
                        }
                        textView {
                            text = "确定"
                            textSizeAuto = 31
                            textColorInt = R.color.rma_yellow_text_color
                        }.lparams(wrapContent, wrapContent)
                    }.lparams(0, autoSize(100), 1f)
                }.lparams(matchParent, autoSize(100))
            }.lparams(matchParent, wrapContent) {
                topMargin = autoSize(450)
                marginStart = autoSize(100)
                marginEnd = autoSize(100)
            }
        }.show()
    }
}


fun _LinearLayout.itemView() {
    view {
        background = resources.getDrawable(R.color.rma_hint_line_color_eee)
    }.lparams(matchParent, autoSize(1))
}