package com.yidianling.medical

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.GridLayoutManager
import com.medical.ydl.medical.pay.MedicalPayActivity
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.Utils
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.medical.archives.MedicalAddNewArchivesActivity
import com.yidianling.medical.archives.MedicalUpdateArchivesActivity
import com.yidianling.medical.archives.adapter.MedicalUserArchivesFlow2Adapter
import com.yidianling.medical.archives.bean.MedicalArchivesListBean
import com.yidianling.medical.popwindow.InformedConsentPopupWindow
import com.yidianling.uikit.custom.http.ServiceImpl
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.medical_graphic_consultation_flow2.*
import kotlinx.coroutines.*


/**
 * 图文问诊2  选择问诊人
 * */
class GraphicConsulttionFlow2Activity : BaseActivity() {

    companion object {
        lateinit var stringExtra: String
        lateinit var fileStrExtra: String
        lateinit var doctorIdStrExtra: String
        lateinit var doctorUidStrExtra: String
        private lateinit var mAdapter: MedicalUserArchivesFlow2Adapter
        private var mList = ArrayList<MedicalArchivesListBean>()
        private var isFirstLoadData = true
        private var mFlow1Activity: BaseActivity? = null

        //是否是首次问诊
        private var isFirst = 1


        /**
         * @param inputText 并请描述
         * @param fileStr 图片拼接字符串
         * */
        @JvmStatic
        fun start(
            context: Context,
            inputText: String,
            fileStr: String,
            doctorId: String,
            doctorUid: String
        ) {
            mFlow1Activity = context as BaseActivity
            val starter = Intent(context, GraphicConsulttionFlow2Activity::class.java)
                .putExtra("inputText", inputText)
                .putExtra("fileStr", fileStr)
                .putExtra("doctorId", doctorId)
                .putExtra("doctorUid", doctorUid)
            context.startActivity(starter)
        }
    }

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

    override fun initDataAndEvent() {
        initStatus()
        stringExtra = intent.getStringExtra("inputText")
        fileStrExtra = intent.getStringExtra("fileStr")
        doctorIdStrExtra = intent.getStringExtra("doctorId")
        doctorUidStrExtra = intent.getStringExtra("doctorUid")

        mAdapter = MedicalUserArchivesFlow2Adapter()
        rv_people_list.layoutManager = GridLayoutManager(this@GraphicConsulttionFlow2Activity, 3)
        rv_people_list.adapter = mAdapter

        mAdapter.setOnItemClickListener { baseQuickAdapter, view, position ->
            val item = mAdapter.data[position]
            when {
                item?.isAdd == true -> {
                    //点击添加患者
                    isFirstLoadData = false
                    MedicalAddNewArchivesActivity.start(this@GraphicConsulttionFlow2Activity)

                }
                item?.needEdit == 1 -> {
                    isFirstLoadData = false
                    MedicalUpdateArchivesActivity.start(this@GraphicConsulttionFlow2Activity,item)

                }
                else -> {
                    //item 点击
                    for ((index, bean) in mAdapter.data.withIndex()) {
                        if (mAdapter.data[index]?.isCheck == true) {
                            mAdapter.data[index]?.isCheck = false
                        } else {
                            mAdapter.data[index]?.isCheck = index == position
                        }
                    }
                    baseQuickAdapter.notifyDataSetChanged()
                }
            }
        }
        empty.setOnClickListener {
            //空数据页面
            isFirstLoadData = false
            MedicalAddNewArchivesActivity.start(this@GraphicConsulttionFlow2Activity)
        }

        radio_first_mit.setOnCheckedChangeListener { group, checkedId ->
            //婚姻状态
            when (checkedId) {
                R.id.yes -> {
                    //是首次问诊
                    input_first_mit.visibility = View.GONE
                    isFirst = 1
                }
                R.id.no -> {
                    //不是首次问诊
                    input_first_mit.visibility = View.VISIBLE
                    isFirst = 0
                }
            }
        }

        yes.isChecked = true
        isFirst = 1
        no.isChecked = false
        text_service.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            //保存
            toSave()

        }
        iv_back_flow2.setOnClickListener {
            backCheck()
        }

        informed_consent_text.setOnClickListener {
            //协议内容

            var collectOutPop = InformedConsentPopupWindow(this,
                object : InformedConsentPopupWindow.OnChatSettingClickListener {
                    override fun onDismissAction() {
                        setWindowBg(1f)
                    }

                })
            collectOutPop?.contentView!!.measure(
                View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED
            ); //这句代码必须要才能获得正确的popupwindow的宽度

            val popupWindowWidth = collectOutPop?.contentView!!.measuredWidth
            setWindowBg(0.4f)
            collectOutPop?.showAsDropDown(
                toolbar,
                -(popupWindowWidth - toolbar.measuredWidth + 20),
                0
            )

        }
        getList()
    }

    private fun backCheck() {
        finish()
    }

    /**
     * 生成图文订单
     * */
    @SuppressLint("CheckResult")
    private fun toSave() {
        var selectBean: MedicalArchivesListBean? = null

        //携程用于解决遍历选中item时，没遍历完就判断了selectBean
        val scope = CoroutineScope(Dispatchers.Default + Job())
        scope.launch {
            for ((index, bean) in mAdapter.data.withIndex()) {
                if (mAdapter.data[index]?.isCheck == true) {
                    selectBean = mAdapter.data[index]!!
                    break
                }
            }

            if (selectBean == null) {
                ToastUtil.toastShort("请选择就诊人")
                scope.cancel()
                return@launch
            }
            if (isFirst == -1) {
                ToastUtil.toastShort("请选择是否首次问诊")
                scope.cancel()
                return@launch
            }
            if (isFirst == 0 && input_first_mit.text.isEmpty()) {
                ToastUtil.toastShort("请描述您的病情")
                scope.cancel()
                return@launch
            }

            ServiceImpl.instance.createArchivesOrder(
                fileStrExtra,
                isFirst,
                stringExtra,
                input_first_mit.text.toString(),
                selectBean!!.patientId,
                doctorIdStrExtra
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response ->
                    mList.clear()
                    if ("200" == response.code) {
                        MedicalPayActivity.start(
                            this@GraphicConsulttionFlow2Activity,
                            response.data.payAmountStr,
                            response.data.inquiryOrderId,
                            doctorUidStrExtra,
                            1
                        )
                        scope.cancel()
                        mFlow1Activity?.finish()
                        finish()
                    } else {
                        getList()
                        scope.cancel()
                        ToastUtil.toastShort(response.msg)
                    }
                }, { e ->
                    scope.cancel()
                    getList()
                    e.printStackTrace()
                })
        }
    }

    override fun onResume() {
        super.onResume()
        if (!isFirstLoadData) {
            getList()
        }
    }

    /**
     * 获取患者列表
     * */
    @SuppressLint("CheckResult")
    private fun getList() {
        ServiceImpl.instance.getList()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->
                if ("200" == response.code) {
                    mList.clear()
                    var data = response.data
                    if (data.size < 8) {
                        mList = data as ArrayList<MedicalArchivesListBean>
                        mList.add(MedicalArchivesListBean(true))
                    } else {
                        mList = data as ArrayList<MedicalArchivesListBean>
                    }
                    mAdapter.setNewData(mList as List<MedicalArchivesListBean?>?)
                    mAdapter.notifyDataSetChanged()

                    if (mAdapter.data.size > 1) {
                        if(mAdapter.data[0]?.needEdit!=1){
                            mAdapter.data[0]?.isCheck = true
                        }
                        rv_people_list.visibility = View.VISIBLE
                        empty.visibility = View.GONE
                    } else {
                        rv_people_list.visibility = View.GONE
                        empty.visibility = View.VISIBLE
                    }
                } else {
                    mList.add(MedicalArchivesListBean(true))
                    mAdapter.notifyDataSetChanged()
                    if (mAdapter.data.size > 1) {
                        rv_people_list.visibility = View.VISIBLE
                        empty.visibility = View.GONE
                    } else {
                        rv_people_list.visibility = View.GONE
                        empty.visibility = View.VISIBLE
                    }
                }
            }, { e ->
                if (mAdapter.data.size > 1) {
                    rv_people_list.visibility = View.VISIBLE
                    empty.visibility = View.GONE
                } else {
                    rv_people_list.visibility = View.GONE
                    empty.visibility = View.VISIBLE
                }
            })

    }

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

    override fun onBackPressed() {
        backCheck()
    }


    /**
     * 设置页面背景色
     */
    private fun setWindowBg(alpha: Float) {
        val lp = window.attributes
        lp.alpha = alpha
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        window.attributes = lp
    }
}