package net.huansi.app.hssummarizingboard.utils

import android.graphics.Color
import baseform.android.huansi.net.log.HsLog
import baseform.android.huansi.net.model.config.AppConfig.SPKey
import baseform.android.huansi.net.request.BaseFormRequest
import baseform.android.huansi.net.request.HttpConnectPool
import baseform.android.huansi.net.request.WebResponseListener.HSException
import baseform.android.huansi.net.util.AndroidTableManager
import baseform.android.huansi.net.util.BasicVariableUtils
import baseform.android.huansi.net.util.ShareUtil
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.huansi.app.checkcloth.api.CommonApi
import net.huansi.app.hssummarizingboard.entity.*


object RequestUtils {

    private fun getCommonApi(): CommonApi {
        val ip = ShareUtil.getString(SPKey.SQL_IP_KEY, "")
        return HttpConnectPool.getInstance().getApi(ip, CommonApi::class.java)
    }

    /**
     * 请求中心统计
     */
    suspend fun requestStatisticsData(): StatisticsDataBean {
        return withContext(Dispatchers.IO) {
            val call = getCommonApi().requestStatisticsData("no_check")
            val resultSyncBean = BaseFormRequest.getInstance().requestApiSync(call)

            return@withContext JSON.parseObject(resultSyncBean.json, StatisticsDataBean::class.java)
        }
    }

    /**
     * 请求优秀区和潜能区
     */
    suspend fun requestAreaData(reportType: String): ListBean {
        return withContext(Dispatchers.IO) {
            val call = getCommonApi().requestAreaData("no_check", reportType)
            val resultSyncBean = BaseFormRequest.getInstance().requestApiSync(call)
            val array =
                resultSyncBean.json.toJSONArray(if (reportType == "excellent") "请求优秀区" else "请求潜能区")

            val list = JSON.parseArray(array.toJSONString(), AreaDataBean::class.java)

            val listBean = ListBean()
            if (list.isEmpty()) {
                listBean.pageCount = 1
                val empty = JSONArray()
                for (i in 0 until 4) {
                    empty.add(JSONArray())
                }
                listBean.contentList.add(empty)
            } else {
                val lineCountOfPage = 4//每页多少行
                val pageCount = if (list.size % 4 == 0) list.size / 4 else list.size / 4 + 1
                listBean.pageCount = pageCount

                list.forEachIndexed { index, data ->
                    val pageIndex = index / lineCountOfPage
                    val pageArray = if (pageIndex >= listBean.contentList.size) {
                        val array = JSONArray()
                        listBean.contentList.add(array)
                        array
                    } else {
                        listBean.contentList[pageIndex]
                    }

                    val lineArray = JSONArray()
                    lineArray.add(getTableColumnItem(data.task_charge_person, Color.WHITE))
                    lineArray.add(getTableColumnItem(data.group_name, Color.WHITE))
                    lineArray.add(getTableColumnItem(data.finished_hasty, getColor("#1DF2F7")))
                    lineArray.add(
                        getTableColumnItem(
                            data.on_time_finished_hasty,
                            getColor("#EEC017")
                        )
                    )
                    pageArray.add(lineArray)
                }

                //每一页需要满lineCountOfPage行，不然显示占比会改变
                if (listBean.contentList.isNotEmpty()) {
                    val emptyLineCountToAdd = lineCountOfPage - listBean.contentList.last().size
                    for (i in 0 until emptyLineCountToAdd) {
                        listBean.contentList.last().add(JSONArray())
                    }
                }
            }

            for (i in 0 until listBean.contentList.size) {
                listBean.contentList[i].add(0, getExcellenceAreaHead())
            }
            return@withContext listBean
        }
    }

    /**
     * 请求节点汇总详情
     */
    suspend fun requestProDetails(): List<ProDetailsBean> {
        return withContext(Dispatchers.IO) {
            val call = getCommonApi().requestProDetails("no_check")
            val resultSyncBean = BaseFormRequest.getInstance().requestApiSync(call)
            val array = resultSyncBean.json.toJSONArray("请求节点汇总详情")
            val list = JSON.parseArray(array.toJSONString(), ProDetailsBean::class.java)
            return@withContext list
        }
    }

    /**
     * 请求各品牌堵点
     */
    suspend fun requestBrandList(): List<BrandBean> {
        return withContext(Dispatchers.IO) {
            val call = getCommonApi().requestBrandList("no_check")
            val resultSyncBean = BaseFormRequest.getInstance().requestApiSync(call)

            val jsonObject = JSON.parseObject(resultSyncBean.json)
            val brandList: MutableList<BrandBean> = mutableListOf()
            val nameList = jsonObject.keys

            nameList.forEachIndexed { _, name ->
                brandList.add(BrandBean().apply {
                    brandName = name
                    infoList = JSON.parseArray(
                        jsonObject.getJSONArray(name).toJSONString(), BrandInfoBean::class.java
                    )
                })
            }
            return@withContext brandList.toList()
        }
    }

    /**
     * 处理产前事件详情数据
     */
    suspend fun getSummaryDetails(list: List<ProDetailsBean>): ListBean {
        return withContext(Dispatchers.IO) {
            val listBean = ListBean()
            if (list.isEmpty()) {
                listBean.pageCount = 1
                val empty = JSONArray()
                for (i in 0 until 4) {
                    empty.add(JSONArray())
                }
                listBean.contentList.add(empty)
            } else {
                val lineCountOfPage = 4//每页多少行
                val pageCount = if (list.size % 4 == 0) list.size / 4 else list.size / 4 + 1
                listBean.pageCount = pageCount

                list.forEachIndexed { index, data ->
                    val pageIndex = index / lineCountOfPage
                    val pageArray = if (pageIndex >= listBean.contentList.size) {
                        val array = JSONArray()
                        listBean.contentList.add(array)
                        array
                    } else {
                        listBean.contentList[pageIndex]
                    }

                    val lineArray = JSONArray()
                    lineArray.add(getTableColumnItem(data.job_name, Color.WHITE))
                    lineArray.add(getTableColumnItem(data.total_task, Color.WHITE))
                    lineArray.add(getTableColumnItem(data.timeout_unfinished, getColor("#F64761")))
                    lineArray.add(getTableColumnItem(data.on_time_unfinished, getColor("#11B5FF")))
                    lineArray.add(getTableColumnItem(data.on_time_finished, getColor("#70B602")))
                    lineArray.add(getTableColumnItem(data.timeout_finished, getColor("#EEC017")))
                    pageArray.add(lineArray)
                }

                //每一页需要满lineCountOfPage行，不然显示占比会改变
                if (listBean.contentList.isNotEmpty()) {
                    val emptyLineCountToAdd = lineCountOfPage - listBean.contentList.last().size
                    for (i in 0 until emptyLineCountToAdd) {
                        listBean.contentList.last().add(JSONArray())
                    }
                }
            }

            for (i in 0 until listBean.contentList.size) {
                listBean.contentList[i].add(0, getSummaryDetailsHead())
            }
            return@withContext listBean
        }
    }

    /**
     * 获取优秀区和潜能区头部
     */
    fun getExcellenceAreaHead(): JSONArray {
        val head = JSONArray()
        head.add(getTableColumnItem("姓名", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("班组", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("任务完成率", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("准时完成率", getColor("#3E93EC"), 11))
        return head
    }

    /**
     * 获取产前事件详情区头部
     */
    fun getSummaryDetailsHead(): JSONArray {
        val head = JSONArray()
        head.add(getTableColumnItem("事件名称", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("总任务", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("超时未完成", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("进行中", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("按期完成", getColor("#3E93EC"), 11))
        head.add(getTableColumnItem("超期完成", getColor("#3E93EC"), 11))
        return head
    }

    private fun getColor(color: String): Int {
        return BasicVariableUtils.parseColor(color, Color.WHITE)
    }

    private fun getTableColumnItem(text: String, textColor: Int, textSize: Int = 10): JSONObject {
        return JSONObject().apply {
            put(AndroidTableManager.TABLE_TEXT_KEY, text)
            put(AndroidTableManager.TABLE_IS_BOLD_KEY, false)
            put(AndroidTableManager.TABLE_TEXT_WEIGHT_KEY, 1)
            put(AndroidTableManager.TABLE_TEXT_BG_KEY, Color.TRANSPARENT)
            put(AndroidTableManager.TABLE_TEXT_COLOR_KEY, textColor)
            put(AndroidTableManager.TABLE_TEXT_SIZE_KEY, textSize)
            put(AndroidTableManager.TABLE_LINE_WIDTH_KEY, 0)
            put(
                AndroidTableManager.TABLE_LINE_COLOR_KEY,
                BasicVariableUtils.parseColor("#C4C4C4", Color.WHITE)
            )
        }
    }

    /**
     * 抛出空数据的异常
     */
    @Throws(HSException::class)
    private fun throwEmptyException(message: String) {
        throw HSException(message = message)
    }


}