package com.pan_american.android.ui.resource_management.car_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.resource_management.car_resource.entity.CarResource
import com.pan_american.android.data.model.resource_management.car_resource.network.CarResourceDetailRequest
import com.pan_american.android.data.model.resource_management.car_resource.network.CarResourceDetailResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddCarResourceBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddCarResourceActivity : BaseActivity<ActivityAddCarResourceBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private lateinit var carResource: CarResource

    private var isChose = false

    private var fromList = false

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

    private var resourceId = 0

    override fun getViewBinding() = ActivityAddCarResourceBinding.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.car_resource_detail)
            } else {
                titleText.text = resources.getString(R.string.add_car_resource)
            }

            backButton.setOnClickListener {
                back()
            }
        }

    }

    override fun initViews() {

        if (fromList) {

            initCarResourceInfo()

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

            if (!OASystem.authorization(OASystem.CAR_RESOURCE, OASystem.EDIT)) {
                binding.apply {
                    carCompany.isEnabled = false
                    companyScore.isEnabled = false
                    departmentArea.isEnabled = false
                    departmentLocation.isEnabled(false)
                    contactsName.isEnabled = false
                    contactsPhone.isEnabled = false
                    contactsEmail.isEnabled = false
                    contactsFax.isEnabled = false
                    carDescription.isEnabled(false)
                    otherInfo.isEnabled(false)

                    carQualificationA.isEnabled = false
                    carQualificationB.isEnabled = false
                    carQualificationC.isEnabled = false

                    carAgeA.isEnabled = false
                    carAgeB.isEnabled = false
                    carAgeC.isEnabled = false

                    carSurfaceA.isEnabled = false
                    carSurfaceB.isEnabled = false
                    carSurfaceC.isEnabled = false

                    carInnerA.isEnabled = false
                    carInnerB.isEnabled = false
                    carInnerC.isEnabled = false

                    carPrepareA.isEnabled = false
                    carPrepareB.isEnabled = false
                    carPrepareC.isEnabled = false

                    carDisposeA.isEnabled = false
                    carDisposeB.isEnabled = false
                    carDisposeC.isEnabled = false

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

                    safetyConceptA.isEnabled = false
                    safetyConceptB.isEnabled = false
                    safetyConceptC.isEnabled = false

                    driverA.isEnabled = false
                    driverB.isEnabled = false
                    driverC.isEnabled = false

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

        } else {

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

            carResource = CarResource()
        }

    }

    override fun initEvents() {

        binding.companyScore.setOnClickListener {

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

                            if (binding.companyScore.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.companyScore.text = OASystem.score[position]
                            isChose = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

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

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

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

                binding.departmentArea.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.department_location_input_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 -> {
                    binding.commit.setButtonStatus(1)

                    initCarResource()

                    if (fromList) {
                        updateCarResource()
                    } else {
                        addCarResource()
                    }
                }
            }
        }
    }

    private fun initCarResourceInfo() {

        apiService.getCarResourceDetailById(CarResourceDetailRequest(resourceId)).enqueue(object : Callback<CarResourceDetailResponse> {
            override fun onResponse(
                call: Call<CarResourceDetailResponse>,
                response: Response<CarResourceDetailResponse>
            ) {
                val resourceResponse = response.body()

                if (resourceResponse != null) {
                    if (resourceResponse.code == 200) {
                        carResource = resourceResponse.data

                        binding.apply {
                            carCompany.setText(carResource.unitName)
                            for (item in OASystem.score) {
                                if (item == carResource.score.toString()) {
                                    companyScore.text = carResource.score.toString()
                                    isChose = true
                                }
                            }
                            departmentArea.setText(carResource.unitArea)
                            departmentLocation.setText(carResource.address)
                            contactsName.setText(carResource.contact)
                            contactsPhone.setText(carResource.contactTel)
                            contactsEmail.setText(carResource.contactEmail)
                            contactsFax.setText(carResource.contactFax)
                            carDescription.setText(carResource.carDes)
                            otherInfo.setText(carResource.otherInfo)
                        }

                        when (carResource.qualificationScore) {
                            "A" -> binding.carQualificationA.isChecked = true
                            "B" -> binding.carQualificationB.isChecked = true
                            "C" -> binding.carQualificationC.isChecked = true
                        }

                        when (carResource.carAgeScore) {
                            "A" -> binding.carAgeA.isChecked = true
                            "B" -> binding.carAgeB.isChecked = true
                            "C" -> binding.carAgeC.isChecked = true
                        }

                        when (carResource.cleanImgScore) {
                            "A" -> binding.carSurfaceA.isChecked = true
                            "B" -> binding.carSurfaceB.isChecked = true
                            "C" -> binding.carSurfaceC.isChecked = true
                        }

                        when (carResource.smellScore) {
                            "A" -> binding.carInnerA.isChecked = true
                            "B" -> binding.carInnerB.isChecked = true
                            "C" -> binding.carInnerC.isChecked = true
                        }

                        when (carResource.waterPaperScore) {
                            "A" -> binding.carPrepareA.isChecked = true
                            "B" -> binding.carPrepareB.isChecked = true
                            "C" -> binding.carPrepareC.isChecked = true
                        }

                        when (carResource.hardwareScore) {
                            "A" -> binding.carDisposeA.isChecked = true
                            "B" -> binding.carDisposeB.isChecked = true
                            "C" -> binding.carDisposeC.isChecked = true
                        }

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

                        when (carResource.safetyScore) {
                            "A" -> binding.safetyConceptA.isChecked = true
                            "B" -> binding.safetyConceptB.isChecked = true
                            "C" -> binding.safetyConceptC.isChecked = true
                        }

                        when (carResource.drivingAgeScore) {
                            "A" -> binding.driverA.isChecked = true
                            "B" -> binding.driverB.isChecked = true
                            "C" -> binding.driverC.isChecked = true
                        }

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

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

    /**
     * 修改车辆资源数据
     */
    private fun updateCarResource() {

        val apiService = ServiceCreator.create<APIService>()
        apiService.updateCarData(carResource).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val baseResponse = response.body()
                if (baseResponse != null) {
                    if (baseResponse.code == 200) {
                        showMessage(resources.getString(R.string.update_success))

                        OASystem.needRefresh = true

                        back()
                    } else {
                        showMessage(baseResponse.msg)

                        binding.commit.setButtonStatus(0)
                    }
                }
            }

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

                binding.commit.setButtonStatus(0)

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

    /**
     * 新增车辆资源数据
     */
    private fun addCarResource() {

        val apiService = ServiceCreator.create<APIService>()
        apiService.addCarData(carResource).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val baseResponse = response.body()
                if (baseResponse != null) {
                    if (baseResponse.code == 200) {
                        showMessage(resources.getString(R.string.insert_success))

                        OASystem.needRefresh = true

                        back()
                    } else {
                        showMessage(baseResponse.msg)

                        binding.commit.setButtonStatus(0)
                    }
                }
            }

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

                binding.commit.setButtonStatus(0)

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

    /**
     * 车辆资源数据
     */
    private fun initCarResource() {
        carResource.apply {
            unitArea = binding.departmentArea.text.toString()
            unitName = binding.carCompany.text.toString()
            address = binding.departmentLocation.getText()
            contact = binding.contactsName.text.toString()
            contactTel = binding.contactsPhone.text.toString()
            contactEmail = binding.contactsEmail.text.toString()
            contactFax = binding.contactsFax.text.toString()
            carDes = binding.carDescription.getText()
            carPicPaths = ""
            otherInfo = binding.otherInfo.getText()
            score = binding.companyScore.text.toString().toInt()

            qualificationScore =
                findViewById<RadioButton>(binding.carQualification.checkedRadioButtonId).text.toString()
            carAgeScore =
                findViewById<RadioButton>(binding.carAge.checkedRadioButtonId).text.toString()
            cleanImgScore =
                findViewById<RadioButton>(binding.carSurface.checkedRadioButtonId).text.toString()
            smellScore =
                findViewById<RadioButton>(binding.carInner.checkedRadioButtonId).text.toString()
            waterPaperScore =
                findViewById<RadioButton>(binding.carPrepare.checkedRadioButtonId).text.toString()
            hardwareScore =
                findViewById<RadioButton>(binding.carDispose.checkedRadioButtonId).text.toString()
            timeScore =
                findViewById<RadioButton>(binding.timeConcept.checkedRadioButtonId).text.toString()
            safetyScore =
                findViewById<RadioButton>(binding.safetyConcept.checkedRadioButtonId).text.toString()
            drivingAgeScore =
                findViewById<RadioButton>(binding.driver.checkedRadioButtonId).text.toString()
        }
    }
}
