package com.pan_american.android.ui.resource_management.guide_resource

import android.os.Bundle
import android.widget.RadioButton
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.resource_management.guide_resource.entity.GuideResource
import com.pan_american.android.data.model.resource_management.guide_resource.network.GuideResourceDetailRequest
import com.pan_american.android.data.model.resource_management.guide_resource.network.GuideResourceDetailResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddGuideResourceBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddGuideResourceActivity : BaseActivity<ActivityAddGuideResourceBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var fromList = false

    private lateinit var guideResource: GuideResource

    private var isChose = false

    private var guideTypeId = -1

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

    private var resourceId = 0

    override fun getViewBinding() = ActivityAddGuideResourceBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        screenAdaptation(binding)

        intent.apply {
            fromList = this.getBooleanExtra("fromList", false)
            resourceId = this.getIntExtra("resource_id", 0)
        }


        initTitle()
        initViews()
        initEvents()
    }

    override fun initTitle() {

        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            if (fromList) {
                titleText.text = resources.getString(R.string.guide_resource_detail)
            } else {
                titleText.text = resources.getString(R.string.add_guide_resource)
            }

            backButton.setOnClickListener {
                back()
            }
        }

    }

    override fun initViews() {

        if (fromList) {

            initGuideResourceDetail()

            binding.commit.setText(resources.getString(R.string.update))

            if (!OASystem.authorization(OASystem.GUIDE_RESOURCE, OASystem.EDIT)) {
                binding.apply {
                    guideType.isEnabled = false
                    serviceScore.isEnabled = false
                    unitArea.isEnabled = false
                    departmentName.isEnabled = false
                    supplierLocation.isEnabled(false)
                    contactsName.isEnabled = false
                    contactsPhone.isEnabled = false
                    contactsEmail.isEnabled = false
                    contactsFax.isEnabled = false
                    otherInfo.isEnabled(false)

                    dressA.isEnabled = false
                    dressB.isEnabled = false
                    dressC.isEnabled = false

                    awarenessA.isEnabled = false
                    awarenessB.isEnabled = false
                    awarenessC.isEnabled = false

                    expertiseA.isEnabled = false
                    expertiseB.isEnabled = false
                    expertiseC.isEnabled = false

                    timeConceptA.isEnabled = false
                    timeConceptB.isEnabled = false
                    timeConceptC.isEnabled = false

                    cooperationA.isEnabled = false
                    cooperationB.isEnabled = false
                    cooperationC.isEnabled = false

                    adaptabilityA.isEnabled = false
                    adaptabilityB.isEnabled = false
                    adaptabilityC.isEnabled = false

                    expressionA.isEnabled = false
                    expressionB.isEnabled = false
                    expressionC.isEnabled = false

                    commit.setText(resources.getString(R.string.back))
                }
            }

        } else {

            binding.commit.setText(resources.getString(R.string.add))

            guideResource = GuideResource()
        }
    }

    override fun initEvents() {

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

                            if (guideTypeId == data.id) {
                                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.guideType[position].apply {
                                binding.guideType.text = name
                                guideTypeId = id
                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

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

                            if (binding.serviceScore.text == data) {
                                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<String> {
                        override fun onItemClick(position: Int) {
                            binding.serviceScore.text = OASystem.score[position]
                            isChose = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

            if (fromList) {
                if (!OASystem.authorization(OASystem.GUIDE_RESOURCE, OASystem.EDIT)) {
                    back()
                    return@setOnClickListener
                }
            }

            when {
                guideTypeId == -1 -> {
                    showMessage(resources.getString(R.string.guide_type_select_hint))
                }

                !isChose -> {
                    showMessage(resources.getString(R.string.score_select_hint))
                }

                binding.unitArea.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.department_location_input_hint))
                }

                binding.departmentName.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.department_name_hint))
                }

                binding.contactsName.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.connector_name_input_hint))
                }

                binding.contactsPhone.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.connector_phone_input_hint))
                }

                else -> {
                    if (fromList) {
                        initGuideResource(2)
                    } else {
                        initGuideResource(1)
                    }

                    updateGuideResourceInfo()
                }
            }
        }
    }

    private fun initGuideResourceDetail() {

        apiService.getLocalGuideDetailById(GuideResourceDetailRequest(resourceId)).enqueue(object : Callback<GuideResourceDetailResponse> {
            override fun onResponse(
                call: Call<GuideResourceDetailResponse>,
                response: Response<GuideResourceDetailResponse>
            ) {
                val resourceDetailResponse = response.body()

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

                        guideResource = resourceDetailResponse.data

                        binding.apply {
                            for (item in OASystem.guideType) {
                                if (item.id == guideResource.staffType) {
                                    guideType.text = item.name
                                    guideTypeId = item.id
                                }
                            }

                            //老数据没有选择评分，更新数据时需要选择评分
                            for (item in OASystem.score) {
                                if (guideResource.score.toString() == item) {
                                    serviceScore.text = item
                                    isChose = true
                                }
                            }

                            unitArea.setText(guideResource.unitArea)
                            departmentName.setText(guideResource.unitName)
                            supplierLocation.setText(guideResource.address)
                            contactsName.setText(guideResource.contact)
                            contactsPhone.setText(guideResource.contactTel)
                            contactsEmail.setText(guideResource.contactEmail)
                            contactsFax.setText(guideResource.contactFax)
                            otherInfo.setText(guideResource.otherInfo)
                        }

                        when (guideResource.suitScore) {
                            "A" -> binding.dressA.isChecked = true
                            "B" -> binding.dressB.isChecked = true
                            "C" -> binding.dressC.isChecked = true
                        }

                        when (guideResource.serveScore) {
                            "A" -> binding.awarenessA.isChecked = true
                            "B" -> binding.awarenessB.isChecked = true
                            "C" -> binding.awarenessC.isChecked = true
                        }

                        when (guideResource.talkProScore) {
                            "A" -> binding.expertiseA.isChecked = true
                            "B" -> binding.expertiseB.isChecked = true
                            "C" -> binding.expertiseC.isChecked = true
                        }

                        when (guideResource.timeScore) {
                            "A" -> binding.timeConceptA.isChecked = true
                            "B" -> binding.timeConceptB.isChecked = true
                            "C" -> binding.timeConceptC.isChecked = true
                        }

                        when (guideResource.fitScore) {
                            "A" -> binding.cooperationA.isChecked = true
                            "B" -> binding.cooperationB.isChecked = true
                            "C" -> binding.cooperationC.isChecked = true
                        }

                        when (guideResource.strainScore) {
                            "A" -> binding.adaptabilityA.isChecked = true
                            "B" -> binding.adaptabilityB.isChecked = true
                            "C" -> binding.adaptabilityC.isChecked = true
                        }

                        when (guideResource.localAndChineseScore) {
                            "A" -> binding.expressionA.isChecked = true
                            "B" -> binding.expressionB.isChecked = true
                            "C" -> binding.expressionC.isChecked = true
                        }

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

            override fun onFailure(call: Call<GuideResourceDetailResponse>, t: Throwable) {
                showErrorInfo(R.string.guide_resource_detail_get_failed)
            }
        })
    }

    /**
     * 导游地接数据
     */

    private fun initGuideResource(type: Int) {
        guideResource.apply {
            staffType = guideTypeId
            unitName = binding.departmentName.text.toString()
            score = binding.serviceScore.text.toString().toInt()
            unitArea = binding.unitArea.text.toString()
            address = binding.supplierLocation.getText()
            contact = binding.contactsName.text.toString()
            contactTel = binding.contactsPhone.text.toString()
            contactEmail = binding.contactsEmail.text.toString()
            contactFax = binding.contactsFax.text.toString()
            otherInfo = binding.otherInfo.getText()

            suitScore =
                findViewById<RadioButton>(binding.dress.checkedRadioButtonId).text.toString()
            serveScore =
                findViewById<RadioButton>(binding.awareness.checkedRadioButtonId).text.toString()
            talkProScore =
                findViewById<RadioButton>(binding.expertise.checkedRadioButtonId).text.toString()
            timeScore =
                findViewById<RadioButton>(binding.timeConcept.checkedRadioButtonId).text.toString()
            fitScore =
                findViewById<RadioButton>(binding.cooperation.checkedRadioButtonId).text.toString()
            strainScore =
                findViewById<RadioButton>(binding.adaptability.checkedRadioButtonId).text.toString()
            localAndChineseScore =
                findViewById<RadioButton>(binding.expression.checkedRadioButtonId).text.toString()

            status = type
        }
    }

    private fun updateGuideResourceInfo() {

        binding.commit.setButtonStatus(1)

        val apiService = ServiceCreator.create<APIService>()

        apiService.guideDataOperation(guideResource).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val baseResponse = response.body()
                if (baseResponse != null) {
                    if (baseResponse.code == 200) {
                        if (guideResource.status == 1) {
                            showMessage(resources.getString(R.string.insert_success))
                        } else {
                            showMessage(resources.getString(R.string.update_success))
                        }

                        OASystem.needRefresh = true

                        back()

                    } else {

                        binding.commit.setButtonStatus(0)

                        showMessage(baseResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<BaseResponse>, t: Throwable) {

                binding.commit.setButtonStatus(0)

                showErrorInfo(R.string.update_error)
            }
        })
    }
}