package com.yidianling.medical

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.ydl.ydlcommon.actions.imagepicker.YDLImagePicker.startPicker
import com.ydl.ydlcommon.adapter.custom.PublishImageAdapter
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.router.YdlCommonOut.Companion.showToast
import com.ydl.ydlcommon.ui.ParcelableImage
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.view.dialog.NormalDialog
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.R
import com.yidianling.medical.pic.MedicalBrowsePicturesActivity
import com.yidianling.medical.pic.MedicalDynamicConstants
import com.yidianling.uikit.custom.http.ServiceImpl
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.im_ui_system_msg_item.*
import kotlinx.android.synthetic.main.medical_graphic_consultation_flow1.*
import kotlinx.coroutines.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File
import java.lang.Runnable
import java.util.*

/**
 * @Author:      刘鹏
 * @Description:  图文问诊页面
 * @CreateDate:  2021/10/27 4:28 下午
 * -------------------------------
 * @UpdateUser:
 * @UpdateDate:  2021/10/27 4:28 下午
 * @UpdateRemark:
 * @Version:
 */
class GraphicConsultationFlow1Activity : BaseActivity() {

    companion object {
        private var publishTrendImgs = ArrayList<ParcelableImage>()
        private var publishTrendImgBrows = ArrayList<ParcelableImage>()
        private var PUBLISH_PIC_BROW = 21009
        private lateinit var mDoctorId: String
        private lateinit var mDoctorUid: String
        private lateinit var imageAdapter: PublishImageAdapter
        private var imgFiles: ArrayList<File>? = null

        @JvmStatic
        fun start(context: Context, doctorId: String, doctorUid: String) {
            val starter = Intent(context, GraphicConsultationFlow1Activity::class.java)
                .putExtra("doctorId", doctorId)
                .putExtra("doctorUid", doctorUid)
            publishTrendImgs.clear()
            publishTrendImgBrows.clear()
            context.startActivity(starter)
        }
    }

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

    override fun initDataAndEvent() {
        initStatus()
        mDoctorId = intent.getStringExtra("doctorId")
        mDoctorUid = intent.getStringExtra("doctorUid")

        imageAdapter =
            PublishImageAdapter(publishTrendImgs, this@GraphicConsultationFlow1Activity);
        rv_pic_list.layoutManager = GridLayoutManager(this@GraphicConsultationFlow1Activity, 4);
        rv_pic_list.adapter = imageAdapter

        setAdapter()

        camera_bg.setOnClickListener {
            //选择图片
            showSelector()
        }

        how_to_dec.setOnClickListener {
            //如何描述
            if (dec.visibility == View.GONE) {
                dec.visibility = View.VISIBLE
            } else {
                dec.visibility = View.GONE
            }
        }
        text_service.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            if (edit_input.text.length < 10) {
                ToastUtil.toastShort("请最少填写10个字")
                return@setOnClickListener
            } else {
                if (publishTrendImgs.size > 0) {
                    var scope = CoroutineScope(Dispatchers.Default + Job())
                    scope.launch {
                        val publishImgs: MutableList<ParcelableImage> = ArrayList()
                        publishImgs.addAll(publishTrendImgs)
                        if (publishTrendImgs.size > 0) {
                            if ("default" == publishTrendImgs[0].image_url) {
                                publishImgs.removeAt(0)
                            }
                        }

                        upFile(publishImgs)
                    }

                } else {
                    //下一步
                    GraphicConsulttionFlow2Activity.start(
                        this@GraphicConsultationFlow1Activity,
                        edit_input.text.toString(), "", mDoctorId, mDoctorUid
                    )
                }
            }

        }
        edit_input.addTextChangedListener(object : TextWatcher {

            @SuppressLint("SetTextI18n")
            override fun afterTextChanged(s: Editable?) {
                setEditHint()
            }

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

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

            }
        })

        iv_back.setOnClickListener {
            backCheck()
        }
        setEditHint()
    }

    /**
     * 设置输入框提示文字
     * */
    private fun setEditHint() {
        val inputNumber = edit_input.text.length
        if (inputNumber < 10) {
            var mustInput = (10 - inputNumber).toString()
            var strStart = "最少还需描述"
            var strEnd = "个字"
            val spannable =
                SpannableStringBuilder(strStart + mustInput + strEnd)
            spannable.setSpan(
                ForegroundColorSpan(resources.getColor(R.color.medical_color_ff7766)),
                strStart.length,
                strStart.length + mustInput.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            input_num.text = spannable
        } else {
            input_num.text = "${inputNumber}/200"
        }
    }


    @SuppressLint("CheckResult")
    private fun upFile(publishTrendImgs: MutableList<ParcelableImage>) {
        imgFiles = ArrayList<File>()

        Observable.fromIterable(publishTrendImgs)
            .subscribeOn(Schedulers.io())
            .map<File> { parcelableImage: ParcelableImage ->
                LogUtil.d("url: " + parcelableImage.image_url)
                DealFile2(parcelableImage.image_url, 1500 / publishTrendImgs.size)
            }.subscribe { file ->
                if (file != null) {
                    LogUtil.d(
                        "xyutest",
                        "图片压缩后大小: ==>" + file.length() + " file path: " + file.absolutePath
                    )
                    imgFiles?.add(file);
                    if (imgFiles!!.size == publishTrendImgs.size) {
                        upFileByNet(imgFiles)
                    }
                } else {
                    runOnUiThread(Runnable() {
                        kotlin.run {
                            YdlCommonOut.Companion.showToast("有图片已被删除");
                        }
                    })
                }
            };

    }

    @SuppressLint("CheckResult")
    private fun upFileByNet(imgFiles: ArrayList<File>?) {
        val scope = CoroutineScope(Dispatchers.Default + Job())
        scope.launch {
            var files: Array<File?>? = null
            if (imgFiles != null) {
                files = arrayOfNulls(imgFiles.size)
                for (i in imgFiles.indices) {
                    files[i] = imgFiles[i]
                }
            }

            var map = TreeMap<String, RequestBody>()

            if (files != null && files.isNotEmpty()) {
                if (files.size == 1) {
                    if (files[0] != null) {
                        val fileBody =
                            RequestBody.create(MediaType.parse("multipart/form-data"), files[0]);
                        map["FILE" + "\"; filename=\"" + files[0]?.name + ""] = fileBody;
                    }
                } else {
                    for (index in files.indices) {
                        if (files[index] != null) {
                            val fileBody = RequestBody.create(
                                MediaType.parse("multipart/form-data"),
                                files[index]
                            )
                            map["FILE" + index + "\"; filename=\"" + files[index]?.name + ""] =
                                fileBody
                        }
                    }
                }
            }

            ServiceImpl.instance.uploadBatch(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response ->
                    if ("200" == response.code) {
                        val scope = CoroutineScope(Dispatchers.Default + Job())
                        scope.launch {
                            var fileStr = StringBuilder("")
                            for (file in response.data) {
                                if (file.upload) {
                                    if (fileStr.isEmpty()) {
                                        fileStr.append(file.url)
                                    } else {
                                        fileStr.append(",${file.url}")
                                    }
                                }
                            }

                            //下一步
                            GraphicConsulttionFlow2Activity.start(
                                this@GraphicConsultationFlow1Activity,
                                edit_input.text.toString(),
                                fileStr.toString(),
                                mDoctorId,
                                mDoctorUid
                            )
                        }
                    } else {
                        ToastUtil.toastShort(response.msg)
                    }
                }, { e ->
                    ToastUtil.toastShort(e.message)
                    e.printStackTrace()

                })
        }


    }

    @Synchronized
    private fun DealFile2(path: String, size: Int): File? {
        var deal_file: File? = null
        deal_file = MedicalImageCompress.scal(this@GraphicConsultationFlow1Activity, path, size)
        try {
            Thread.sleep(100)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
        return deal_file
    }

    private fun backCheck() {
        val builder = NormalDialog.Builder(this@GraphicConsultationFlow1Activity, "center", true)
        builder.setTitle("")
        builder.setMessage("\n仅剩一步就可抢到医生的问诊名额，确认放弃吗？\n")
        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()
    }

    override fun onBackPressed() {
        backCheck()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == RESULT_OK) {
            when (requestCode) {
                MedicalDynamicConstants.PUBLISH_PIC_BROW -> {
                    if (data == null) {
                        return
                    }
                    val chane_state = data.getBooleanExtra("chane_state", false)
                    if (chane_state) {
                        //图片放大删除后，返回的数据
                        val bundle = data.getBundleExtra("bundle")

                        var list = bundle.getParcelableArrayList<ParcelableImage>("publish_img")

                        if (list.size == 9) {
                            publishTrendImgs = list
                        } else if (list.size > 0) {
                            publishTrendImgs.clear()
                            publishTrendImgs.add(ParcelableImage("default"))
                            publishTrendImgs.addAll(list)
                        } else {
                            publishTrendImgs = list
                            group_empty_camera.visibility = View.VISIBLE
                            rv_pic_list.visibility = View.GONE
                        }

                        imageAdapter.updateDate(publishTrendImgs)
                    }
                }
            }
        }
    }

    private fun setAdapter() {
        imageAdapter.setOnItemClickLister(object : PublishImageAdapter.OnItemClickLister {
            override fun onItemClick(view: View, position: Int) {
                publishTrendImgBrows = ArrayList()
                publishTrendImgBrows.clear()
                publishTrendImgBrows.addAll(publishTrendImgs)
                if (publishTrendImgBrows.size < 9) {
                    publishTrendImgBrows.removeAt(0)
                    if (publishTrendImgBrows.size > 0) {
                        val intent = Intent()
                        intent.setClass(
                            this@GraphicConsultationFlow1Activity,
                            MedicalBrowsePicturesActivity::class.java
                        )
                        intent.putExtra("browse_type", "preview")
                        intent.putExtra("position", position - 1)
                        val bd = Bundle()
                        bd.putParcelableArrayList(
                            "allTrendImages",
                            publishTrendImgBrows as ArrayList<out Parcelable?>
                        )
                        intent.putExtra("allTrendImages_bd", bd)
                        startActivityForResult(intent, PUBLISH_PIC_BROW)
                    }
                } else {
                    if ("default" == publishTrendImgBrows[0].image_url) {
                        publishTrendImgBrows.removeAt(0)
                    }
                    val intent = Intent()
                    intent.setClass(
                        this@GraphicConsultationFlow1Activity,
                        MedicalBrowsePicturesActivity::class.java
                    )
                    intent.putExtra("browse_type", "preview")
                    intent.putExtra("position", position - 1)
                    val bd = Bundle()
                    bd.putParcelableArrayList(
                        "allTrendImages",
                        publishTrendImgBrows as ArrayList<out Parcelable?>
                    )
                    intent.putExtra("allTrendImages_bd", bd)
                    startActivityForResult(intent, PUBLISH_PIC_BROW)
                }
            }

            override fun onItemLongClick(view: View, position: Int) {}
        })
        imageAdapter.setOnDeleteClickLister(object : PublishImageAdapter.OnDeleteClickLister {
            override fun onDeleteClick(view: View, position: Int) {
                DeleteImg(position)
            }

            override fun onDeleteLongClick(view: View, position: Int) {}
        })
        imageAdapter.setOnAddClickLister(object : PublishImageAdapter.OnAddClickLister {
            override fun OnAddClick(view: View, position: Int) {
                if (publishTrendImgs.size < 9) {
                    showSelector()
                } else {
                    if ("default" == publishTrendImgs[0].image_url) {
                        showSelector()
                    } else {
                        showToast("最多选择9张照片")
                    }
                }
            }

            override fun OnAddLongClick(view: View, position: Int) {}
        })
    }

    private fun showSelector() {
        val selectedSize = if (publishTrendImgs.size != 0) publishTrendImgs.size - 1 else 0
        startPicker(
            (this as BaseActivity?)!!,
            9 - selectedSize,
            object : OnResultCallbackListener {
                override fun onResult(list: List<LocalMedia>) {

                    if (list.isEmpty()) {
                        return
                    }
                    for (i in list.indices) {
                        AddImag(list[i].androidQToPath)
                    }
                }

                override fun onCancel() {

                }
            })
    }

    /**
     * 添加照片
     */
    private fun AddImag(pic_path: String) {
        val trendImage = ParcelableImage(pic_path)
        when (publishTrendImgs.size) {
            in 1..8 -> {
                publishTrendImgs.add(publishTrendImgs.size, trendImage)
            }
            0 -> {
                publishTrendImgs.add(ParcelableImage("default"))
                publishTrendImgs.add(publishTrendImgs.size, trendImage)
            }
            else -> {
                publishTrendImgs.removeAt(0)
                publishTrendImgs.add(8, trendImage)
            }
        }

        if (publishTrendImgs.size > 1) {
            group_empty_camera.visibility = View.GONE
            rv_pic_list.visibility = View.VISIBLE
        } else {
            group_empty_camera.visibility = View.VISIBLE
            rv_pic_list.visibility = View.GONE
        }

        imageAdapter.updateDate(publishTrendImgs)
    }

    /**
     * 删除照片
     */
    private fun DeleteImg(position: Int) {
        if (publishTrendImgs.size in 3..8) {
            publishTrendImgs.removeAt(position)
        } else if (publishTrendImgs.size == 2) {
            publishTrendImgs.clear()
        } else {
            if ("default" == publishTrendImgs[0].image_url) {
                publishTrendImgs.removeAt(position)
            } else {
                publishTrendImgs.removeAt(position)
                publishTrendImgs.add(0, ParcelableImage("default"))
            }

        }
        if (publishTrendImgs.size > 1) {
            group_empty_camera.visibility = View.GONE
            rv_pic_list.visibility = View.VISIBLE
        } else {
            group_empty_camera.visibility = View.VISIBLE
            rv_pic_list.visibility = View.GONE
        }

        imageAdapter.updateDate(publishTrendImgs)
    }

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

}