package com.pan_american.android.ui.group_management.group_info

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
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.group_management.group_info.entity.GroupCustomerInfo
import com.pan_american.android.data.model.group_management.group_info.network.NameSpellGenerateRequest
import com.pan_american.android.data.model.group_management.group_info.network.NameSpellGenerateResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentGroupCustomerDetailBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class GroupCustomerDetailFragment : BaseFragment<FragmentGroupCustomerDetailBinding>() {

    private var fromList = false

    private var position = -1

    private var groupCustomerInfo = GroupCustomerInfo()

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

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

    override fun onStart() {
        super.onStart()

        requireArguments().apply {
            position = getInt("position")
            fromList = getBoolean("from_list")
        }

        if (fromList) {
            groupCustomerInfo = OASystem.groupCustomerList[position]
        }

        initViews()
        initEvents()
    }

    override fun initViews() {

        if (fromList) {
            binding.title.text = resources.getString(R.string.customer_info_detail)
            binding.commit.text = resources.getString(R.string.update)

            binding.lastName.setText(groupCustomerInfo.lastName)
            binding.firstName.setText(groupCustomerInfo.firstName)

            if (groupCustomerInfo.pinyin.isNotBlank()) {
                binding.nameSpell.setText(groupCustomerInfo.pinyin)
                binding.nameSpell.visibility = View.VISIBLE
                binding.nameSpellGenerate.visibility = View.GONE
            }

            binding.departmentName.setText(groupCustomerInfo.companyFullName)
            binding.job.setText(groupCustomerInfo.job)
            binding.phoneNumber.setText(groupCustomerInfo.phone)

            when (groupCustomerInfo.sex) {
                0 -> {
                    binding.male.isChecked = true
                }

                1 -> {
                    binding.female.isChecked = true
                }
            }

            binding.idCard.setText(groupCustomerInfo.idCardNo)
            binding.customerBirthday.text = groupCustomerInfo.birthDay

            for (item in OASystem.berthType) {
                if (item.id == groupCustomerInfo.shippingSpaceTypeId) {
                    binding.berthType.text = item.name
                }
            }

            binding.berthNotes.setText(groupCustomerInfo.shippingSpaceSpecialNeeds)
            binding.roomNotes.setText(groupCustomerInfo.hotelSpecialNeeds)
            binding.mealNotes.setText(groupCustomerInfo.mealSpecialNeeds)
            binding.notes.setText(groupCustomerInfo.remark)

        } else {
            binding.title.text = resources.getString(R.string.add_single_customer_info)
            binding.commit.text = resources.getString(R.string.add)

            //默认经济舱
            for (item in OASystem.berthType) {
                if (item.id == groupCustomerInfo.shippingSpaceTypeId) {
                    binding.berthType.text = item.name
                }
            }
        }

        if (!OASystem.authorization(OASystem.GROUP_CLIENT_LIST, OASystem.EDIT)) {
            binding.apply {
                lastName.isEnabled = false
                firstName.isEnabled = false
                nameSpell.isEnabled = false
                departmentName.isEnabled = false
                job.isEnabled = false
                phoneNumber.isEnabled = false
                male.isEnabled = false
                female.isEnabled = false
                idCard.isEnabled = false
                customerBirthday.isEnabled = false

                berthType.isEnabled = false

                berthNotes.isEnabled = false
                roomNotes.isEnabled = false
                mealNotes.isEnabled = false
                notes.isEnabled = false

                commit.visibility = View.GONE
            }
        }
    }

    override fun initEvents() {

        binding.nameSpellGenerate.setOnClickListener {

            if (binding.firstName.text.isNullOrBlank() || binding.lastName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.first_name_and_last_name_hint))
                return@setOnClickListener
            }

            val originalText = ArrayList<String>()

            var lastNameSize: Int

            binding.lastName.text.toList().apply {
                for (item in this) {
                    originalText.add(item.toString())
                }

                lastNameSize = this.size
            }

            binding.firstName.text.toList().apply {
                for (item in this) {
                    originalText.add(item.toString())
                }
            }

            apiService.generateNameSpell(NameSpellGenerateRequest(originalText, true))
                .enqueue(object : Callback<NameSpellGenerateResponse> {
                    override fun onResponse(
                        call: Call<NameSpellGenerateResponse>,
                        response: Response<NameSpellGenerateResponse>
                    ) {

                        val nameSpellResponse = response.body()

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

                                var firstNameSpell = ""

                                var lastNameSpell = ""

                                for ((i, item) in nameSpellResponse.data.withIndex()) {
                                    if (i < lastNameSize) {
                                        lastNameSpell += "$item "
                                    }

                                    if (i in lastNameSize until nameSpellResponse.data.size) {
                                        firstNameSpell += " $item"
                                    }
                                }

                                binding.nameSpell.apply {
                                    setText(
                                        String.format(
                                            resources.getString(R.string.name_spell_format),
                                            lastNameSpell.trim(),
                                            firstNameSpell.trim()
                                        )
                                    )
                                    visibility = View.VISIBLE
                                }

                                binding.nameSpellGenerate.visibility = View.GONE

                            } else {
                                showMessage(nameSpellResponse.msg)
                            }
                        }

                    }

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

        binding.customerBirthday.setOnClickListener {
            showDatePicker(resources.getString(R.string.birthday), binding.customerBirthday) {
                val str = binding.customerBirthday.text.toString()
                str.replaceFirst("-", "年")
                str.replace("-", "月")
                binding.customerBirthday.text = str
            }
        }

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

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            OASystem.berthType[position].apply {
                                binding.berthType.text = name

                                groupCustomerInfo.shippingSpaceTypeId = id
                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {
            if (fromList) {
                OASystem.groupCustomerList[position].apply {
                    lastName = binding.lastName.text.toString()
                    firstName = binding.firstName.text.toString()
                    pinyin = binding.nameSpell.text.toString()
                    companyFullName = binding.departmentName.text.toString()
                    job = binding.job.text.toString()
                    phone = binding.phoneNumber.text.toString()

                    when (binding.gender.checkedRadioButtonId) {
                        binding.male.id -> {
                            sex = 0
                        }

                        binding.female.id -> {
                            sex = 1
                        }
                    }

                    idCardNo = binding.idCard.text.toString()
                    birthDay = binding.customerBirthday.text.toString()

                    shippingSpaceSpecialNeeds = binding.berthNotes.getText()
                    hotelSpecialNeeds = binding.roomNotes.getText()
                    mealSpecialNeeds = binding.mealNotes.getText()
                    remark = binding.notes.getText()

                    showMessage(resources.getString(R.string.update_success))
                }
            } else {

                binding.lastName.text.apply {
                    if (isNullOrBlank()) {
                        showMessage(resources.getString(R.string.last_name_hint))
                        return@setOnClickListener
                    }
                }

                binding.firstName.text.apply {
                    if (isNullOrBlank()) {
                        showMessage(resources.getString(R.string.first_name_hint))
                        return@setOnClickListener
                    }
                }

                binding.nameSpell.text.apply {
                    if (isNullOrBlank()) {
                        showMessage(resources.getString(R.string.name_spell_hint))
                        return@setOnClickListener
                    }
                }

                binding.departmentName.text.apply {
                    if (isNullOrBlank()) {
                        showMessage(resources.getString(R.string.department_name_hint))
                        return@setOnClickListener
                    }
                }

                binding.job.text.apply {
                    if (isNullOrBlank()) {
                        showMessage(resources.getString(R.string.job_name_hint))
                        return@setOnClickListener
                    }
                }

                groupCustomerInfo.apply {
                    lastName = binding.lastName.text.toString()
                    firstName = binding.firstName.text.toString()
                    pinyin = binding.nameSpell.text.toString()
                    companyFullName = binding.departmentName.text.toString()
                    job = binding.job.text.toString()
                    phone = binding.phoneNumber.text.toString()

                    when (binding.gender.checkedRadioButtonId) {
                        binding.male.id -> {
                            sex = 0
                        }

                        binding.female.id -> {
                            sex = 1
                        }
                    }

                    idCardNo = binding.idCard.text.toString()
                    birthDay = binding.customerBirthday.text.toString()

                    shippingSpaceSpecialNeeds = binding.berthNotes.getText()
                    hotelSpecialNeeds = binding.roomNotes.getText()
                    mealSpecialNeeds = binding.mealNotes.getText()
                    remark = binding.notes.getText()
                }

                OASystem.groupCustomerList.add(groupCustomerInfo)

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

            parentFragmentManager.popBackStack()
        }
    }
}