package com.swago.user

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.swago.baseswago.UserVm
import com.swago.baseswago.activity.BaseXActivity
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.model.UploadInfo
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.GlideEngine
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.baseswago.util.UserInfo
import com.swago.lib_country_picker.Country
import com.swago.user.databinding.ActivityUserEditBinding
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File

/**
 *@date 2021/8/27 14:45
 *description:
 */
@Route(path = ARouteConstant.User.editInfo)
class EditInfoActivity : BaseXActivity<ActivityUserEditBinding>() {


    var age = ""
    var name = ""
    var imageUrl = ""
    var sign = ""
    var constellation = ""
    var sex = 0
    var country = ""

    private val userVm by viewModels<UserVm>()


    override fun loadData() {

    }

    override fun initOther() {
        setBackView(binding.toolbar.ivBack)
        binding.toolbar.tvTitle.text = AppContext.getContext().resources.getString(R.string.edit_profile)

        UserInfo.getUserInfo()?.let {
            age = it.user_age
            name = it.user_name
            imageUrl = it.user_head_img_url
            sign = it.user_signature
            constellation = it.user_constellation
            sex = it.user_sex
            country = it.user_country

            Glide.with(this).load(it.user_head_img_url).into(binding.ivAvatar)
            binding.etName.setText(it.user_name)
            binding.etAge.setText(it.user_age)
            binding.etSign.setText(it.user_signature)
            binding.etConstellation.setText(it.user_constellation)
            binding.tvCountry.text = it.user_country
            if (it.user_sex == 0){
                binding.tvSex.text = AppContext.getContext().resources.getString(R.string.male)
            }else{
                binding.tvSex.text = AppContext.getContext().resources.getString(R.string.female)
            }
        }

        binding.clGender.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                val dialog = SexBottomDFragment()
                dialog.show(supportFragmentManager, "SexBottomDFragment")
                dialog.callback = {
                    sex = it
                    if (it == 0) {
                        binding.tvSex.text =
                            AppContext.getContext().resources.getString(R.string.male)
                    } else {
                        binding.tvSex.text =
                            AppContext.getContext().resources.getString(R.string.female)
                    }
                }
            }
        })

        binding.etName.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                name =binding.etName.text.toString()
            }

        })


        binding.etConstellation.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                constellation =binding.etConstellation.text.toString()
            }

        })


        binding.etSign.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                sign =binding.etSign.text.toString()
            }

        })

        binding.etAge.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                age = binding.etAge.text.toString()
            }

        })


        binding.clCountry.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                startActivityForResult(Intent(this@EditInfoActivity,CountryActivity::class.java),111)
            }
        })


        binding.tvSave.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                val uploadInfo = UploadInfo()
                uploadInfo.user_age = age
                uploadInfo.user_constellation = constellation
                uploadInfo.user_head_img_url = imageUrl
                uploadInfo.user_name = name
                uploadInfo.user_sex = sex
                uploadInfo.user_signature = sign
                uploadInfo.user_country = country
                userVm.modifyInfo(uploadInfo)
            }
        })

        binding.ivAvatar.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                EasyPhotos.createAlbum(
                    this@EditInfoActivity,
                    false,
                    false,
                    GlideEngine.getInstance()
                )
                    .setFileProviderAuthority(AppContext.getContext().packageName + "/fileprovider")
                    .setCount(1)//参数说明：最大可选数，默认1
                    .start(object : SelectCallback() {
                        override fun onResult(
                            picList: ArrayList<Photo>?,
                            isOriginal: Boolean
                        ) {
                            if (picList != null && picList.size > 0) {
                                Glide.with(this@EditInfoActivity).load(picList[0].uri.toString())
                                    .error(R.mipmap.default_avatar).into(binding.ivAvatar)
                                Luban.with(this@EditInfoActivity)
                                    .load(picList[0].path)
                                    .ignoreBy(100)
                                    .setCompressListener(object : OnCompressListener {
                                        override fun onStart() {
                                        }

                                        override fun onSuccess(file: File?) {
                                            userVm.uploadFile(file.toString())
                                        }

                                        override fun onError(e: Throwable?) {}

                                    }).launch()
                            }
                        }

                        override fun onCancel() {

                        }
                    })
            }
        })

    }

    override fun initLiveData() {
        userVm.modifyInfoLiveData.observe(this,{
            Toast.makeText(AppContext.getContext(), "Modify Success", Toast.LENGTH_SHORT).show()
        })

        userVm.uploadPicUrlLiveData.observe(this,{
            imageUrl = it.path
            Toast.makeText(AppContext.getContext(), "Upload Success", Toast.LENGTH_SHORT).show()
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 111 && resultCode == RESULT_OK){
            val country = Country.fromJson(data?.getStringExtra("country"))
            if (country!=null){
                this@EditInfoActivity.country = country.name
                binding.tvCountry.text = country.name
            }
        }
    }
}