package com.swago.user

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
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.*
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>()

    private var optionsXinZuo: OptionsPickerView<String>? = null
    private var optionsSex: OptionsPickerView<String>? = null
    private var optionsAge: OptionsPickerView<String>? = null

    private val list by lazy {
        arrayListOf(
            "Aquarius", "Pisces", "Aries", "Taurus",
            "Gemini", "Cancer", "Leo", "Virgo",
            "Libra", "Scorpio", "Sagittarius", "Capricorn"
        )
    }

    private val sexList by lazy {
        arrayListOf(AppContext.getContext().resources.getString(R.string.male),AppContext.getContext().resources.getString(R.string.female))
    }


    private val ageList by lazy {
       ArrayList<String>()
    }

    override fun loadData() {

    }

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

        for (i in 1..100){
            ageList.add("$i")
        }

        UserInfo.getUserInfo()?.let {
            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
            age = it.user_age

            Glide.with(this).load(it.user_head_img_url)
                .placeholder(R.mipmap.default_avatar)
                .error(R.mipmap.default_avatar).into(binding.ivAvatar)
            binding.tvEditName.text = it.user_name
            binding.tvEditAge.text = it.user_age
            binding.tvEditSign.setText(it.user_signature)
            binding.tvEditConstellation.text = it.user_constellation
            binding.tvEditCountry.text = it.user_country
            if (it.user_sex == 0) {
                binding.tvEditSex.text = AppContext.getContext().resources.getString(R.string.male)
            } else {
                binding.tvEditSex.text = AppContext.getContext().resources.getString(R.string.female)
            }
        }

        binding.tvSex.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                if (optionsSex == null) {
                    optionsSex =
                        OptionsPickerBuilder(this@EditInfoActivity) { options1, options2, options3, v ->
                            if (list[options1] == AppContext.getContext().resources.getString(R.string.male)){
                                sex = 0
                            }else{
                                sex = 1
                            }
                            binding.tvEditSex.text  = list[options1]
                        }.build()
                    optionsSex?.setPicker(sexList)

                }
                optionsSex?.show()
            }
        })

        binding.tvName.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                EditDialog.newInstance(1,name).apply {
                    callback = {
                        name = it
                        this@EditInfoActivity.binding.tvEditName.text = name
                    }
                }.show(supportFragmentManager,"EditDialog")
            }
        })

        binding.tvSign.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                EditDialog.newInstance(2,sign).apply {
                    callback = {
                        sign = it
                        this@EditInfoActivity.binding.tvEditSign.text = sign
                    }
                }.show(supportFragmentManager,"EditDialog")
            }
        })

        binding.tvAge.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                if (optionsAge == null) {
                    optionsAge =
                        OptionsPickerBuilder(this@EditInfoActivity) { options1, options2, options3, v ->
                            age = ageList[options1]
                            binding.tvEditAge.text = age
                        }.build()
                    optionsAge?.setPicker(ageList)

                }
                optionsAge?.show()
            }

        })


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

        binding.tvConstellation.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                if (optionsXinZuo == null) {
                    optionsXinZuo =
                        OptionsPickerBuilder(this@EditInfoActivity) { options1, options2, options3, v ->
                            constellation = list[options1]
                            binding.tvEditConstellation.text = constellation
                        }.build()
                    optionsXinZuo?.setPicker(list)

                }
                optionsXinZuo?.show()
            }
        })


        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()
            finish()
        }

        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.tvEditCountry.text = country.name
            }
        }
    }
}