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

import android.os.Bundle
import android.text.InputType
import android.view.View
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.resource_management.guide_resource.entity.GuideResource
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

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

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

        fromList = intent.getBooleanExtra("fromList", false)

        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) {

            guideResource = intent.getSerializableExtra("guideResource") as GuideResource
            binding.commit.text = resources.getString(R.string.update)
            initGuideResourceInfo()

        } else {

            guideResource = GuideResource(
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                0,
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                OASystem.userInfo.userId,
                ""
            )
        }
    }

    override fun initEvents() {

        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) {
                            popupWindow.dismiss()
                            binding.serviceScore.text = OASystem.score[position]
                            isChose = true
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {
            if (fromList) {
                initGuideResource(2)
                updateGuideResourceInfo()
            } else {
                if (isChose) {
                    initGuideResource(1)
                    updateGuideResourceInfo()
                } else {
                    showMessage("请选择评分！")
                }
            }
        }
    }

    private fun initGuideResourceInfo() {
        binding.apply {
            guideResourceName.setText(guideResource.unitName)
            serviceScore.text = guideResource.score.toString()
            unitArea.setText(guideResource.unitArea)
            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
        }

        if (!OASystem.authorization(OASystem.GUIDE_RESOURCE, OASystem.EDIT)) {
            binding.apply {
                guideResourceName.inputType = InputType.TYPE_NULL
                serviceScore.isEnabled = false
                unitArea.inputType = InputType.TYPE_NULL
                supplierLocation.setInputType(InputType.TYPE_NULL)
                contactsName.inputType = InputType.TYPE_NULL
                contactsPhone.inputType = InputType.TYPE_NULL
                contactsEmail.inputType = InputType.TYPE_NULL
                contactsFax.inputType = InputType.TYPE_NULL
                otherInfo.setInputType(InputType.TYPE_NULL)
                otherInfo.setSingleLine(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.text = resources.getString(R.string.back)
            }
        }
    }

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

    private fun initGuideResource(type: Int) {
        guideResource.apply {
            unitName = binding.guideResourceName.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.isEnabled = false

        binding.commit.visibility = View.GONE

        binding.updateLoading.visibility = View.VISIBLE

        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 {
                        showMessage(baseResponse.msg)

                        binding.commit.isEnabled = true

                        binding.commit.visibility = View.VISIBLE

                        binding.updateLoading.visibility = View.GONE
                    }
                }
            }

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

                binding.commit.isEnabled = true

                binding.commit.visibility = View.VISIBLE

                binding.updateLoading.visibility = View.GONE

                showMessage(resources.getString(R.string.network_error))
            }
        })
    }
}