puzhibing
2026-08-21 5fa94b3718b4a78a4fcea4c97652b0ef20b7de3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package com.xw.yunwei.ui.work.checkInMission.viewmodel
 
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import androidx.core.net.toUri
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import com.amap.location.support.util.TextUtils
import com.blankj.utilcode.util.UriUtils
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.xw.common.CommonDialog
import com.xw.common.base.BaseViewModel
import com.xw.common.base.ShowImgListDialog
import com.xw.common.utils.ToastUtilCommon
import com.xw.yunwei.model.CheckInMissionPointInfo
import com.xw.yunwei.model.UploadModel
import com.xw.yunwei.net.CommonRepository
import com.xw.yunwei.net.WorkRepository
import com.xw.yunwei.ui.dialog.CruiseCheckInSuccessDialog
import com.xw.yunwei.ui.work.checkInMission.CruiseCheckInMissionCompleteActivity
import com.xw.yunwei.utils.PictureSelectorFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import org.greenrobot.eventbus.EventBus
import org.koin.core.component.inject
import java.io.File
 
class CruiseCheckInOperationViewModel(application: Application) : BaseViewModel(application),
    OnResultCallbackListener<LocalMedia> {
 
    val commonRepository: CommonRepository by inject()
    val workRepository: WorkRepository by inject()
    var id: String = ""
    val model = MutableLiveData<CheckInMissionPointInfo>()
 
    //是否是最后一个点
    var isEndPoint = false
    val working = MutableLiveData<Boolean>(true)
    val maxLength = MutableLiveData(200)
    val desc = MutableLiveData("")
    val countNotice: MutableLiveData<String> =
        MutableLiveData("${desc.value?.length ?: 0}/${maxLength.value}")
    val noticeLabel: MutableLiveData<String> = MutableLiveData("最多输入${maxLength.value}字")
    val pictureMax = MutableLiveData(6)
 
    //操作图片
    val operationPictures: MutableLiveData<MutableList<String>> = MutableLiveData(mutableListOf(""))
 
    //是否正在上传中
    var isUploading = false
 
    //添加图片
    fun addPicture(url: String) {
        val list = operationPictures.value ?: mutableListOf()
        list.add(url)
        refreshPictures(list)
        operationPictures.postValue(list.toMutableList())
    }
 
    //移除图片
    fun removePicture(position: Int) {
        val list = operationPictures.value ?: mutableListOf()
        list.removeAt(position)
        refreshPictures(list)
        operationPictures.postValue(list.toMutableList())
    }
 
    //刷新图片
    fun refreshPictures(list: MutableList<String>) {
        list.removeIf { it.isEmpty() }
        if (list.size == pictureMax.value) {
            return
        }
        list.add("")
    }
 
    //操作图片
    fun operatePicture(context: Context, position: Int) {
        val list = operationPictures.value ?: mutableListOf()
        val element = list.elementAtOrNull(position) ?: return
        if (element.isEmpty()) {
            operatePictureFromDevice(context)
        } else {
            val backUp = list.toMutableList()
            backUp.removeIf { it.isEmpty() }
            ShowImgListDialog(
                context as FragmentActivity,
                backUp,
                position
            ).show()
        }
    }
 
    //从设备操作图片
    fun operatePictureFromDevice(context: Context) {
        CommonDialog.showTypeDialog(context) {
            if (it == 0) takeAPhotograph(context) else if (it == 1) enterGallery(context)
        }
    }
 
    // 进入图库
    @SuppressLint("SourceLockedOrientationActivity")
    private fun enterGallery(context: Context) {
        PictureSelectorFactory.enterGallery(
            context,
            (pictureMax.value ?: 1) - (operationPictures.value?.count { it.isNotEmpty() } ?: 0),
            this)
    }
 
    // 拍照
    private fun takeAPhotograph(context: Context) {
        PictureSelectorFactory.takeAPhotograph(context, this)
    }
 
    override fun onResult(result: ArrayList<LocalMedia>?) {
        result?.let { selectList ->
            for (item in selectList) {
                val path: String = item.availablePath
                val imgPath =
                    if (PictureMimeType.isContent(path) && !item.isCut && !item.isCompressed) {
                        UriUtils.uri2File(path.toUri()).absolutePath
                    } else {
                        path
                    }
                addPicture(imgPath)
            }
        }
    }
 
    override fun onCancel() {
 
    }
 
    private fun uploadFile(files: MutableList<Pair<String, UploadModel?>>, succ: () -> Unit) {
        val result = files.find { it.second == null }
        if (result == null) {
            succ()
        } else {
            launchRequest(showLoading = false, error = { _, errMsg ->
                ToastUtilCommon.showError(errMsg)
                dismissDialog()
                isUploading = false
            }) {
                val file = File(result.first)
                val fileRequestBody = file.asRequestBody("image/jpg".toMediaType())
                val mBuilder = MultipartBody.Builder()
                mBuilder.addFormDataPart("file", file.name, fileRequestBody)
                mBuilder.setType(MultipartBody.FORM)
                val data = commonRepository.uploadFile(mBuilder.build())
                files[files.indexOf(result)] = result.first to data
                uploadFile(files, succ)
            }
        }
    }
 
    //提交
    fun submit(context: Context) {
        if (model.value == null) {
            return
        }
        if (working.value == null) {
            ToastUtilCommon.showError("请选择现场情况")
            return
        }
        if (TextUtils.isEmpty(desc.value) && working.value != true) {
            ToastUtilCommon.showError("请输入现场情况描述")
            return
        }
        if ((desc.value?.length ?: 0) > maxLength.value!!) {
            ToastUtilCommon.showError(noticeLabel.value)
            return
        }
        val list = operationPictures.value ?: mutableListOf()
        list.removeIf { it.isEmpty() }
        if (list.count { !it.startsWith("http") } > 0) {
            val result = list.map { Pair<String, UploadModel?>(it, null) }.toMutableList()
            uploadFile(result) {
                result.removeIf { it.second == null }
                submit(context, result.map { it.second!! }.toMutableList())
            }
            return
        }
        submit(context, mutableListOf())
    }
 
    //提交
    private fun submit(context: Context, urls: MutableList<UploadModel>) {
        launchRequest {
            workRepository.saveCruiseCheckInRecord(
                model.value!!.locationId!!,
                working.value!!,
                desc.value ?: "",
                urls
            )?.also { it ->
                val list = workRepository.getCheckInMissionPointsList(id)
                if (list == null || list.count { !it.hadCheckIn() } > 0) {
                    withContext(Dispatchers.Main) {
                        CruiseCheckInSuccessDialog.show(
                            context = context, result = it,
                            operationLabel = if (isEndPoint) "前往打卡列表页" else "前往下一个点位"
                        ).apply {
                            setOnDismissListener { _ ->
                                EventBus.getDefault().post(it)
                                finish()
                            }
                        }
                    }
                    return@also
                }
                EventBus.getDefault().post(it)
                startActivity(
                    CruiseCheckInMissionCompleteActivity::class.java,
                    CruiseCheckInMissionCompleteActivity.getParams(it)
                )
                finish()
            }
        }
    }
}