package com.pan_american.android.ui.customer_resource.market_sales_revenue

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.entity.QuarterlyMonthData
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.entity.YearQuarterlyData
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesStatisticsCustomerRequest
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesStatisticsCustomerResponse
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesStatisticsRequest
import com.pan_american.android.data.model.customer_resource.market_sales_revenue.network.MarketSalesStatisticsResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentSalesRevenueTotalBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.Calendar

class SalesRevenueTotalFragment : BaseFragment<FragmentSalesRevenueTotalBinding>() {

    private companion object {
        val MATERIAL_COLOR_LIST = listOf(
            Color.parseColor("#3F51B5"), Color.parseColor("#8BC34A"), Color.parseColor("#FF9800"),
            Color.parseColor("#F44336"), Color.parseColor("#03A9F4"), Color.parseColor("#009688"),
            Color.parseColor("#FFEB3B"), Color.parseColor("#E91E63"), Color.parseColor("#00BCD4"),
            Color.parseColor("#CDDC39"), Color.parseColor("#FF5722"), Color.parseColor("#FF5722"))
    }

    private val monthMap = mapOf(1 to "一月", 2 to "二月", 3 to "三月", 4 to "四月", 5 to "五月", 6 to "六月", 7 to "七月", 8 to "八月", 9 to "九月", 10 to "十月", 11 to "十一月", 12 to "十二月")

    private val apiService = ServiceCreator.create<APIService>()

    private var yearStartDate = ""

    private var yearEndDate = ""

    private var quarterlyStartDate = ""

    private var quarterlyEndDate = ""

    private var monthStartDate = ""

    private var monthEndDate = ""

    private var marketSalesStatisticsRequest = MarketSalesStatisticsRequest()

    private var year = 0

    private var month = 0

    private var quarterList = ArrayList<QuarterlyMonthData>()

    private var monthList = ArrayList<QuarterlyMonthData>()

    private var sellerList = ArrayList<Selector>()

    private var isInit = true

    private var pieChartNeedRefresh = true

    private var companyId = 0

    private var sellerId = 0

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        bundle: Bundle?
    ) = FragmentSalesRevenueTotalBinding.inflate(layoutInflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if (isInit) {

            val calendar = Calendar.getInstance()

            year = calendar.get(Calendar.YEAR)

            for (item in OASystem.marketSalesRevenueDateList) {
                if (year == item.year) {
                    quarterList = item.quarterData
                }
            }

            binding.year.text = year.toString()

            yearStartDate = "$year-01-01"
            yearEndDate = "$year-12-31"

            month = calendar.get(Calendar.MONTH) + 1

            when(month) {
                in 1.. 3 -> {
                    quarterlyStartDate = getFirstDayOfMonth(year, 1)
                    quarterlyEndDate = getLastDayOfMonth(year, 3)

                    for (item in quarterList) {
                        if (resources.getString(R.string.first_quarter) == item.name) {
                            monthList = item.monthData
                        }
                    }

                    binding.quarterly.text = resources.getString(R.string.first_quarter)
                }

                in 4 .. 6 -> {
                    quarterlyStartDate = getFirstDayOfMonth(year, 4)
                    quarterlyEndDate = getLastDayOfMonth(year, 6)

                    for (item in quarterList) {
                        if (resources.getString(R.string.second_quarter) == item.name) {
                            monthList = item.monthData
                        }
                    }

                    binding.quarterly.text = resources.getString(R.string.second_quarter)
                }

                in 7 .. 9 -> {
                    quarterlyStartDate = getFirstDayOfMonth(year, 7)
                    quarterlyEndDate = getLastDayOfMonth(year, 9)

                    for (item in quarterList) {
                        if (resources.getString(R.string.third_quarter) == item.name) {
                            monthList = item.monthData
                        }
                    }

                    binding.quarterly.text = resources.getString(R.string.third_quarter)
                }

                in 10 .. 12 -> {
                    quarterlyStartDate = getFirstDayOfMonth(year, 10)
                    quarterlyEndDate = getLastDayOfMonth(year, 12)

                    for (item in quarterList) {
                        if (resources.getString(R.string.forth_quarter) == item.name) {
                            monthList = item.monthData
                        }
                    }

                    binding.quarterly.text = resources.getString(R.string.forth_quarter)
                }
            }

            monthStartDate = getFirstDayOfMonth(year, month)
            monthEndDate = getLastDayOfMonth(year, month)

            binding.month.text = monthMap[month]

            for (item in OASystem.marketSalesRevenueCompanyList) {
                if (OASystem.userInfo.companyName == item.name) {
                    companyId = item.id

                }
            }

            binding.companyName.text = OASystem.userInfo.companyName

            for (item in OASystem.marketSalesRevenueUserList) {
                if (marketSalesStatisticsRequest.companyId == item.companyId) {
                    sellerList.add(item)
                }
            }

            binding.seller.text = OASystem.userInfo.cnName

            sellerId = OASystem.userInfo.userId

            initViews()

            isInit = false
        }
        initEvents()
    }

    override fun initViews() {
        //二次验证
        var haveAuthorization = false

        for (item in OASystem.marketSalesRevenueUserList) {
            if (OASystem.userInfo.userId == item.id) {
                haveAuthorization = true
            }
        }

        if (haveAuthorization) {
            getYearSalesStatistics()
        } else {
            showMessage(resources.getString(R.string.permission_denied))
        }

        if (OASystem.userInfo.userId == 258 || OASystem.userInfo.userId == 21) {
            binding.siftMenu.visibility = View.VISIBLE
        }

    }

    override fun initEvents() {

        binding.companyName.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(OASystem.marketSalesRevenueCompanyList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (binding.companyName.text == data.name) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                    override fun onItemClick(position: Int) {

                        OASystem.marketSalesRevenueCompanyList[position].apply {
                            if (name != binding.companyName.text) {
                                binding.companyName.text = name

                                companyId = id

                                sellerList.clear()

                                for (item in OASystem.marketSalesRevenueUserList) {
                                    if (item.companyId == id) {
                                        sellerList.add(item)
                                    }
                                }

                                if (sellerList.size > 0) {
                                    marketSalesStatisticsRequest.groupPickupUserId = sellerList[0].id
                                } else {
                                    sellerList.add(Selector().apply {
                                        name = resources.getString(R.string.all)
                                        id = -1
                                    })
                                }

                                binding.seller.text = sellerList[0].name
                                sellerId = sellerList[0].id
                            }
                        }

                        pieChartNeedRefresh = true

                        getYearSalesStatistics()

                        popupWindow.dismiss()
                    }
                }
            }
        }

        binding.seller.setOnClickListener {
            if (sellerList.size > 0) {
                showSelector {
                    val adapter = ListAdapter.Builder<Selector>().apply {
                        setData(sellerList)
                        setLayoutId(R.layout.item_selector)
                        addBindView { itemView, data ->
                            itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                                text = data.name

                                if (binding.seller.text == data.name) {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                                } else {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                                }
                            }
                        }
                    }.create()

                    selector.adapter = adapter

                    adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            sellerList[position].apply {
                                if (name != binding.seller.text) {
                                    binding.seller.text = name
                                    sellerId = id
                                }
                            }

                            pieChartNeedRefresh = true

                            getYearSalesStatistics()

                            popupWindow.dismiss()
                        }
                    }
                }
            }
        }

        binding.year.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<YearQuarterlyData>().apply {
                    setData(OASystem.marketSalesRevenueDateList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.year.toString()

                            if (year == data.year) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<YearQuarterlyData> {
                    override fun onItemClick(position: Int) {

                        if (year != OASystem.marketSalesRevenueDateList[position].year) {
                            year = OASystem.marketSalesRevenueDateList[position].year

                            month = 1

                            binding.year.text = year.toString()

                            yearStartDate = "$year-01-01"
                            yearEndDate = "$year-12-31"

                            quarterList = OASystem.marketSalesRevenueDateList[position].quarterData

                            if (quarterList.size > 0) {

                                quarterlyStartDate = getFirstDayOfMonth(year, 1)
                                quarterlyEndDate = getLastDayOfMonth(year, 3)
                                binding.quarterly.text = resources.getString(R.string.first_quarter)

                                monthStartDate = getFirstDayOfMonth(year, month)
                                monthEndDate = getLastDayOfMonth(year, month)
                                binding.month.text = monthMap[1]

                                pieChartNeedRefresh = true

                                getYearSalesStatistics()

                                popupWindow.dismiss()
                            }
                        }
                    }
                }
            }
        }

        binding.quarterly.setOnClickListener {
            val selectList = quarterList.subList(1, quarterList.size).toList()
            showSelector {
                val adapter = ListAdapter.Builder<QuarterlyMonthData>().apply {
                    setData(selectList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (binding.quarterly.text == data.name) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<QuarterlyMonthData> {
                    override fun onItemClick(position: Int) {

                        if (binding.quarterly.text != selectList[position].name) {

                            binding.quarterly.text = selectList[position].name

                            monthList = selectList[position].monthData

                            quarterlyStartDate = monthList[0].beginDt
                            quarterlyEndDate = monthList[0].endDt

                            if (monthList.size > 0) {

                                monthStartDate = monthList[1].beginDt
                                monthEndDate = monthList[1].endDt
                                binding.month.text = monthList[1].name

                                getQuarterlySalesStatistics()

                                popupWindow.dismiss()
                            }
                        }
                    }
                }
            }
        }

        binding.month.setOnClickListener {
            val selectList = monthList.subList(1, monthList.size).toList()
            showSelector {
                val adapter = ListAdapter.Builder<QuarterlyMonthData>().apply {
                    setData(selectList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (binding.month.text == data.name) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<QuarterlyMonthData> {
                    override fun onItemClick(position: Int) {

                        if (binding.month.text != selectList[position].name) {

                            binding.month.text = selectList[position].name

                            monthStartDate = selectList[position].beginDt
                            monthEndDate = selectList[position].endDt

                            getMonthSalesStatistics()

                            popupWindow.dismiss()
                        }
                    }
                }
            }
        }
    }

    private fun getYearSalesStatistics() {

        if (!isAdded) {
            return
        }

        marketSalesStatisticsRequest.beginDt = yearStartDate
        marketSalesStatisticsRequest.endDt = yearEndDate

        marketSalesStatisticsRequest.companyId = companyId
        marketSalesStatisticsRequest.groupPickupUserId = sellerId

        apiService.getMarketSalesStatistics(marketSalesStatisticsRequest).enqueue(object : Callback<MarketSalesStatisticsResponse> {
            override fun onResponse(
                marketSalesStatisticsRequest: Call<MarketSalesStatisticsResponse>,
                response: Response<MarketSalesStatisticsResponse>
            ) {
                val yearSalesResponse = response.body()

                if (yearSalesResponse != null) {
                    if (yearSalesResponse.code == 200) {

                        binding.yearLoading.visibility = View.GONE
                        binding.yearTitle.visibility = View.VISIBLE
                        binding.yearDetail.visibility = View.VISIBLE

                        binding.yearTotalRevenue.text = String.format(resources.getString(R.string.price_format), yearSalesResponse.data.thisYearSales)
                        binding.yearYoy.text = String.format(resources.getString(R.string.percentage_format), yearSalesResponse.data.yoy)

                        binding.yearInfo.background = if (yearSalesResponse.data.yoy > 0) {
                            ResourcesCompat.getDrawable(resources, R.drawable.shape_corner_rise, null)
                        } else {
                            ResourcesCompat.getDrawable(resources, R.drawable.shape_corner_decline, null)
                        }

                        getQuarterlySalesStatistics()

                    } else {
                        showMessage(yearSalesResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<MarketSalesStatisticsResponse>, p1: Throwable) {
                showErrorInfo(R.string.year_yoy_get_error)
            }
        })
    }

    private fun getQuarterlySalesStatistics() {

        if (!isAdded) {
            return
        }

        marketSalesStatisticsRequest.beginDt = quarterlyStartDate
        marketSalesStatisticsRequest.endDt = quarterlyEndDate

        apiService.getMarketSalesStatistics(marketSalesStatisticsRequest).enqueue(object : Callback<MarketSalesStatisticsResponse> {
            override fun onResponse(
                marketSalesStatisticsRequest: Call<MarketSalesStatisticsResponse>,
                response: Response<MarketSalesStatisticsResponse>
            ) {
                val quarterlySalesStatistics = response.body()

                if (quarterlySalesStatistics != null) {
                    if (quarterlySalesStatistics.code == 200) {

                        binding.quarterLoading.visibility = View.GONE
                        binding.quarterTitle.visibility = View.VISIBLE
                        binding.quarterDetail.visibility = View.VISIBLE

                        binding.quarterlyTotalRevenue.text = String.format(resources.getString(R.string.price_format), quarterlySalesStatistics.data.thisYearSales)
                        binding.quarterlyYoy.text = String.format(resources.getString(R.string.percentage_format), quarterlySalesStatistics.data.yoy)

                        binding.quarterInfo.background = if (quarterlySalesStatistics.data.yoy > 0) {
                            ResourcesCompat.getDrawable(resources, R.drawable.shape_corner_rise, null)
                        } else {
                            ResourcesCompat.getDrawable(resources, R.drawable.shape_corner_decline, null)
                        }

                        getMonthSalesStatistics()

                    } else {
                        showMessage(quarterlySalesStatistics.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<MarketSalesStatisticsResponse>, p1: Throwable) {
                showErrorInfo(R.string.year_yoy_get_error)
            }
        })
    }

    private fun getMonthSalesStatistics() {

        if (!isAdded) {
            return
        }

        marketSalesStatisticsRequest.beginDt = monthStartDate
        marketSalesStatisticsRequest.endDt = monthEndDate

        apiService.getMarketSalesStatistics(marketSalesStatisticsRequest).enqueue(object : Callback<MarketSalesStatisticsResponse> {
            override fun onResponse(
                marketSalesStatisticsRequest: Call<MarketSalesStatisticsResponse>,
                response: Response<MarketSalesStatisticsResponse>
            ) {
                val monthlySalesStatistics = response.body()

                if (monthlySalesStatistics != null) {
                    if (monthlySalesStatistics.code == 200) {

                        binding.monthLoading.visibility = View.GONE
                        binding.monthTitle.visibility = View.VISIBLE
                        binding.monthDetail.visibility = View.VISIBLE

                        binding.monthTotalRevenue.text = String.format(resources.getString(R.string.price_format), monthlySalesStatistics.data.thisYearSales)
                        binding.monthYoy.text = String.format(resources.getString(R.string.percentage_format), monthlySalesStatistics.data.yoy)

                        binding.monthInfo.background = if (monthlySalesStatistics.data.yoy > 0) {
                            ResourcesCompat.getDrawable(resources, R.drawable.shape_corner_rise, null)
                        } else {
                            ResourcesCompat.getDrawable(resources, R.drawable.shape_corner_decline, null)
                        }

                        if (pieChartNeedRefresh) {
                            initCustomerTypePieChart()
                            pieChartNeedRefresh = false
                        }

                    } else {
                        showMessage(monthlySalesStatistics.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<MarketSalesStatisticsResponse>, p1: Throwable) {
                showErrorInfo(R.string.year_yoy_get_error)
            }
        })
    }

    private fun initCustomerTypePieChart() {

        if (!isAdded) {
            return
        }

        val marketSalesStatisticsCustomerRequest = MarketSalesStatisticsCustomerRequest(1)

        marketSalesStatisticsCustomerRequest.beginDt = yearStartDate
        marketSalesStatisticsCustomerRequest.endDt = yearEndDate

        marketSalesStatisticsCustomerRequest.companyId = companyId
        marketSalesStatisticsCustomerRequest.groupPickupUserId = sellerId

        apiService.getMarketSalesRevenueCustomerStatistics(marketSalesStatisticsCustomerRequest).enqueue(object : Callback<MarketSalesStatisticsCustomerResponse> {
            override fun onResponse(
                marketSalesStatisticsCustomerResponse: Call<MarketSalesStatisticsCustomerResponse>,
                response: Response<MarketSalesStatisticsCustomerResponse>
            ) {
                val customerTypeResponse = response.body()

                if (customerTypeResponse != null) {
                    if (customerTypeResponse.code == 200) {

                        val customerTypeList = ArrayList<PieEntry>()

                        var count = 0

                        for (item in customerTypeResponse.data) {
                            customerTypeList.add(PieEntry(item.count.toFloat(), item.name))
                            count += item.count
                        }

                        var isEmpty = false

                        if (customerTypeList.size == 0) {
                            customerTypeList.add(PieEntry(100F, resources.getString(R.string.none)))
                            isEmpty = true
                        }

                        val customFormatter = object : ValueFormatter() {
                            override fun getFormattedValue(value: Float): String {
                                val itemValue = value.toInt()

                                val percentage = itemValue / count.toDouble() * 100

                                val percentageString = String.format(resources.getString(R.string.percentage_format), percentage)

                                return if (!isEmpty) {
                                    String.format(resources.getString(R.string.currency_name_code_format), itemValue.toString(), percentageString)
                                } else {
                                    String.format(resources.getString(R.string.price_and_currency_format), 0, "0.00%")
                                }
                            }
                        }

                        val typePieDataSet = PieDataSet(customerTypeList, "").apply {
                            //设置各个数据的颜色
                            colors = if (!isEmpty) {
                                MATERIAL_COLOR_LIST
                            } else {
                                listOf(Color.parseColor("#9E9E9E"))
                            }
                            valueTextSize = 10F
                            valueTextColor = Color.WHITE
                            valueFormatter = customFormatter
                            xValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
                            //设置描述连接线长度
                            //valueLinePart1Length = 0.2f
                            //设置数据的位置
                            yValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
                            //设置数据连接线长度
                            //valueLinePart2Length = 0.2f
                            //设置两根连接线的颜色
                            //valueLineColor = Color.GRAY
                            //设置数据的字体大小
                            valueTextSize = 10F
                        }

                        binding.customerTypeChart.apply {
                            data = PieData(typePieDataSet)
                            setBackgroundColor(ResourcesCompat.getColor(resources, R.color.white, null))
                            //实体扇形的空心圆的半径 设置成0时是一个圆 而不是一个环
                            holeRadius = 60F
                            //中间半透明白色圆的半径 设置成0时隐藏
                            transparentCircleRadius = 60F
                            //设置中心圆的颜色
                            setHoleColor(Color.WHITE)
                            //设置中心部分的字 （一般中间白色圆不隐藏的情况下才设置）
                            centerText = resources.getString(R.string.customer_type_distribution)
                            //设置中心字的字体颜色
                            setCenterTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            //设置中心字的字体大小
                            setCenterTextSize(20F)
                            setCenterTextTypeface(Typeface.DEFAULT_BOLD)
                            //设置描述的字体大小
                            setEntryLabelTextSize(10F)
                            setEntryLabelColor(Color.WHITE)

                            //对于右下角一串字母的操作
                            //是否显示右下角描述
                            description.isEnabled = false
                            //修改右下角字母的显示
                            description.text = ""
                            //字体大小
                            description.textSize = 14F
                            //字体颜色
                            description.textColor = Color.RED

                            //动画（如果使用了动画可以则省去更新数据的那一步）
                            //在Y轴的动画  参数是动画执行时间 毫秒为单位
                            animateY(1000)
                            //X轴动画
                            //line.animateX(2000)
                            //XY两轴混合动画
                            //line.animateXY(2000,2000)

                            //设置不可手动旋转
                            isRotationEnabled = false
                        }

                        //图例
                        val typeLegend = binding.customerTypeChart.legend
                        //是否显示图例
                        typeLegend.isEnabled = true
                        //图例的位置
                        typeLegend.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM

                        //数据更新
                        //binding.customerTypeChart.notifyDataSetChanged()
                        //binding.customerTypeChart.invalidate()

                        initCustomerLevelPieChart()

                    } else {
                        showMessage(customerTypeResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<MarketSalesStatisticsCustomerResponse>, p1: Throwable) {
                showErrorInfo(R.string.customer_type_data_get_error)
            }
        })
    }

    private fun initCustomerLevelPieChart() {

        if (!isAdded) {
            return
        }

        val marketSalesStatisticsCustomerRequest = MarketSalesStatisticsCustomerRequest(2)

        marketSalesStatisticsCustomerRequest.beginDt = yearStartDate
        marketSalesStatisticsCustomerRequest.endDt = yearEndDate

        marketSalesStatisticsCustomerRequest.companyId = companyId
        marketSalesStatisticsCustomerRequest.groupPickupUserId = sellerId

        apiService.getMarketSalesRevenueCustomerStatistics(marketSalesStatisticsCustomerRequest).enqueue(object : Callback<MarketSalesStatisticsCustomerResponse> {
            override fun onResponse(
                marketSalesStatisticsCustomerResponse: Call<MarketSalesStatisticsCustomerResponse>,
                response: Response<MarketSalesStatisticsCustomerResponse>
            ) {
                val customerLevelResponse = response.body()

                if (customerLevelResponse != null) {
                    if (customerLevelResponse.code == 200) {

                        val customerLeveList = ArrayList<PieEntry>()

                        var count = 0

                        for (item in customerLevelResponse.data) {
                            customerLeveList.add(PieEntry(item.count.toFloat(), item.name))
                            count += item.count
                        }

                        var isEmpty = false

                        if (customerLeveList.size == 0) {
                            customerLeveList.add(PieEntry(100F, resources.getString(R.string.none)))
                            isEmpty = true
                        }

                        val customFormatter = object : ValueFormatter() {
                            override fun getFormattedValue(value: Float): String {
                                val itemValue = value.toInt()

                                val percentage = itemValue / count.toDouble() * 100

                                val percentageString = String.format(resources.getString(R.string.percentage_format), percentage)

                                return if (!isEmpty) {
                                    String.format(resources.getString(R.string.currency_name_code_format), itemValue.toString(), percentageString)
                                } else {
                                    String.format(resources.getString(R.string.price_and_currency_format), 0, "0.00%")
                                }
                            }
                        }

                        val typePieDataSet = PieDataSet(customerLeveList, "").apply {
                            //设置各个数据的颜色
                            colors = if (!isEmpty) {
                                MATERIAL_COLOR_LIST
                            } else {
                                listOf(Color.parseColor("#9E9E9E"))
                            }
                            valueTextSize = 10F
                            valueTextColor = Color.WHITE
                            valueFormatter = customFormatter
                            xValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
                            //设置描述连接线长度
                            //valueLinePart1Length = 0.2f
                            //设置数据的位置
                            yValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
                            //设置数据连接线长度
                            //valueLinePart2Length = 0.2f
                            //设置两根连接线的颜色
                            //valueLineColor = Color.GRAY
                            //设置数据的字体大小
                            valueTextSize = 10F
                        }

                        binding.customerLevelChart.apply {
                            data = PieData(typePieDataSet)
                            setBackgroundColor(ResourcesCompat.getColor(resources, R.color.white, null))
                            //实体扇形的空心圆的半径 设置成0时是一个圆 而不是一个环
                            holeRadius = 60F
                            //中间半透明白色圆的半径 设置成0时隐藏
                            transparentCircleRadius = 60F
                            //设置中心圆的颜色
                            setHoleColor(Color.WHITE)
                            //设置中心部分的字 （一般中间白色圆不隐藏的情况下才设置）
                            centerText = resources.getString(R.string.customer_type_distribution)
                            //设置中心字的字体颜色
                            setCenterTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            //设置中心字的字体大小
                            setCenterTextSize(20F)
                            setCenterTextTypeface(Typeface.DEFAULT_BOLD)
                            //设置描述的字体大小
                            setEntryLabelTextSize(10F)
                            setEntryLabelColor(Color.WHITE)

                            //对于右下角一串字母的操作
                            //是否显示右下角描述
                            description.isEnabled = false
                            //修改右下角字母的显示
                            description.text = ""
                            //字体大小
                            description.textSize = 14F
                            //字体颜色
                            description.textColor = Color.RED

                            //动画（如果使用了动画可以则省去更新数据的那一步）
                            //在Y轴的动画  参数是动画执行时间 毫秒为单位
                            animateY(1000)
                            //X轴动画
                            //line.animateX(2000);
                            //XY两轴混合动画
                            //line.animateXY(2000,2000);

                            //设置不可手动旋转
                            isRotationEnabled = false
                        }

                        //图例
                        val typeLegend = binding.customerTypeChart.legend
                        //是否显示图例
                        typeLegend.isEnabled = true
                        //图例的位置
                        typeLegend.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM

                        //数据更新
                        //binding.customerTypeChart.notifyDataSetChanged()
                        //binding.customerTypeChart.invalidate()

                    } else {
                        showMessage(customerLevelResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<MarketSalesStatisticsCustomerResponse>, p1: Throwable) {
                showErrorInfo(R.string.customer_type_data_get_error)
            }
        })
    }

    private fun getFirstDayOfMonth(year: Int, month: Int):String {
        val calendar = Calendar.getInstance()
        calendar.set(year, month, 1)
        return String.format(resources.getString(R.string.date_format), year, month, calendar.get(Calendar.DATE))
    }

    private fun getLastDayOfMonth(year: Int, month: Int):String {
        val calendar = Calendar.getInstance()
        calendar.set(year, month, 1)
        calendar.add(Calendar.DATE, - 1)
        return String.format(resources.getString(R.string.date_format), year, month, calendar.get(Calendar.DATE))
    }
}