package com.pan_american.android.ui.group_invite_official.official_visits

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.CardAdapter
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.FileListItem
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.entity.SimpleGroupInfo
import com.pan_american.android.data.model.common.network.QueryDataSetRequest
import com.pan_american.android.data.model.common.network.QueryDataSetResponse
import com.pan_american.android.data.model.common.network.SimpleGroupInfoRequest
import com.pan_american.android.data.model.common.network.SimpleGroupInfoResponse
import com.pan_american.android.data.model.group_invite_official.official_visits.network.DeleteOfficialVisitPic
import com.pan_american.android.data.model.group_invite_official.official_visits.network.GetOfficialVisitDetailRequest
import com.pan_american.android.data.model.group_invite_official.official_visits.network.GetOfficialVisitDetailResponse
import com.pan_american.android.data.model.group_invite_official.official_visits.network.UpdateOfficialVisitCheckCommitRequest
import com.pan_american.android.data.model.group_invite_official.official_visits.network.UpdateOfficialVisitRequest
import com.pan_american.android.data.model.group_invite_official.official_visits.network.UpdateOfficialVisitResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddOfficialVisitsBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.squareup.picasso.Picasso
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File

class AddOfficialVisitsActivity : BaseActivity<ActivityAddOfficialVisitsBinding>() {

    private var fromList = false

    private var officialVisitId = 0

    private var groupId = 0

    private val apiService = ServiceCreator.create<APIService>()

    private val simpleGroupInfoRequest = SimpleGroupInfoRequest()

    private val simpleGroupInfoList = ArrayList<SimpleGroupInfo>()

    private lateinit var titleBinding: LayoutTitleBinding

    private val invitorList = ArrayList<Selector>()

    private val officialTypeList = ArrayList<Selector>()

//    private val officialAttributeList = ArrayList<Selector>()

    private val photoList = ArrayList<FileListItem>()

    private var invitorId = 0

    private var officialTypeId = 0

//    private var officialAttributeId = 0

    private var checkCommitType = 0

    private val updateOfficialVisitRequest = UpdateOfficialVisitRequest()

    //监听相册事件回调
    private lateinit var result: ActivityResultLauncher<Intent>

    override fun getViewBinding() = ActivityAddOfficialVisitsBinding.inflate(layoutInflater)

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

        intent.apply {
            fromList = getBooleanExtra("fromList", false)
            officialVisitId = getIntExtra("id", 0)
            groupId = getIntExtra("groupId", 0)

            binding.groupName.text = getStringExtra("groupName")
            binding.visitCountry.text = getStringExtra("visitCountry")
            binding.clientName.text = getStringExtra("clientName")
            binding.groupCode.text = getStringExtra("groupCode")
        }

        simpleGroupInfoRequest.apply {
            pageIndex = 1
            pageSize = 10
        }

        result = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback { result ->
                if (result.resultCode == RESULT_OK) {
                    val data: Intent? = result.data
                    if (data != null) {
                        val selectedImageUri = data.data
                        if (selectedImageUri != null) {
                            photoList.add(FileListItem().apply {
                                fileName = File(uri2Path(selectedImageUri)).name

                                if (fileName.isBlank()) {
                                    showMessage(resources.getString(R.string.picture_select_error_hint))
                                    return@ActivityResultCallback
                                }

                                uri = selectedImageUri
                            })

                            initPictureList()
                        }
                    }
                }
            })

        initTitle()
        getSelectDataSource()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {

            titleText.text = if (fromList) {
                resources.getString(R.string.update_official_visits)
            } else {
                resources.getString(R.string.add_official_visits)
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {
        if (fromList) {
            getOfficialVisitsDetail()

            if (!OASystem.authorization(OASystem.OFFICIAL_VISITS, OASystem.EDIT)) {
                binding.apply {
                    country.isEnabled = false
                    area.isEnabled = false
                    officialDepartment.isEnabled(false)
                    officialDate.isEnabled = false
                    officialTime.isEnabled = false
                    invitor.isEnabled = false
                    officialContactJob.isEnabled(false)
                    officialContact.isEnabled = false
                    phone.isEnabled = false
                    officialAttribute.isEnabled = false
                    officialType.isEnabled = false
                    dressDemand.isEnabled = false
                    industry.isEnabled = false
                    needTranslatorYes.isEnabled = false
                    needTranslatorNo.isEnabled = false
                    translator.isEnabled = false
                    translateLanguage.isEnabled = false
                    isPayYes.isEnabled = false
                    isPayNo.isEnabled = false
                    isApprovalYes.isEnabled = false
                    isApprovalNo.isEnabled = false
                    emailOrWechat.isEnabled = false
                    website.isEnabled = false
                    officialLocation.isEnabled(false)
                    officialBackground.isEnabled(false)
                    officialRequestExample.isEnabled(false)
                    provisionalAgenda.isEnabled(false)
                    participationMember.isEnabled(false)
                    addEmailScreenshot.visibility = View.GONE
                    commit.setText(resources.getString(R.string.back))
                }
            }
        }

        when(checkCommitType) {
            0 -> {
                binding.checkCommit.setText(resources.getString(R.string.check_commit))
            }

            1 -> {
                binding.checkCommit.setText(resources.getString(R.string.check_cancel))
            }
        }


        binding.commit.setText(resources.getString(R.string.save))

        if (OASystem.authorization(OASystem.OFFICIAL_VISITS, OASystem.PROCESS)) {
            binding.checkCommit.visibility = View.VISIBLE
        }
    }

    override fun initEvents() {

        if (!fromList) {
            binding.groupName.setOnClickListener {
                simpleGroupInfoList.clear()

                getSimpleGroupInfoResource(1)
            }
        }

        binding.invitor.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(invitorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (invitorId == data.id) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.title_background_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                    override fun onItemClick(position: Int) {
                        invitorList[position].apply {
                            binding.invitor.text = name
                            invitorId = id
                        }

                        popupWindow.dismiss()
                    }
                }
            }
        }

        binding.officialType.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(officialTypeList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {

                            text = data.name

                            if (officialTypeId == data.id) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.title_background_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                    override fun onItemClick(position: Int) {
                        officialTypeList[position].apply {
                            binding.officialType.text = name
                            officialTypeId = id
                        }

                        popupWindow.dismiss()
                    }
                }
            }
        }

        binding.officialDate.setOnClickListener {
            showDatePicker(resources.getString(R.string.official_date), binding.officialDate)
        }

        binding.officialTime.setOnClickListener {
            showTimePicker(resources.getString(R.string.official_time), binding.officialTime)
        }

        binding.addEmailScreenshot.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(OASystem.context, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有权限，则申请需要的权限
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_MEDIA_IMAGES), OASystem.GALLERY_REQUEST_CODE)
                } else {
                    // 已经申请了权限
                    openGallery()
                }
            } else {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有权限，则申请需要的权限
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), OASystem.GALLERY_REQUEST_CODE)
                }else {
                    // 已经申请了权限
                    openGallery()
                }
            }
        }

        binding.commit.setOnClickListener {

            if (!OASystem.authorization(OASystem.OFFICIAL_VISITS, OASystem.EDIT)) {
                back()
                return@setOnClickListener
            }

            binding.country.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.country = this.toString()
                } else {
                    showMessage(resources.getString(R.string.country_input_hint))
                    return@setOnClickListener
                }
            }

            binding.area.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.area = this.toString()
                } else {
                    showMessage(resources.getString(R.string.area_input_hint))
                    return@setOnClickListener
                }
            }

            binding.officialDepartment.getText().apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.client = this
                } else {
                    showMessage(resources.getString(R.string.official_department_input_hint))
                    return@setOnClickListener
                }
            }

            binding.officialDate.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.date = this.toString()
                } else {
                    showMessage(resources.getString(R.string.official_date_select_hint))
                    return@setOnClickListener
                }
            }

            binding.officialTime.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.time = this.toString()
                } else {
                    showMessage(resources.getString(R.string.official_time_select_hint))
                    return@setOnClickListener
                }
            }

            binding.officialAttribute.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.nature = this.toString()
                } else {
                    showMessage(resources.getString(R.string.official_attribute_input_hint))
                    return@setOnClickListener
                }
            }

            binding.invitor.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.type = invitorId
                } else {
                    showMessage(resources.getString(R.string.invitor_select_hint))
                    return@setOnClickListener
                }
            }

            binding.officialContactJob.getText().apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.job = this
                } else {
                    showMessage(resources.getString(R.string.official_contact_job_input_hint))
                    return@setOnClickListener
                }
            }

            binding.officialContact.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.contact = this.toString()
                } else {
                    showMessage(resources.getString(R.string.official_contact_input_hint))
                    return@setOnClickListener
                }
            }

            binding.phone.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.tel = this.toString()
                } else {
                    showMessage(resources.getString(R.string.phone_input_hint))
                    return@setOnClickListener
                }
            }

            binding.officialType.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.officialForm = officialTypeId
                } else {
                    showMessage(resources.getString(R.string.official_type_select_hint))
                    return@setOnClickListener
                }
            }

            binding.dressDemand.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.dresscode = this.toString()
                } else {
                    showMessage(resources.getString(R.string.official_dress_demand_input_hint))
                    return@setOnClickListener
                }
            }

            binding.industry.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.field = this.toString()
                } else {
                    showMessage(resources.getString(R.string.official_industry_input_hint))
                    return@setOnClickListener
                }
            }

            when(binding.needTranslator.checkedRadioButtonId) {
                binding.needTranslatorYes.id -> {
                    updateOfficialVisitRequest.isNeedTrans = 1
                }

                binding.needTranslatorNo.id -> {
                    updateOfficialVisitRequest.isNeedTrans = 0
                }
            }

            binding.translator.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.translators = this.toString()
                }
            }

            binding.translateLanguage.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.language = this.toString()
                } else {
                    showMessage(resources.getString(R.string.translate_language_input_hint))
                    return@setOnClickListener
                }
            }

            when(binding.isPay.checkedRadioButtonId) {
                binding.isPayYes.id -> {
                    updateOfficialVisitRequest.isPay = 1
                }

                binding.isPayNo.id -> {
                    updateOfficialVisitRequest.isPay = 0
                }
            }

            when(binding.isApproval.checkedRadioButtonId) {
                binding.isApprovalYes.id -> {
                    updateOfficialVisitRequest.isSubmitApproval = 1
                }

                binding.isApprovalNo.id -> {
                    updateOfficialVisitRequest.isSubmitApproval = 0
                }
            }

            binding.emailOrWechat.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.emailOrWeChat = this.toString()
                } else {
                    showMessage(resources.getString(R.string.translate_language_input_hint))
                    return@setOnClickListener
                }
            }

            binding.website.text.apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.website = this.toString()
                } else {
                    showMessage(resources.getString(R.string.email_or_wechat_hint))
                    return@setOnClickListener
                }
            }

            binding.officialLocation.getText().apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.address = this
                } else {
                    showMessage(resources.getString(R.string.official_location_input_hint))
                    return@setOnClickListener
                }
            }

            binding.officialBackground.getText().apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.setting = this
                } else {
                    showMessage(resources.getString(R.string.official_background_input_hint))
                    return@setOnClickListener
                }
            }

            if (photoList.size == 0) {
                showMessage(resources.getString(R.string.picture_upload_hint))
                return@setOnClickListener
            }

            binding.officialRequestExample.getText().apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.reqSample = this
                }
            }

            binding.provisionalAgenda.getText().apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.trip = this
                }
            }

            binding.participationMember.getText().apply {
                if (isNotBlank()) {
                    updateOfficialVisitRequest.attendees = this
                }
            }

            updateOfficialVisitRequest.status = if (fromList) {
                2
            } else {
                1
            }

            updateOfficialVisitRequest.id = officialVisitId

            updateOfficialVisitRequest.diId = groupId

            updateOfficialVisitData()
        }

        binding.checkCommit.setOnClickListener {
            updateOfficialVisitCheckStatus()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == OASystem.GALLERY_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openGallery()
            } else {
                showMessage(resources.getString(R.string.camera_permission_hint))
            }
        }
    }

    private fun getSelectDataSource() {
        apiService.getQueryDataSet(QueryDataSetRequest(arrayListOf(38, 85))).enqueue(object : Callback<QueryDataSetResponse> {
            override fun onResponse(
                call: Call<QueryDataSetResponse>,
                response: Response<QueryDataSetResponse>
            ) {

                val dataResponse = response.body()

                if (dataResponse != null) {
                    if (dataResponse.code == 200) {

                        for (dataset in dataResponse.data) {
                            when(dataset.key) {
                                38 -> {
                                    for (item in dataset.arr) {
                                        officialTypeList.add(item)
                                    }
                                }

                                85 -> {
                                    for (item in dataset.arr) {
                                        invitorList.add(item)
                                    }
                                }
                            }
                        }

                        initViews()
                        initEvents()

                    } else {
                        showMessage(dataResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<QueryDataSetResponse>, t: Throwable) {
                showErrorInfo(R.string.base_resource_data_get_failed)
            }
        })
    }

    private fun getOfficialVisitsDetail() {

        apiService.getOfficialVisitDetailById(GetOfficialVisitDetailRequest(officialVisitId, groupId)).enqueue(object : Callback<GetOfficialVisitDetailResponse> {
            override fun onResponse(
                call: Call<GetOfficialVisitDetailResponse>,
                response: Response<GetOfficialVisitDetailResponse>
            ) {

                val detailResponse = response.body()

                if (detailResponse != null) {
                    if (detailResponse.code == 200) {

                        detailResponse.data.apply {
                            binding.country.setText(country)
                            binding.area.setText(area)
                            binding.officialDepartment.setText(client)
                            checkCommitType = confirmTheInvitation
                            binding.officialDate.text = date
                            binding.officialTime.text = time
                            binding.officialAttribute.setText(nature)

                            for (item in invitorList) {
                                if (type == item.id) {
                                    binding.invitor.text = item.name
                                    invitorId = item.id
                                }
                            }

                            binding.officialContactJob.setText(job)
                            binding.officialContact.setText(contact)
                            binding.phone.setText(tel)

                            for (item in officialTypeList) {
                                if (officialForm == item.id) {
                                    binding.officialType.text = item.name
                                    officialTypeId = item.id
                                }
                            }

                            binding.dressDemand.setText(dresscode)
                            binding.industry.setText(field)

                            when(isNeedTrans) {
                                0 -> {
                                    binding.needTranslatorNo.isChecked = true
                                }

                                1 -> {
                                    binding.needTranslatorYes.isChecked = true
                                }
                            }

                            binding.translator.setText(translators)
                            binding.translateLanguage.setText(language)

                            when(isPay) {
                                0 -> {
                                    binding.isPayNo.isChecked = true
                                }

                                1 -> {
                                    binding.isPayYes.isChecked = true
                                }
                            }

                            when(isSubmitApproval) {
                                0 -> {
                                    binding.isApprovalNo.isChecked = true
                                }

                                1 -> {
                                    binding.isApprovalYes.isChecked = true
                                }
                            }

                            binding.emailOrWechat.setText(emailOrWeChat)
                            binding.website.setText(website)
                            binding.officialLocation.setText(address)
                            binding.officialBackground.setText(setting)
                            binding.officialRequestExample.setText(reqSample)
                            binding.provisionalAgenda.setText(trip)
                            binding.participationMember.setText(attendees)

                            for (item in screenshotOfMailUrls) {
                                val photo = FileListItem().apply {
                                    fileName = item.substringAfterLast("/")
                                    url = item
                                    fromServer = true
                                }

                                photoList.add(photo)
                            }

                            initPictureList()
                        }

                    } else {
                        showMessage(detailResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<GetOfficialVisitDetailResponse>, t: Throwable) {
                showErrorInfo(R.string.official_visit_detail_get_error)
            }
        })
    }

    private fun getSimpleGroupInfoResource(type: Int) {
        apiService.getGroupNameWithSearch(simpleGroupInfoRequest).enqueue(object :
            Callback<SimpleGroupInfoResponse> {
            override fun onResponse(p0: Call<SimpleGroupInfoResponse>, response: Response<SimpleGroupInfoResponse>) {
                val resourceResponse = response.body()

                if (resourceResponse != null) {
                    if (resourceResponse.code == 200) {

                        for (item in resourceResponse.data) {
                            simpleGroupInfoList.add(item)
                        }

                        when(type) {

                            1 -> {

                                val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_selector, null)
                                popupWindow = PopupWindow(popView, RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)

                                showPopupWindow {
                                    val searchView: LinearLayout = popView.findViewById(R.id.search_view)
                                    searchView.visibility = View.VISIBLE

                                    val searchText: EditText = popView.findViewById(R.id.search_text)

                                    selector = popView.findViewById(R.id.selector_list)

                                    selectorContainer = popView.findViewById(R.id.selector_refresh_container)
                                    selectorContainer.setEnableRefresh(true)
                                    selectorContainer.setEnableLoadMore(true)

                                    val layoutManager = LinearLayoutManager(OASystem.context)
                                    selector.layoutManager = layoutManager

                                    val adapter = ListAdapter.Builder<SimpleGroupInfo>().apply {
                                        setData(simpleGroupInfoList)
                                        setLayoutId(R.layout.item_selector)
                                        addBindView { itemView, data ->
                                            itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                                                text = data.name

                                                if (binding.groupName.text == data.name) {
                                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                                                } else {
                                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                                                }
                                            }
                                        }
                                    }.create()

                                    selector.adapter = adapter

                                    adapter.onRecyclerViewItemClick =
                                        object : ListAdapter.OnRecyclerViewItemClick<SimpleGroupInfo> {
                                            override fun onItemClick(position: Int) {
                                                simpleGroupInfoList[position].apply {
                                                    binding.groupName.text = name
                                                    binding.clientName.text = clientName
                                                    binding.visitCountry.text = visitCountry
                                                    binding.groupCode.text = tourCode
                                                    groupId = id

                                                    popupWindow.dismiss()
                                                }
                                            }
                                        }

                                    selectorContainer.setOnRefreshLoadMoreListener(object :
                                        OnRefreshLoadMoreListener {
                                        override fun onRefresh(p0: RefreshLayout) {
                                            simpleGroupInfoRequest.pageIndex = 1

                                            selector.adapter!!.notifyItemRangeRemoved(0, simpleGroupInfoList.size)

                                            simpleGroupInfoList.clear()

                                            getSimpleGroupInfoResource(2)
                                        }

                                        override fun onLoadMore(p0: RefreshLayout) {
                                            simpleGroupInfoRequest.pageIndex += 1

                                            getSimpleGroupInfoResource(3)
                                        }
                                    })

                                    searchText.addTextChangedListener(object : TextWatcher {
                                        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                                        }

                                        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                                        }

                                        override fun afterTextChanged(editable: Editable?) {

                                            adapter.notifyItemRangeRemoved(0, simpleGroupInfoList.size)

                                            simpleGroupInfoList.clear()

                                            simpleGroupInfoRequest.apply {
                                                pageIndex = 1
                                                search = editable.toString()
                                            }

                                            getSimpleGroupInfoResource(2)
                                        }
                                    })

                                    popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
                                }

                                selectorContainer.setEnableLoadMore(simpleGroupInfoRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            2 -> {
                                selectorContainer.finishRefresh()
                                selectorContainer.setEnableLoadMore(simpleGroupInfoRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            3 -> {
                                selectorContainer.finishLoadMore()
                                selectorContainer.setEnableLoadMore(simpleGroupInfoRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(simpleGroupInfoList.size)
                            }
                        }

                    } else {
                        showMessage(resourceResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<SimpleGroupInfoResponse>, p1: Throwable) {
                showErrorInfo(R.string.group_name_list_get_failed)
            }
        })
    }

    private fun getTotalPage(count: Int): Int {
        var pageCount = count / 10

        if (count % 10 > 0) {
            pageCount += 1
        }

        return pageCount
    }

    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        result.launch(intent)
    }

    private fun initPictureList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.emailScreenshotList.layoutManager = layoutManager

        val adapter = CardAdapter.Builder<FileListItem>().apply {
            setData(photoList)
            setLayoutId(R.layout.item_delete_button_selector)
            setCanDelete(OASystem.authorization(OASystem.OFFICIAL_VISITS, OASystem.EDIT))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.left_text).text = data.fileName
            }
        }.create()

        binding.emailScreenshotList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : CardAdapter.OnRecyclerViewItemClick<FileListItem> {
            override fun onItemClick(position: Int) {
//                val intent = Intent(OASystem.context, PicturePreviewActivity::class.java).apply {
//                    putExtra("name", photoList[position].picName)
//                    putExtra("fromServer", photoList[position].fromServer)
//                    if (photoList[position].fromServer) {
//                        putExtra("url", photoList[position].url)
//                    } else {
//                        putExtra("uri", photoList[position].uri)
//                    }
//                }
//
//                startActivity(intent)

                val picturePreViewPopView = View.inflate(OASystem.context, R.layout.popup_list_selector, null)
                popupWindow = PopupWindow(picturePreViewPopView, ViewGroup.LayoutParams.MATCH_PARENT, binding.root.height * 3 / 4)

                showPopupWindow {

                    val recyclerTitle = picturePreViewPopView.findViewById<TextView>(R.id.recycler_title)
                    val recyclerView = picturePreViewPopView.findViewById<RecyclerView>(R.id.recycler_view)

                    recyclerTitle.text = resources.getString(R.string.picture_preview)

                    recyclerView.layoutManager = LinearLayoutManager(OASystem.context)

                    val picturePreviewAdapter = ListAdapter.Builder<FileListItem>().apply {
                        setData(photoList)
                        setLayoutId(R.layout.item_image_preview)
                        addBindView { itemView, data ->
                            if (data.fromServer) {
                                Picasso.get().load(data.url).into(itemView.findViewById<AppCompatImageView>(R.id.image_view))
                            } else {
                                Picasso.get().load(data.uri).into(itemView.findViewById<AppCompatImageView>(R.id.image_view))
                            }

                            itemView.findViewById<TextView>(R.id.image_name).text = data.fileName
                        }
                    }.create()

                    recyclerView.adapter = picturePreviewAdapter

                    popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
                }
            }

            override fun onItemDelete(position: Int) {

                CustomAlertDialog.Builder().apply {
                    setTitle(resources.getString(R.string.alert))

                    if (photoList[position].fromServer) {
                        setMessage(String.format(resources.getString(R.string.picture_uploaded_delete_hint), photoList[position].fileName))
                    } else {
                        setMessage(String.format(resources.getString(R.string.delete_alert_text), photoList[position].fileName))

                    }

                    setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                        dialog.dismiss()
                    }

                    setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                        deleteOfficialPic(position)
                    }
                }.show()
            }
        }
    }

//    private fun uri2Path(uri: Uri?): String {
//        if (uri == null) {
//            return ""
//        }
//        if (ContentResolver.SCHEME_FILE == uri.scheme) {
//            return uri.path.toString()
//        } else if (ContentResolver.SCHEME_CONTENT == uri.scheme) {
//            val authority = uri.authority
//            if (authority!!.startsWith("com.android.externalstorage")) {
//                return Environment.getExternalStorageDirectory()
//                    .toString() + "/" + uri.path!!.split(":".toRegex())
//                    .dropLastWhile { it.isEmpty() }
//                    .toTypedArray()[1]
//            } else {
//                var idStr = ""
//                if (authority == "media") {
//                    idStr = uri.toString().substring(uri.toString().lastIndexOf('/') + 1)
//                } else if (authority.startsWith("com.android.providers")) {
//                    idStr = DocumentsContract.getDocumentId(uri).split(":".toRegex())
//                        .dropLastWhile { it.isEmpty() }
//                        .toTypedArray()[1]
//                }
//                val contentResolver = OASystem.context.contentResolver
//                val cursor = contentResolver.query(
//                    MediaStore.Files.getContentUri("external"),
//                    arrayOf(MediaStore.Files.FileColumns.DATA),
//                    "_id=?",
//                    arrayOf(idStr),
//                    null
//                )
//                if (cursor != null) {
//                    cursor.moveToFirst()
//                    try {
//                        val idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)
//                        return cursor.getString(idx)
//                    } catch (_: Exception) {
//                    } finally {
//                        cursor.close()
//                    }
//                }
//            }
//        }
//        return ""
//    }

    private fun uri2Path(uri: Uri): String {
        var filePath = ""
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = contentResolver.query(uri, projection, null, null, null)!!
        if (cursor.moveToFirst()) {
            val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            filePath = cursor.getString(columnIndex)
            cursor.close()
        }

        return filePath
    }

    private fun updateOfficialVisitData() {

        apiService.updateOfficialVisitData(updateOfficialVisitRequest).enqueue(object : Callback<UpdateOfficialVisitResponse> {
            override fun onResponse(
                call: Call<UpdateOfficialVisitResponse>,
                response: Response<UpdateOfficialVisitResponse>
            ) {
                val updateResponse = response.body()

                if (updateResponse != null) {
                    if (updateResponse.code == 200) {

                        officialVisitId = updateResponse.data.id

                        uploadPic()

                    } else {
                        showMessage(updateResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<UpdateOfficialVisitResponse>, t: Throwable) {
                showErrorInfo(R.string.update_error)
            }
        })
    }

    private fun updateOfficialVisitCheckStatus() {
        apiService.updateOfficialVisitCheckCommit(UpdateOfficialVisitCheckCommitRequest(officialVisitId, checkCommitType)).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {

                val updateResponse = response.body()

                if (updateResponse != null) {
                    if (updateResponse.code == 200) {
                        showMessage(resources.getString(R.string.confirm_success))

                        when(checkCommitType) {
                            0 -> {
                                checkCommitType = 1
                                binding.checkCommit.setText(resources.getString(R.string.check_cancel))
                            }

                            1 -> {
                                checkCommitType = 0
                                binding.checkCommit.setText(resources.getString(R.string.check_commit))
                            }
                        }

                    } else {
                        showMessage(updateResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<BaseResponse>, p1: Throwable) {
                showErrorInfo(R.string.interface_request_error)
            }
        })
    }

    private fun uploadPic() {

        if (fromList) {
            var count = 0
            for (item in photoList) {
                if (!item.fromServer) {
                    count += 1
                }
            }

            if (count == 0) {

                showMessage(resources.getString(R.string.update_success))

                OASystem.needRefresh = true

                back()

                return
            }
        }

        val requestBody = MultipartBody.Builder().setType(MultipartBody.FORM).apply {
            addFormDataPart("id", officialVisitId.toString())
            addFormDataPart("diId", groupId.toString())
            addFormDataPart("currUserId", OASystem.userInfo.userId.toString())
            for (item in photoList) {
                if (!item.fromServer) {
                    val file = File(uri2Path(item.uri))
                    val fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
                    addFormDataPart("files", file.name, fileRequestBody)
                }
            }
        }.build()

        apiService.uploadOfficialPic(requestBody).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {

                val uploadResponse = response.body()

                if (uploadResponse != null) {
                    if (uploadResponse.code == 200) {
                        if (fromList) {
                            showMessage(resources.getString(R.string.update_success))
                        } else {
                            showMessage(resources.getString(R.string.insert_success))
                        }

                        OASystem.needRefresh = true

                        back()

                    } else {
                        showMessage(uploadResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<BaseResponse>, t: Throwable) {
                showErrorInfo(R.string.picture_upload_error)
            }
        })
    }

    private fun deleteOfficialPic(position: Int) {

        binding.emailScreenshotList.adapter!!.notifyItemRemoved(position)
        binding.emailScreenshotList.adapter!!.notifyItemRangeChanged(position, photoList.size - position)

        if (photoList[position].fromServer){

            val deleteOfficialVisitPic = DeleteOfficialVisitPic().apply {
                id = officialVisitId
                fileName = photoList[position].fileName
            }

            apiService.deleteOfficialPic(deleteOfficialVisitPic).enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>,
                    response: Response<BaseResponse>
                ) {
                    val deleteResponse = response.body()

                    if (deleteResponse != null) {
                        if (deleteResponse.code == 200) {

                            showMessage(resources.getString(R.string.delete_success))

                        } else {
                            showMessage(deleteResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponse>, t: Throwable) {
                    showErrorInfo(R.string.interface_request_error)
                }
            })
        }

        photoList.removeAt(position)
    }
}