package com.gh.gamecenter.servers.add

import android.app.Activity
import android.app.Application
import android.os.Build
import android.text.Html
import android.text.Spanned
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils.toast
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import retrofit2.HttpException

class AddKaiFuViewModel(application: Application) : AndroidViewModel(application) {

    val calendarList = ArrayList<ServerCalendarEntity>()
    val postResult = MutableLiveData<ArrayList<ServerCalendarEntity>>()

    private var mAllKaifuList = ArrayList<ServerCalendarEntity>()

    private var mGameId = ""

    fun initData(entity: ServerCalendarEntity?, allKaifuList: ArrayList<ServerCalendarEntity>, gameId: String) {
        mAllKaifuList = allKaifuList
        mGameId = gameId
        val text = entity?.getNote()
        if (!text.isNullOrEmpty()) {
            var firstName = ""
            var serverName = ""
            var str: Array<String> = text.split("︱".toRegex()).toTypedArray()
            if (str.size == 1) {
                str = text.split("\\|".toRegex()).toTypedArray()
                if (str.size == 1) {
                    serverName = text
                } else {
                    firstName = str[0].trim()
                    serverName = str[1].trim()
                }
            } else {
                firstName = str[0].trim()
                serverName = str[1].trim()
            }
            entity.setFirstName(getColorPlusText(firstName))
            entity.setServerName(getColorPlusText(serverName))
        }
        if (entity != null) calendarList.add(entity)
        for (i in 0 until 5) {
            calendarList.add(ServerCalendarEntity())
        }
    }

    fun getColorPlusText(str: String): Spanned {
        val plus = String.format("<font color='#2496FF'>%1\$s</font>", "&nbsp+")
        val name = String.format("<font color='#B3B3B3'>%1\$s</font>", str)
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            Html.fromHtml(name + plus, Html.FROM_HTML_MODE_LEGACY)
        else
            Html.fromHtml(name + plus)
    }

    fun bluePlus(): Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) Html.fromHtml(
        String.format(
            "<font color='#2496FF'>%1\$s</font>",
            "&nbsp+"
        ), Html.FROM_HTML_MODE_LEGACY
    ) else Html.fromHtml(String.format("<font color='#2496FF'>%1\$s</font>", "&nbsp+"))

    fun copyTimeToNext() {
        for (i in 0 until calendarList.size) {
            if (i != calendarList.size - 1 && calendarList[i].getTime() != 0L && calendarList[i + 1].getTime() == 0L) {
                calendarList[i + 1].setTime(calendarList[i].getTime())
                break
            }
        }
    }

//    fun copyNameToNext() {
//        for (i in 0 until calendarList.size) {
//            if (i != calendarList.size - 1 && !calendarList[i].getNote().isNullOrEmpty() && calendarList[i + 1].getNote().isNullOrEmpty()) {
//                val compile = Pattern.compile("^.*?(\\d+)[^\\d]*$")
//                var note = calendarList[i].getNote()
//                val m = compile.matcher(note)
//                if (m.find()) {
//                    val group = m.group(1).toInt()
//                    note = note?.replace(group.toString(), (group + 1).toString()) // todo 替换最后出现的数字(有可能出现两次相同)
//                }
//                if (!note.isNullOrEmpty() && "+" == note?.get(note.length - 1).toString()) {
//                    note = note!!.substring(0, note.length - 1)
//                }
//                calendarList[i + 1].setNote(note)
//                break
//            }
//        }
//    }

    fun copyLastFirstNameToNext() {
        for (i in 0 until calendarList.size) {
            if (i != calendarList.size - 1 && !calendarList[i].getFirstName()
                    .isNullOrEmpty() && calendarList[i + 1].getFirstName().isNullOrEmpty()
            ) {
                var firstName = calendarList[i].getFirstName().toString()
                if (firstName.isNotEmpty() && "+" == firstName[firstName.length - 1].toString()) {
                    firstName = firstName.substring(0, firstName.length - 2)
                }
                calendarList[i + 1].setFirstName(firstName)
                break
            }
        }
    }

    fun copyLastFirstAndServerNameToNext() {
        for (i in 0 until calendarList.size) {
            if (i != calendarList.size - 1 && !calendarList[i].getServerName()
                    .isNullOrEmpty() && calendarList[i + 1].getServerName().isNullOrEmpty()
            ) {
                var firstName = calendarList[i].getFirstName().toString()
                var serverName = calendarList[i].getServerName().toString()
                val pattern = "[0-9]+(?=[^0-9]*\$)"
                val number = Regex(pattern).find(serverName)?.value
                if (!number.isNullOrEmpty()) {
                    val newNum = (number.toInt() + 1).toString()
                    serverName = serverName.replace(number, newNum)
                }
                if (serverName.isNotEmpty() && "+" == serverName[serverName.length - 1].toString()) {
                    serverName = serverName.substring(0, serverName.length - 2)
                }
                if (firstName.isNotEmpty() && "+" == firstName[firstName.length - 1].toString()) {
                    firstName = firstName.substring(0, firstName.length - 2)
                }
                calendarList[i + 1].setFirstName(firstName)
                calendarList[i + 1].setServerName(serverName)
                break
            }
        }
    }

    fun post(activity: Activity) {
        var isSuccess = true
//        for (entity in calendarList) {
//            if (!TextUtils.isEmpty(entity.getNote())) {
//                entity.setNote(entity.getNote()?.trim())
//            }
//        }

        // 初始化标红提示
        for (i in 1 until calendarList.size) {
            calendarList[i].setDataMark(0)
        }

        for (i in 1 until calendarList.size) {
            val entity = calendarList[i]
            if (entity.getTime() != 0L || !entity.getFirstName()?.trim().isNullOrEmpty() || !entity.getServerName()
                    ?.trim().isNullOrEmpty()
            ) {
                break
            }
            if (i == calendarList.size - 1) {
                toast(getApplication(), "内容为空，不能提交")
                return
            }
        }

//        for (i in 1 until calendarList.size) {
//            val entity = calendarList[i]
//            if (!entity.getFirstName().isNullOrEmpty() && entity.getTime() == 0L && entity.getServerName().isNullOrEmpty()) {
//                entity.setDataMark(4)
//                isSuccess = false
//            }
//            if (i == calendarList.size - 1 && !isSuccess) {
//                toast(getApplication(), "必须填写时间和服务器名称")
//                return
//            }
//        }
//
//        for (i in 1 until calendarList.size) {
//            val entity = calendarList[i]
//            if (entity.getTime() != 0L && entity.getNote().isNullOrEmpty() || entity.getTime() == 0L && !entity.getNote().isNullOrEmpty()) {
//                isSuccess = false
//                entity.setDataMark(if (entity.getTime() != 0L) 2 else 1)
//            }
//            if (i == calendarList.size - 1 && !isSuccess) {
//                toast(getApplication(), "时间和名字必须同时填写")
//                return
//            }
//        }

        for (i in 1 until calendarList.size) {
            val entity = calendarList[i]
            if (entity.getTime() == 0L || entity.getFirstName()?.trim().isNullOrEmpty() || entity.getServerName()
                    ?.trim().isNullOrEmpty()
            ) {
                entity.setNote("")
                break
            } else {
                val note = entity.getFirstName().toString().trim() + " | " + entity.getServerName().toString().trim()
                entity.setNote(note)
                entity.remark = "新服"
            }
        }

        val listJson = GsonUtils.toJson(calendarList)
        for (i in 1 until calendarList.size) {
            val entity = calendarList[i]
            if (entity.getTime() != 0L && !entity.getNote().isNullOrEmpty()) {
                val splitTime = listJson.split("\"time\":" + entity.getTime().toString())
                val splitName = listJson.split("\"note\":" + "\"" + entity.getNote()!! + "\"")
                if (splitTime.size > 2 && splitName.size > 2) {
                    isSuccess = false
                    entity.setDataMark(4)
                }
            }
            if (i == calendarList.size - 1 && !isSuccess) {
                toast(getApplication(), "内容重复，请检查修改")
                return
            }
        }

        for (i in 1 until calendarList.size) {
            val entity = calendarList[i]
            for (allEntity in mAllKaifuList) {
                if (entity.getTime() == allEntity.getTime() && entity.getNote() == allEntity.getNote()?.trim()) {
                    isSuccess = false
                    entity.setDataMark(4)
                }
            }
            if (i == calendarList.size - 1 && !isSuccess) {
                DialogHelper.showDialog(
                    activity,
                    "提示",
                    "当前开服表中已经存在相同的内容，请检查修改",
                    "返回修改",
                    "",
                    extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                )
                return
            }
        }

        val postList = ArrayList<ServerCalendarEntity>()
        for (i in 1 until calendarList.size) {
            if (calendarList[i].getTime() != 0L && !calendarList[i].getNote().isNullOrEmpty())
                postList.add(calendarList[i]) // filter empty data and default data
        }
        if (postList.size == 0) {
            toast(getApplication(), "内容为空，不能提交")
            return
        }
        DialogHelper.showDialog(
            activity,
            "提示",
            "确定提交${postList.size}条开服信息吗？",
            "确定",
            "返回",
            { postData(postList) },
            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }


    private fun postData(postList: ArrayList<ServerCalendarEntity>) {
        val body = RequestBody.create(MediaType.parse("application/json"), GsonUtils.toJson(postList))
        RetrofitManager.getInstance().api.addKaifu(body, mGameId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<String>>() {
                override fun onResponse(response: List<String>?) {
                    if (response != null) {
                        for (i in response.indices) {
                            postList[i].id = response[i]
                        }
                    }
                    postResult.postValue(postList)
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    postResult.postValue(null)
                }
            })
    }
}
