package cn.muchinfo.rma.view.base.home.commodity

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.lifecycle.MutableLiveData
import cn.muchinfo.rma.R
import cn.muchinfo.rma.global.MTPEnums
import cn.muchinfo.rma.global.data.ContractData
import cn.muchinfo.rma.global.data.MiddleGoodsData
import cn.muchinfo.rma.global.data.WrStandardData
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.protobuf.protoclasses.ManageServiceMI2
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.base.BaseActivity
import cn.muchinfo.rma.view.base.home.commodity.viewholder.InsuredVarietyViewHolder
import cn.muchinfo.rma.view.base.home.commodity.viewholder.SpotInfoData
import cn.muchinfo.rma.view.base.home.commodity.viewholder.SpotModelViewHolder
import cn.muchinfo.rma.view.base.home.contract.ContractDataViewHolder
import cn.muchinfo.rma.view.base.home.contract.baseInformationView
import cn.muchinfo.rma.view.base.home.contract.emptyView
import cn.muchinfo.rma.view.base.home.contract.viewItemUI
import com.blankj.utilcode.util.ToastUtils
import mtp.polymer.com.autowidget.adapter.BaseAdapter
import mtp.polymer.com.autowidget.dialog.SelectData
import mtp.polymer.com.autowidget.dialog.creatBottomSheetDialog
import mtp.polymer.com.autowidget.dialog.createLoadingDialog
import mtp.polymer.com.autowidget.utils.bindTaskStatus
import org.jetbrains.anko.*

/**
 * 新增现货品种
 */
class AddSpotGoodsActivity : BaseActivity<CommodityInformationViewModel>() {

    /** 备注 **/
    lateinit var remask_edittext: EditText

    /** 现货品种名称 **/
    lateinit var spot_variety_name_edittext: EditText

    /** 现货品种代码 **/
    lateinit var spot_variety_code_edittext: EditText

    /** 现货品种代码 **/
    lateinit var spot_variety_enauname_edittext: EditText

    /**
     * type 1 新增 2 修改 3 停用 4 详情 5 恢复
     */
    val type by lazy {
        intent.getStringExtra("type")
    }

    /**
     * 用作修改，停用，恢复时的数据
     */
    val data: WrStandardData by lazy {
        intent.getParcelableExtra<WrStandardData>("data") as WrStandardData
    }

    //型号适配
    private val spotModelAdapter: BaseAdapter<SpotInfoData, SpotModelViewHolder> =
        BaseAdapter { _, _ -> SpotModelViewHolder(this, viewModel, "1",operationType = type ?: "") }

    //品牌适配
    private val brandModelAdapter: BaseAdapter<SpotInfoData, SpotModelViewHolder> =
        BaseAdapter { _, _ -> SpotModelViewHolder(this, viewModel, "2",operationType = type ?: "") }

    //品牌适配
    private val middleGoodsAdapter: BaseAdapter<SpotInfoData, InsuredVarietyViewHolder> =
        BaseAdapter { _, _ -> InsuredVarietyViewHolder(this, viewModel,operationType = type ?: "") }

    /** 选择的单位 **/
    val selectUnitType: MutableLiveData<SelectData> = MutableLiveData()

    val dialog by lazy { createLoadingDialog(hintStr = "请求中...") }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //页面内容UI
        contentUI()
        init()
    }

    //初始化数据
    fun init() {
        if (type == "1") {
            val spotModelList = arrayListOf(SpotInfoData(id = "1", value = ""))
            viewModel.spotModelList.postValue(spotModelList)
            val beandModelList = arrayListOf(SpotInfoData(id = "1", value = ""))
            viewModel.brandModelList.postValue(beandModelList)
            val middleModelList = arrayListOf(SpotInfoData(id = "1"))
            viewModel.middlegoodList.postValue(middleModelList)
            viewModel.queryMiddleGoodsList("1")
        } else {
            viewModel.queryWrStandardDetails(data.wrstandardid ?: "")
        }
    }

    fun contentUI() {
        verticalLayout {
            dialog.bindTaskStatus(context, viewModel.loadingDialogStatus)
            background = resources.getDrawable(R.color.segtabment_bg_color)
            //头部标题
            topBar {
                commonLeftButton()
                commonTitle {
                    if (type == "1") {
                        text = "新增现货品种"
                    } else if (type == "2") {
                        text = "修改现货品种"
                    } else if (type == "3") {
                        text = "停用现货品种"
                    } else if (type == "5") {
                        text = "恢复现货品种"
                    }else{
                        text = "现货品种详情"
                    }
                }
            }

            frameLayout {
                nestedScrollView {
                    verticalLayout {
                        baseInformationView("基本信息")

                        linearLayout {
                            background = resources.getDrawable(R.color.white)
                            gravity = Gravity.CENTER_VERTICAL
                            textView {
                                text = "*"
                                textColorInt = R.color.rma_star_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(37)
                            }

                            textView {
                                text = "现货品种名称"
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(10)
                            }

                            editText {
                                if (type == "2" ||  type == "4" || type == "3" || type == "5"){
                                    isEnabled = false
                                    setText(data.wrstandardname)
                                }else{
                                    isEnabled = true
                                }
                                spot_variety_name_edittext = this
                                hint = "请输入商品名称"
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_TEXT
//                                setDecimalInputType()
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(matchParent, autoSize(132)) {
                                marginStart = autoSize(40)
                            }
                        }.lparams(matchParent, autoSize(132))

                        viewItemUI()


                        linearLayout {
                            background = resources.getDrawable(R.color.white)
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                text = "现货品种代码"
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(50)
                            }

                            editText {
                                if (type == "2" || type == "4" || type == "3" || type == "5"){
                                    isEnabled = false
                                    setText(data.wrstandardcode)
                                }else{
                                    isEnabled = true
                                }
                                spot_variety_code_edittext = this
                                hint = "请输入商品代码"
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_TEXT
//                                setDecimalInputType()
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(matchParent, autoSize(132)) {
                                marginStart = autoSize(40)
                            }
                        }.lparams(matchParent, autoSize(132))

                        viewItemUI()

                        linearLayout {
                            background = resources.getDrawable(R.color.white)
                            gravity = Gravity.CENTER_VERTICAL
                            viewModel.wrStandardDetails.bindOptional(context) { data ->
                                selectUnitType.postValue(
                                    SelectData(
                                        id = data?.wrd?.unitid ?: "",
                                        value = data?.wrd?.enumdicname ?: ""
                                    )
                                )
                            }
                            onThrottleFirstClick {
                                //对于修改，停用，复用的操作不能选择
                                if (type == "4" || type == "3" || type == "5"){
                                    return@onThrottleFirstClick
                                }
                                val selectDataList = arrayListOf(
                                    SelectData(
                                        id = "1",
                                        value = "吨"
                                    ),
                                    SelectData(
                                        id = "2",
                                        value = "千克"
                                    ), SelectData(
                                        id = "3",
                                        value = "克"
                                    ),
                                    SelectData(
                                        id = "4",
                                        value = "股"
                                    ),
                                    SelectData(
                                        id = "6",
                                        value = "张"
                                    ),
                                    SelectData(
                                        id = "7",
                                        value = "桶"
                                    )
                                )
                                creatBottomSheetDialog("请选择客户类型", selectDataList) {
                                    selectUnitType.postValue(this)
                                }
                            }
                            textView {
                                text = "*"
                                textColorInt = R.color.rma_star_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(37)
                            }

                            textView {
                                text = "单位"
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(10)
                            }

                            textView {
                                selectUnitType.bindOptional(context) {
                                    text = it?.value
                                    textColorInt = R.color.rma_black_33
                                }
                                text = "请选择单位"
                                textSizeAuto = 31
                                textColorInt = R.color.rma_hint_text_color_ccc
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(80)
                            }

                            emptyView()

                            imageView {
                                imageResource = R.mipmap.rma_more
                            }.lparams(autoSize(36), autoSize(36)) {
                                marginEnd = autoSize(25)
                            }
                        }.lparams(matchParent, autoSize(132))

                        baseInformationView("型号品牌信息")

                        //添加型号信息
                        recyclerView {
                            background = resources.getDrawable(R.color.white)
                            adapter = spotModelAdapter
                            isNestedScrollingEnabled = false
                        }.lparams(matchParent, wrapContent)

                        viewModel.spotModelList.bindOptional(context) {
                            spotModelAdapter.setNewData(it)
                        }

                        viewItemUI()

                        linearLayout {
                            background = resources.getDrawable(R.color.white)
                            gravity = Gravity.CENTER_VERTICAL
                            emptyView()
                            imageView {
                                imageResource = R.mipmap.rma_add
                            }.lparams(autoSize(36), autoSize(36))

                            textView {
                                onThrottleFirstClick {
                                    if (type == "4" || type == "3" || type == "5"){
                                        return@onThrottleFirstClick
                                    }
                                    viewModel.changeSpotModelList(
                                        "1",
                                        viewModel.spotModelList.value?.size?.plus(1).toString(),
                                        value = ""
                                    )
                                }
                                text = "添加型号"
                                textColorInt = R.color.rma_blue_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginEnd = autoSize(35)
                            }
                        }.lparams(matchParent, autoSize(80))

                        //添加型号信息
                        recyclerView {
                            background = resources.getDrawable(R.color.white)
                            adapter = brandModelAdapter
                            isNestedScrollingEnabled = false
                        }.lparams(matchParent, wrapContent)

                        viewModel.brandModelList.bindOptional(context) {
                            brandModelAdapter.setNewData(it)
                        }

                        viewItemUI()

                        linearLayout {
                            background = resources.getDrawable(R.color.white)
                            gravity = Gravity.CENTER_VERTICAL
                            emptyView()
                            imageView {
                                imageResource = R.mipmap.rma_add
                            }.lparams(autoSize(36), autoSize(36))

                            textView {
                                onThrottleFirstClick {
                                    if (type == "4" || type == "3" || type == "5"){
                                        return@onThrottleFirstClick
                                    }
                                    viewModel.changeSpotModelList(
                                        "1",
                                        viewModel.spotModelList.value?.size?.plus(1).toString(),
                                        value = ""
                                    )
                                }
                                text = "添加品牌"
                                textColorInt = R.color.rma_blue_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginEnd = autoSize(35)
                            }
                        }.lparams(matchParent, autoSize(80))

                        baseInformationView("套保品种信息")

                        //添加套保品种信息
                        recyclerView {
                            background = resources.getDrawable(R.color.white)
                            adapter = middleGoodsAdapter
                            isNestedScrollingEnabled = false
                        }.lparams(matchParent, wrapContent)

                        viewModel.middlegoodList.bindOptional(context) {
                            middleGoodsAdapter.setNewData(it)
                        }

                        linearLayout {
                            background = resources.getDrawable(R.color.white)
                            gravity = Gravity.CENTER_VERTICAL
                            emptyView()
                            imageView {
                                imageResource = R.mipmap.rma_add
                            }.lparams(autoSize(36), autoSize(36))

                            textView {
                                onThrottleFirstClick {
                                    if (type == "4" || type == "3" || type == "5"){
                                        return@onThrottleFirstClick
                                    }
                                    viewModel.changeMiddleGoodsList(
                                        "1",
                                        viewModel.middlegoodList.value?.size?.plus(1).toString()
                                    )
                                }
                                text = "添加套保品种"
                                textColorInt = R.color.rma_blue_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginEnd = autoSize(35)
                            }
                        }.lparams(matchParent, autoSize(80))

                        baseInformationView("其他信息")

                        linearLayout {
                            background = resources.getDrawable(R.color.white)
                            gravity = Gravity.CENTER_VERTICAL
                            textView {
                                text = "备        注"
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            editText {
                                isEnabled = if (type == "4" || type == "3" || type == "5"){
                                    false
                                }else{
                                    true
                                }
                                remask_edittext = this
                                hint = "请输入备注"
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_TEXT
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(matchParent, autoSize(260)) {
                                marginStart = autoSize(80)
                            }
                        }.lparams(matchParent, autoSize(136)) {
                            bottomMargin = autoSize(200)
                        }

                    }
                }

                linearLayout {
                    background = resources.getDrawable(R.color.white)
                    gravity = Gravity.CENTER_VERTICAL

                    if (type == "4"){
                        visibility = View.GONE
                    }else{
                        visibility = View.VISIBLE
                    }
                    textView {
                        onThrottleFirstClick {
                            if (checkUpdate().not()) {
                                return@onThrottleFirstClick
                            }
                            if (type == "1") {
                                viewModel.requestGoodsApply(
                                    deliverygoodscode = spot_variety_code_edittext.text.toString(),
                                    deliverygoodsname = spot_variety_name_edittext.text.toString(),
                                    unitid = selectUnitType.value?.id?.toLong()!!,
                                    type = 1,
                                    remark = remask_edittext.text.toString(),
                                    spotgoodsmodels = getSpotModelList(),
                                    spotgoodsbrands = getBrandModelList(),
                                    wrsconvertdetails = getMiddleModelList()
                                ) {
                                    finish()
                                }
                            }else if (type == "2"){//修改
                                viewModel.requestGoodsApply(
                                    deliverygoodscode = spot_variety_code_edittext.text.toString(),
                                    deliverygoodsname = spot_variety_name_edittext.text.toString(),
                                    unitid = selectUnitType.value?.id?.toLong()!!,
                                    wrstandardid = data.wrstandardid?.toLong() ?: 0,
                                    type = 2,
                                    remark = remask_edittext.text.toString(),
                                    spotgoodsmodels = getSpotModelList(),
                                    spotgoodsbrands = getBrandModelList(),
                                    wrsconvertdetails = getMiddleModelList()
                                ) {
                                    finish()
                                }
                            }else if (type == "3"){//停用
                                viewModel.requestGoodsCancelReq(wrstandardid = data.wrstandardid?.toLong() ?: 0,isvalid = 0){
                                    finish()
                                }
                            }else if (type == "5"){//恢复
                                viewModel.requestGoodsCancelReq(wrstandardid = data.wrstandardid?.toLong() ?: 0,isvalid = 1){
                                    finish()
                                }
                            }
                        }
                        gravity = Gravity.CENTER
                        backgroundResource = R.mipmap.rma_submit_bg
                        if (type == "1") {
                            text = "完成"
                        } else if (type == "2") {
                            text = "修改"
                        } else if (type == "3") {
                            text = "停用"
                        } else if (type == "5") {
                            text = "恢复"
                        }
                        textColorInt = R.color.white
                        textSizeAuto = 38
                    }.lparams(matchParent, autoSize(119)) {
                        marginStart = autoSize(59)
                        marginEnd = autoSize(59)
                    }
                }.lparams(matchParent, autoSize(144)) {
                    gravity = Gravity.BOTTOM
                }
            }.lparams(matchParent, matchParent)


        }
    }

    /**
     * 型号列表
     * @return List<ManageServiceMI2.SpotGoodsModelEx>
     */
    private fun getSpotModelList(): List<ManageServiceMI2.SpotGoodsModelEx> {
        val spotgoodsmodels = arrayListOf<ManageServiceMI2.SpotGoodsModelEx>()
        viewModel.spotModelList.value?.forEach {
            val spotGoodsData = ManageServiceMI2.SpotGoodsModelEx.newBuilder()
            spotGoodsData.modelname = it.value
            spotgoodsmodels.add(spotGoodsData.build())
        }
        return spotgoodsmodels
    }

    /**
     * 品牌列表
     * @return List<ManageServiceMI2.SpotGoodsModelEx>
     */
    private fun getBrandModelList(): List<ManageServiceMI2.SpotGoodsBrandEx> {
        val brandgoodsmodels = arrayListOf<ManageServiceMI2.SpotGoodsBrandEx>()
        viewModel.brandModelList.value?.forEach {
            val spotGoodsData = ManageServiceMI2.SpotGoodsBrandEx.newBuilder()
            spotGoodsData.brandname = it.value
            brandgoodsmodels.add(spotGoodsData.build())
        }
        return brandgoodsmodels
    }

    /**
     * 套保品牌列表
     * @return List<ManageServiceMI2.SpotGoodsModelEx>
     */
    private fun getMiddleModelList(): List<ManageServiceMI2.WRSConvertDetailEx> {
        val middlegoodsmodels = arrayListOf<ManageServiceMI2.WRSConvertDetailEx>()
        viewModel.middlegoodList.value?.forEach {
            val spotGoodsData = ManageServiceMI2.WRSConvertDetailEx.newBuilder()
            spotGoodsData.middlegoodsid = it.middleGoodsId.toLong()
            spotGoodsData.convertratio = it.value.toDouble()
            middlegoodsmodels.add(spotGoodsData.build())
        }
        return middlegoodsmodels
    }

    /**
     * 提交资料前的效验
     * @return Boolean
     */
    private fun checkUpdate(): Boolean {

        if (spot_variety_name_edittext.text.toString().isNullOrEmpty()) {
            ToastUtils.showLong("请输入商品名称")
            return false
        }

        if (selectUnitType.value?.id.isNullOrEmpty()) {
            ToastUtils.showLong("请选择单位")
            return false
        }

        viewModel.spotModelList.value?.forEach {
            if (it.value.isNullOrEmpty()) {
                ToastUtils.showLong("请输入型号")
                return false
            }
        }

        viewModel.brandModelList.value?.forEach {
            if (it.value.isNullOrEmpty()) {
                ToastUtils.showLong("请输入品牌")
                return false
            }
        }

        viewModel.middlegoodList.value?.forEach {
            if (it.middleGoodsName.isNullOrEmpty()) {
                ToastUtils.showLong("请选择套保类型")
                return false
            }
            if (it.value.isNullOrEmpty()) {
                ToastUtils.showLong("请输入套保系数")
                return false
            }
        }

        return true
    }

}