package com.lemonhc.mplus.mcare_plus.activity

import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.lemonhc.mplus.MPlusConstants
import com.lemonhc.mplus.framework.task.ApiClient
import com.lemonhc.mplus.framework.util.kotlinExtension.format
import com.lemonhc.mplus.framework.util.kotlinExtension.isCaptureFlag
import com.lemonhc.mplus.framework.util.kotlinExtension.toBase64
import com.lemonhc.mplus.mcare_plus.R
import com.lemonhc.mplus.model.Photo
import com.lemonhc.mplus.model.update
import uk.co.senab.photoview.PhotoView
import java.io.File
import java.util.*

class PhotoDetailActivity: AppCompatActivity() {
    companion object {
        lateinit var item: Photo
        lateinit var callBack:() -> Unit
    }

    lateinit var imageView: PhotoView

    //환자번호
    private lateinit var bt_patientId: Button
    //환자이름
    private lateinit var bt_patientNm: Button
    //환자나이/성별
    private lateinit var bt_ageGender: Button
    private lateinit var headerText: TextView
    private lateinit var bt_send: ImageButton
    private lateinit var bt_finish: ImageButton

    private lateinit var imageButton: ImageButton

    open var photoPath = "${Environment.getExternalStorageDirectory()}/kunkuk"
    open var thumbPath = "${Environment.getExternalStorageDirectory()}/kunkuk/thumb"

    private lateinit var bt_deptNm: Button
    private lateinit var bt_treatClsKr: Button
    private lateinit var bt_doctorNm: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (!isCaptureFlag) {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }

        setContentView(R.layout.activity_detail).run {
            imageView = findViewById(R.id.imageView)
            bt_patientNm = findViewById(R.id.patientNm)
            bt_patientId = findViewById(R.id.patientId)
            bt_ageGender = findViewById(R.id.agegender)
            headerText = findViewById(R.id.headerText)
            bt_send = findViewById(R.id.bt_send)
            bt_finish = findViewById(R.id.bt_finish)
            imageButton = findViewById(R.id.imageButton)
            bt_deptNm = findViewById(R.id.deptNm)
            bt_treatClsKr = findViewById(R.id.treatClsKr)
            bt_doctorNm = findViewById(R.id.doctorNm)
        }

        val filePath = intent.getStringExtra("filePath")
        val bitmap = BitmapFactory.decodeFile(filePath)
        imageView.setImageBitmap(bitmap)

        item.let {
            bt_patientNm.text = it.user.patientNm
            bt_patientId.text = it.user.patientId
            bt_ageGender.text = "${it.user.age} / ${it.user.gender}"
            headerText.text = it.key
            bt_deptNm.text = it.user.deptNm
            bt_treatClsKr.text = it.user.treatClsKr
            bt_doctorNm.text = it.user.doctorNm
            if (item.isSended) {
                bt_send.visibility = View.GONE
            }
        }

        bt_send.setOnClickListener{
            this.sendAction()
        }
        bt_finish.setOnClickListener{
            this.finishAction()
        }
        imageButton.setOnClickListener {
            this.finishAction()
        }
    }

    private fun sendAction() {
        this.uploadItem(item)
    }

    private fun finishAction() {
        this.finish()
        callBack()
    }

    private fun uploadItem(item: Photo) {
        val reqParam = mutableListOf<Pair<String, Any?>>().apply {
            add("hospitalCd" to item.user.hospitalCD)
            add("userId" to item.user.userId)
            add("patientId" to item.user.patientId)
            add("deptCd" to item.user.deptCd)
            add("doctorId" to item.user.doctorId)
            add("searchCls" to item.user.treatCls)
            add("excutionDtTm" to Date().format("yyyy-MM-dd hh:mm:ss"))
            add("visitDt" to item.user.visitDt)
            add("thumbnail" to "")
            add("image" to File("${photoPath}/${item.file}").toBase64())
        }

        val url = "${MPlusConstants.DOMAIN_NAME}${item.user.serviceUrl}"
        ApiClient(url, reqParam, header_param = mapOf("Content-Type" to "application/json"))
                .encType(ApiClient.ENC_Type.Json)
                .connect {
                    val json = it ?: run {
                        //json 값이 실제로 들어있는지 체크하는 로직 추가
                        Toast.makeText(this, "서버와 통신이 원활하지 않습니다.", Toast.LENGTH_LONG).show()
                        return@connect
                    }
                    //성공일시
                    val result = json.getJSONArray("result")
                    val returnCd = result.getJSONObject(0).get("returnCd") as? String
                    val returnMsg: String = result.getJSONObject(0).get("returnMsg") as? String ?: "전송에 실패하였습니다. 관리자에게 문의하여 주세요."
                    if (returnCd == "0000") {
                        item.isSended = true
                        item.update()
                        Toast.makeText(this, "전송이 완료되었습니다.", Toast.LENGTH_SHORT).show()
                        this.finishAction()
                    } else {
                        Toast.makeText(this, returnMsg, Toast.LENGTH_SHORT).show()
                    }
                }
    }

}
