package com.etong.smart.Main.LeftDrawer.SystemSetting

import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import com.alibaba.fastjson.JSONException
import com.alibaba.fastjson.JSONObject
import com.etong.smart.Other.BaseActivity
import com.etong.smart.Other.Service
import com.etong.smart.Other.Storage
import com.etong.smart.R
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*

class ChangePhoneActivity : BaseActivity(), TextWatcher {


    private var mSendCode: Button? = null
    private var mCommitBtn: Button? = null
    private var mPwdEditText: EditText? = null
    private var mPhoneEditText: EditText? = null
    private var mCodeEditText: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_change_phone)
        val toolbar = findViewById(R.id.toolbar) as Toolbar
        mSendCode = findViewById(R.id.button8) as Button
        mCommitBtn = findViewById(R.id.button9) as Button
        mPwdEditText = findViewById(R.id.et_pwd) as EditText
        mPhoneEditText = findViewById(R.id.et_phone) as EditText
        mCodeEditText = findViewById(R.id.et_code) as EditText

        mPwdEditText?.addTextChangedListener(this)
        mPhoneEditText?.addTextChangedListener(this)
        mCodeEditText?.addTextChangedListener(this)

        setSupportActionBar(toolbar)
        toolbar.setNavigationOnClickListener { v -> finish() }


        findViewById(R.id.back_view).setOnClickListener {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(mSendCode?.windowToken, 0)
        }

        //发送code
        mSendCode!!.setOnClickListener { v ->
            mSendCode!!.isEnabled = false
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(mSendCode?.windowToken, 0)
            if (mPhoneEditText!!.text.length < 11) {
                Snackbar.make(v, "手机号不正确,请重新输入", Snackbar.LENGTH_SHORT).show()
            } else if (mPwdEditText?.text.toString() != Storage.readPwd()) {
                Snackbar.make(v, "密码不正确,请重新输入", Snackbar.LENGTH_SHORT).show()
            } else {
                Service.sendCode(mPhoneEditText?.text.toString(), false)
                        .enqueue(object : Callback<String> {
                            override fun onFailure(call: Call<String>?, t: Throwable?) {
                                t?.printStackTrace()
                            }

                            override fun onResponse(call: Call<String>?, response: Response<String>?) {
                                try {
                                    val json = JSONObject.parseObject(response?.body())
                                    if (json.getIntValue("status") == 1) setTiemr() else {
                                        Snackbar.make(v, json.getString("error"), Snackbar.LENGTH_SHORT).show()
                                    }
                                } catch (e: JSONException) {
                                    Snackbar.make(v, "服务器出错,请稍后再试", Snackbar.LENGTH_SHORT).show()
                                }
                            }
                        })
            }
        }


    }

    //提交
    fun commit(v: View) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(mSendCode?.windowToken, 0)
        Service.binding_mobile(mPhoneEditText?.text.toString(), mCodeEditText?.text.toString())
                .enqueue(object : Callback<String> {
                    override fun onResponse(call: Call<String>?, response: Response<String>?) {
                        try {
                            val jsonObj = JSONObject.parseObject(response?.body())
                            val status = jsonObj.getInteger("status")
                            if (status == 1) {
                                Snackbar.make(v, "修改手机号成功", Snackbar.LENGTH_SHORT).setCallback(object :Snackbar.Callback(){
                                    override fun onDismissed(snackbar: Snackbar?, event: Int) {
                                        finish()
                                    }
                                }).show()
                            } else if (status == 0) {
                                Snackbar.make(v, jsonObj.getString("error"), Snackbar.LENGTH_SHORT).show()
                            }
                        } catch (e: JSONException) {
                            Snackbar.make(v, "服务器出错,请稍后再试", Snackbar.LENGTH_SHORT).show()
                        }
                    }

                    override fun onFailure(call: Call<String>?, t: Throwable?) {
                        t?.printStackTrace()
                    }

                })
    }

    ///////////////////////////////////////////////////////////////////////////
    // textChangeWhater
    ///////////////////////////////////////////////////////////////////////////
    override fun afterTextChanged(s: Editable?) {
        mCommitBtn?.isEnabled = mPwdEditText?.text?.length!! >= 6 && mPhoneEditText?.text?.length!! == 11 && mCodeEditText?.length()!! == 4
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }

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

    private var time = 60
    //设置计时器
    private fun setTiemr() {
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                if (time > 0) {
                    runOnUiThread {
                        mSendCode!!.setText(time.toString() + "s")
                        mSendCode!!.isEnabled = false
                    }
                    time--
                } else {
                    runOnUiThread {
                        mSendCode!!.text = "重发验证码"
                        mSendCode!!.isEnabled = true
                    }
                    time = 60
                    timer.cancel()
                }

            }
        }, 0, 1000)
    }
}
