package com.yidianling.medical.archives

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.*
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.msg.model.IMMessage
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.view.dialog.NormalDialog
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.medical.archives.bean.MedicalArchivesListBean
import com.yidianling.medical.utils.EditTextUtils
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper
import com.yidianling.uikit.custom.http.ServiceImpl
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.medical_add_new_archives_activity.*


/**
 * 修改问诊人
 * */
class MedicalUpdateArchivesActivity : BaseActivity() {
    private var mArchivesBeanExtra: MedicalArchivesListBean?=null
    private var mPatientId:String?=null
    private var toUid:String?=null
    companion object {
        const val ARCHIVESBEAN_KEY = "archivesBean"        //患者信息key
        const val PATIENT_ID_KEY = "patient_id"
        const val SESSION_ID = "session_id"
        var mMarried = -1
        var mRelation = -1


        //之前输入内容长度
        var oldLength = 0;

        @JvmStatic
        fun start(context: Context, archivesBean: MedicalArchivesListBean) {
            val intent = Intent(context, MedicalUpdateArchivesActivity::class.java)
                .putExtra(ARCHIVESBEAN_KEY, archivesBean)
            context.startActivity(intent)
        }

        fun start(context: Context, patientId:String,toUid:String) {
            val intent = Intent(context, MedicalUpdateArchivesActivity::class.java)
                .putExtra(PATIENT_ID_KEY, patientId)
                .putExtra(SESSION_ID,toUid)
            context.startActivity(intent)
        }
    }

    override fun layoutResId(): Int {
        return R.layout.medical_add_new_archives_activity
    }

    override fun initDataAndEvent() {
        initStatus()
        tv_title.text="编辑就诊人"
        mMarried = -1
        mRelation = -1
        mPatientId = intent.getStringExtra(PATIENT_ID_KEY)
        toUid = intent.getStringExtra(SESSION_ID)
        if (TextUtils.isEmpty(mPatientId)){
            mArchivesBeanExtra = intent.getSerializableExtra(ARCHIVESBEAN_KEY) as MedicalArchivesListBean
        }


        if (mArchivesBeanExtra!=null){
            mArchivesBeanExtra!!.let {
                mPatientId = it.patientId.toString()
                it.name?.let { name ->
                    et_name.setText(name)
                }
                it.idcardNo?.let { idcard ->
                    et_idcard.setText(idcard)
                }
            }
            setRelation()
            setMarried()
        }else{
            // 接口获取就诊者信息
            getPatientInfo()
        }

        group_merried.setOnCheckedChangeListener { group, checkedId ->
            //婚姻状态
            when (checkedId) {
                R.id.unmarried -> {
                    //未婚  0
                    mMarried = 0
                }
                R.id.married -> {
                    //已婚  1
                    mMarried = 1

                }
                R.id.widowed -> {
                    //丧偶  2
                    mMarried = 2
                }
                R.id.divorce -> {
                    //离异  3
                    mMarried = 3
                }
                else -> {
                    mMarried = -1
                }
            }
        }
        group_relation.setOnCheckedChangeListener { group, checkedId ->
            //与本人关系
            when (checkedId) {
                R.id.relation_me -> {
                    //本人  0
                    mRelation = 0

                }
                R.id.relation_parent -> {
                    //父母  0
                    mRelation = 1
                }

                R.id.relation_spouse -> {
                    //配偶  2
                    mRelation = 2
                }
                R.id.relation_children -> {
                    //子女  3
                    mRelation = 3
                }
                R.id.relation_other -> {
                    //其他  4
                    mRelation = 4
                }
                else -> {

                    mRelation = -1
                }
            }
        }
        add_archives_save.setOnClickListener {
            //保存新增问诊人
            checkInfo()
        }
        EditTextUtils.disableCopyAndPaste(et_name)

        iv_back.setOnClickListener { finish() }

        showDialogTip()
    }

    /**
     * 根据接口获取就诊人信息
     */
    @SuppressLint("CheckResult")
    private fun getPatientInfo(){
        if (!TextUtils.isEmpty(mPatientId)){
            ServiceImpl.instance.getArchives(mPatientId!!)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if ("200" == it.code) {
                        mArchivesBeanExtra = MedicalArchivesListBean(false,idcardNo = it.data.idcardNo,merried = it.data.merried,
                            name = it.data.name,relation = it.data.relation)
                        mArchivesBeanExtra!!.let { archivesBeanExtra->
                            et_name.setText(archivesBeanExtra.name)
                            et_idcard.setText(archivesBeanExtra.idcardNo)
                        }
                        setRelation()
                        setMarried()
                    }
                }, {
                    it.printStackTrace()
                    ToastUtil.toastShort("网络错误")
                })
        }
    }

    /**
     * 关系
     * */
    private fun setMarried() {
        when (mArchivesBeanExtra!!.merried) {
            0 -> {
                //未婚  0
                unmarried.isChecked = true
                mMarried = 0
            }
            1 -> {
                // 1-父母
                married.isChecked = true
                mMarried = 1
            }
            2 -> {
                // 2-配偶
                widowed.isChecked = true
                mMarried = 2
            }
            3 -> {
                // 3-子女
                divorce.isChecked = true
                mMarried = 3
            }
        }
    }

    /**
     * 设置与就诊人关系
     * */
    private fun setRelation() {
        when (mArchivesBeanExtra!!.relation) {
            0 -> {
                //0-本人
                relation_me.isChecked = true
                mRelation = 0
            }
            1 -> {
                // 1-父母
                relation_parent.isChecked = true
                mRelation = 1
            }
            2 -> {
                // 2-配偶
                relation_spouse.isChecked = true
                mRelation = 2
            }
            3 -> {
                // 3-子女
                relation_children.isChecked = true
                mRelation = 3
            }
            4 -> {
                // 4-其他
                relation_other.isChecked = true
                mRelation = 4
            }
        }
    }

    private fun showDialogTip() {
        val builder = NormalDialog.Builder(this@MedicalUpdateArchivesActivity, "center", false)
        builder.setTitle("")
        val strs = arrayOf("就诊人的身份证号码", "就诊人的授权同意", "您需要在提供前征得该儿童监护人的同意")
        builder.setMessageAndBolds(
            "\n为向您添加的就诊人提供问诊服务，您需要向我们提供该就诊人的身份证号码，并确保在提供前已取得该就诊人的授权同意；若该就诊人为儿童的，您需要在提供前征得该儿童监护人的同意。\n",
            strs
        )
        builder.setPositiveButton(
            "同意"
        ) { dialog, which ->
            dialog.dismiss()
        }.setNegativeButton(
            "不同意"
        ) { dialog, which ->
            //关闭页面
            finish()
            dialog.dismiss()
        }
        builder.setRight_color("#3464EC")
        builder.setLeft_color("#8595A9")
        builder.setContent_color("#10233A")

        builder.create().show()

    }

    @SuppressLint("CheckResult")
    private fun checkInfo() {
        if (et_name.text.isNullOrEmpty()) {
            ToastUtil.toastShort("请填写姓名")
            return
        }
        if (et_idcard.text.isNullOrEmpty()) {
            ToastUtil.toastShort("请填写身份证号")
            return
        }

        if (et_idcard.text.length < 15 || et_idcard.text.length > 18) {
            ToastUtil.toastShort("请填写有效身份证号")
            return
        }
        if (mMarried == -1) {
            ToastUtil.toastShort("请选择婚姻状况")
            return
        }
        if (mRelation == -1) {
            ToastUtil.toastShort("请选择与就诊人的关系")
            return
        }

        ServiceImpl.instance.updateArchives(et_name.text.toString(), et_idcard.text.toString(),
            mMarried,
            mRelation,
            mPatientId!!
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if ("200" == it.code) {
                    if (!TextUtils.isEmpty(toUid)){     // 如果是来自云信自定义消息打开的页面，保存完信息，发送一条im消息告知医生
                        val textMessage: IMMessage = MessageBuilder.createTextMessage(
                            toUid,
                            SessionTypeEnum.P2P,
                            "我已完善信息，请您开具处方"
                        )
                        NIMClient.getService(MsgService::class.java).sendMessage(textMessage, false)
                        MessageListPanelHelper.getInstance().notifyAddMessage(textMessage)
                    }
                    finish()
                    ToastUtil.toastShort("保存成功")
                } else {
                    ToastUtil.toastShort(it.msg)
                }
            }, {
                it.printStackTrace()
                ToastUtil.toastShort("网络错误")
            })


    }

    private fun initStatus() {
        StatusBarUtils.setTransparentForImageView(this@MedicalUpdateArchivesActivity, null)
        StatusBarUtils.statusBarLightMode(this@MedicalUpdateArchivesActivity)
    }
}