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

import android.annotation.SuppressLint
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.ViewEnumUtils
import cn.muchinfo.rma.global.data.ContractData
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.netManage.base.InteractiveException
import cn.muchinfo.rma.netManage.utils.UpLoadUtils
import cn.muchinfo.rma.protobuf.protoclasses.ErmcpMI1
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.autoWidget.photopicter.PhotoUtils
import cn.muchinfo.rma.view.base.BaseActivity
import cn.muchinfo.rma.view.base.app.Constant
import cn.muchinfo.rma.view.base.home.contract.emptyView
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.protobuf.ByteString
import com.zhy.http.okhttp.callback.StringCallback
import mtp.polymer.com.autowidget.dialog.createLoadingDialog
import mtp.polymer.com.autowidget.utils.TaskUiModel
import mtp.polymer.com.autowidget.utils.bindTaskStatus
import okhttp3.Call
import org.jetbrains.anko.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.File

/**
 * 发票登记页面
 */
class InvoiceRegistrationActivity : BaseActivity<RegistrationViewModel>() {

    private var uploadFile: String = ""//上传成功后服务给的图片地址
    private val imageString: MutableLiveData<String> =
        MutableLiveData<String>().apply { value = "" }//文件地址

    /** 开票金额输入 **/
    lateinit var amount_edittext : EditText

    //type 为1是采购 2是销售
    private val type by lazy {
        intent.getStringExtra("type")
    }

    //传进来的数据
    private val data by lazy {
        intent.getParcelableExtra<ContractData>("data") as ContractData
    }

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

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        verticalLayout {
            dialog.bindTaskStatus(context,viewModel.loadingDialogStatus)
            val margingPadding = autoSize(47)
            background = resources.getDrawable(R.color.main_hit_bg_color)
            topBar {
                commonLeftButton()
                commonTitle {
                    text = "发票登记"
                }
            }

            frameLayout {
                scrollView {
                    verticalLayout {
                        verticalLayout {
                            background = resources.getDrawable(R.color.white)
                            textView {
                                text = "合同基本信息"
                                textColorInt = R.color.rma_blue_color
                                textSizeAuto = 34
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = margingPadding
                                topMargin = autoSize(25)
                            }

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                linearLayout {
                                    textView {
                                        text = "合同编号"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = ViewEnumUtils.getContractType(data.contracttype ?: "") + "/"
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                        textView {
                                            text = data.spotcontractid
                                            textSizeAuto = 17
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, wrapContent)

                                }.lparams(autoSize(450), wrapContent)
                                linearLayout {
                                    textView {
                                        text = if (type == "1") {
                                            "销售方"
                                        } else {
                                            "采购方"
                                        }
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = data.accountname
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent) {
                                            marginEnd = margingPadding
                                        }
                                    }.lparams(matchParent, wrapContent)
                                }.lparams(autoSize(450), wrapContent)
                            }.lparams(matchParent, autoSize(60)) {
                                topMargin = autoSize(30)
                            }

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                linearLayout {
                                    textView {
                                        text = "定价类型"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = ViewEnumUtils.getPriceType(data.pricetype ?: "")
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)

                                    }.lparams(matchParent, wrapContent)

                                }.lparams(autoSize(450), wrapContent)
                                linearLayout {
                                    textView {
                                        text = "现货品种"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = data.deliverygoodsname
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent) {
                                            marginEnd = margingPadding
                                        }
                                    }.lparams(matchParent, wrapContent)
                                }.lparams(autoSize(450), wrapContent)
                            }.lparams(matchParent, autoSize(60))


                            view {
                                background = resources.getDrawable(R.color.rma_hint_line_color_eee)
                            }.lparams(matchParent, autoSize(1)) {
                                marginStart = autoSize(36)
                                marginEnd = autoSize(36)
                                topMargin = autoSize(30)
                            }


                            textView {
                                text = "已登记信息"
                                textColorInt = R.color.rma_blue_color
                                textSizeAuto = 34
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = margingPadding
                                topMargin = autoSize(25)
                            }

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                linearLayout {
                                    textView {
                                        text = "贷款总额"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = data.loanamount
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                        textView {
                                            text = "元"
                                            textSizeAuto = 17
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, wrapContent)

                                }.lparams(autoSize(450), wrapContent)
                                linearLayout {
                                    textView {
                                        text = "合计总额"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = data.totalamount
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                        textView {
                                            text = "元"
                                            textSizeAuto = 17
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent){
                                            marginEnd = margingPadding
                                        }
                                    }.lparams(matchParent, wrapContent)
                                }.lparams(autoSize(450), wrapContent)
                            }.lparams(matchParent, autoSize(60)) {
                                topMargin = autoSize(25)
                            }

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                linearLayout {
                                    textView {
                                        text = "保证金"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = data.margin
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                        textView {
                                            text = "元"
                                            textSizeAuto = 17
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                    }.lparams(matchParent, wrapContent)

                                }.lparams(autoSize(450), wrapContent)
                                linearLayout {
                                    textView {
                                        text = "已收款"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = data.payamount
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)
                                        textView {
                                            text = "元"
                                            textSizeAuto = 17
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent){
                                            marginEnd = margingPadding
                                        }
                                    }.lparams(matchParent, wrapContent)
                                }.lparams(autoSize(450), wrapContent)
                            }.lparams(matchParent, autoSize(60)) {
                                topMargin = autoSize(10)
                            }

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                linearLayout {
                                    textView {
                                        text = "其他费用"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = "500000元"
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)

                                    }.lparams(matchParent, wrapContent)

                                }.lparams(autoSize(450), wrapContent)
                                linearLayout {
                                    textView {
                                        text = "已开票额"
                                        textColorInt = R.color.p_normal_summary_txt_color
                                        textSizeAuto = 29
                                    }.lparams(wrapContent, wrapContent) {
                                        marginStart = margingPadding
                                    }

                                    linearLayout {
                                        emptyView()
                                        textView {
                                            text = data.invoiceamount
                                            textSizeAuto = 29
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent)

                                        textView {
                                            text = "元"
                                            textSizeAuto = 17
                                            textColorInt = R.color.rma_black_33
                                        }.lparams(wrapContent, wrapContent){
                                            marginEnd = margingPadding
                                        }
                                    }.lparams(matchParent, wrapContent)
                                }.lparams(autoSize(450), wrapContent)
                            }.lparams(matchParent, autoSize(60)) {
                                topMargin = autoSize(10)
                                bottomMargin = autoSize(40)
                            }

                        }.lparams(matchParent, wrapContent)

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

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                textView {
                                    text = "本次点价信息"
                                    textColorInt = R.color.rma_blue_color
                                    textSizeAuto = 34
                                }.lparams(wrapContent, wrapContent) {
                                    marginStart = autoSize(36)
                                }

                                imageView {
                                    onThrottleFirstClick {
                                        showPopups(context = context,textString = "待开票额=货款总额+其他费用-已开发票额",v = this)
                                    }
                                    imageResource = R.mipmap.rma_zhushi
                                }.lparams(autoSize(36), autoSize(36)){
                                    marginStart = autoSize(29)
                                }
                            }.lparams(matchParent, autoSize(60)){
                                topMargin = autoSize(36)
                            }

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                textView {
                                    text = "开票金额"
                                    textSizeAuto = 31
                                    textColorInt = R.color.rma_black_33
                                }.lparams(wrapContent, wrapContent){
                                    marginStart = autoSize(36)
                                }


                                linearLayout {
                                    background = resources.getDrawable(R.drawable.rma_item_click_bg)

                                    editText {
                                        amount_edittext = this
                                        setPadding(0, 10, 0, 0)
                                        setSingleLine(true)
                                        gravity = Gravity.CENTER
                                        hint = "0.00"
                                        background = null
                                        inputType = EditorInfo.TYPE_CLASS_NUMBER
                                        setDecimalInputType()
                                        hintColorStr = "#CCCCCC"
                                        textSizeAuto = 31
                                        textColorStr = "#333333"
                                    }.lparams(matchParent, matchParent) {

                                    }
                                }.lparams(autoSize(432), autoSize(72)) {
                                    marginStart = autoSize(80)
                                }

                                textView {
                                    text = "元"
                                    textSizeAuto = 29
                                    textColorInt = R.color.rma_black_33
                                }.lparams(wrapContent, wrapContent) {
                                    marginStart = autoSize(28)
                                }
                            }.lparams(matchParent, autoSize(80)){
                                topMargin = autoSize(20)
                            }

                            linearLayout {
                                textView {
                                    text = "待开票金额："
                                    textColorInt = R.color.text_hit_color
                                    textSizeAuto = 29
                                }.lparams(wrapContent, wrapContent){
                                    marginStart = autoSize(240)
                                }

                                textView {
                                    text = ((data.loanamount?.toDouble() ?: 0.0).minus(data.reckonotheramount?.toDouble() ?: 0.0).minus(data.invoiceamount?.toDouble() ?: 0.0)).toString()
                                    textSizeAuto = 29
                                    textColorInt = R.color.rma_blue_color
                                }.lparams(wrapContent, wrapContent){
                                    marginStart = autoSize(15)
                                }


                            }.lparams(matchParent, wrapContent){
                                topMargin = autoSize(10)
                            }

                            textView {
                                text = "全部登记"
                                textSizeAuto = 29
                                textColorInt = R.color.rma_green_color
                            }.lparams(wrapContent, wrapContent){
                                marginStart = autoSize(240)
                                topMargin = autoSize(10)
                            }

                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL
                                textView {
                                    text = "发票附件"
                                    textColorInt = R.color.rma_black_33
                                    textSizeAuto = 31
                                }.lparams(wrapContent, wrapContent){
                                    marginStart = autoSize(36)
                                }

                                textView {
                                    onThrottleFirstClick {
                                        if (imageString.value.isNullOrEmpty()){
                                            PhotoUtils().showPicker(this@InvoiceRegistrationActivity) {
                                                it.firstOrNull()?.let {
                                                    viewModel.loadingDialogStatus.value =
                                                        TaskUiModel.inFlight()
                                                    UpLoadUtils(this@InvoiceRegistrationActivity).uploadPicture(
                                                        File(it),
                                                        object : StringCallback() {
                                                            override fun onError(
                                                                call: Call,
                                                                e: Exception,
                                                                id: Int
                                                            ) {
                                                                LogUtils.e("hidahdashdsdasd", e.message)
                                                                viewModel.loadingDialogStatus.value =
                                                                    TaskUiModel.failed(
                                                                        InteractiveException(
                                                                            errorMessage = e.message ?: ""
                                                                        )
                                                                    )
                                                            }

                                                            override fun onResponse(
                                                                response: String,
                                                                id: Int
                                                            ) {
                                                                /*[{"originalName":"tem.jpg","fileName":"201907161657044712.jpg","fileSize":"0KB","fileType":"image/jpeg","filePath":"./uploadFile/20190716/201907161657044712.jpg","submitName":null}]*/
                                                                try {
                                                                    viewModel.loadingDialogStatus.value =
                                                                        TaskUiModel.success(msg = "附件选择成功")
                                                                    val jsonArray = JSONArray(response)
                                                                    LogUtils.eTag(
                                                                        "图片",
                                                                        JSON.toJSONString(jsonArray)
                                                                    )
                                                                    for (i in 0 until jsonArray.length()) {
                                                                        uploadFile =
                                                                            (jsonArray.get(i) as JSONObject).getString(
                                                                                "filePath"
                                                                            )
                                                                        imageString.value = it
                                                                        LogUtils.e("hidahdashd", uploadFile)
                                                                    }
                                                                } catch (e: JSONException) {
                                                                    e.printStackTrace()
                                                                }
                                                            }
                                                        },
                                                        10000.0,
                                                        SPUtils.getInstance().getString(Constant.uploadUrl)
                                                    )
                                                }
                                            }
                                        }else{
                                            val path = imageString.value.guard {
                                                return@onThrottleFirstClick
                                            }
                                            PhotoUtils().showImageViewer(this@InvoiceRegistrationActivity, 1, arrayListOf(path))
                                        }
                                    }
                                    backgroundDrawable = createRoundRectDrawable("#DAEDFF", 25)
                                    gravity = Gravity.CENTER
                                    imageString.bindOptional(context) {
                                        if (it?.isNotEmpty() == true) {
                                            text = "查看附件"
                                        }
                                    }
                                    text = "上传附件"
                                    textColorInt = R.color.rma_blue_color
                                    textSizeAuto = 31
                                }.lparams(autoSize(180), autoSize(54)){
                                    marginStart = autoSize(80)
                                }
                            }.lparams(matchParent, autoSize(80)){
                                topMargin = autoSize(40)
                                bottomMargin = autoSize(40)
                            }
                        }.lparams(matchParent, wrapContent) {
                            marginStart = autoSize(24)
                            marginEnd = autoSize(24)
                            topMargin = autoSize(24)
                            bottomMargin = autoSize(200)
                        }
                    }.lparams(autoSize(900), matchParent)
                }

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

                    textView {
                        onThrottleFirstClick {
                            if (checkUpdate().not()){
                                return@onThrottleFirstClick
                            }
                            viewModel.orderPerationContract(info = getPerationContractInfo(),operateType = 1){
                                finish()
                            }
                        }
                        gravity = Gravity.CENTER
                        backgroundResource = R.mipmap.rma_submit_bg
                        text = "发票登记"
                        textColorInt = R.color.white
                        textSizeAuto = 38
                    }.lparams(autoSize(780), autoSize(119)) {
                        marginStart = autoSize(59)
                    }

                }.lparams(matchParent, autoSize(144)) {
                    gravity = Gravity.BOTTOM
                }
            }.lparams(matchParent, matchParent)
        }

    }

    /**
     * 获取合同操作info
     * @return ErmcpMI1.ContractOperateApplyInfo
     */
    private fun getPerationContractInfo(): ErmcpMI1.ContractOperateApplyInfo {
        val json = JSONObject()
        json.put("InvoiceAmount",amount_edittext.text.toString().toDouble())
        val contractInfobuilder = ErmcpMI1.ContractOperateApplyInfo.newBuilder()

        contractInfobuilder.relatedID = data.spotcontractid?.toLong() ?: 0// 现货合同ID
        contractInfobuilder.operateApplyType = 4//款项
        contractInfobuilder.detailJson = ByteString.copyFrom(json.toString().toByteArray())

        return contractInfobuilder.build()
    }

    /**
     * 提交信息前的效验
     * @return Boolean
     */
    private fun checkUpdate(): Boolean{
        if (amount_edittext.text.toString().isNullOrEmpty()){
            ToastUtils.showLong("请输入开票金额!")
            return false
        }

        return true
    }
}