lmw
2023-06-13 adf8013576cbdd12e5ebea8ff7e32baf5d558b27
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package com.kuanzhai.user.ui.trip
 
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import cn.sinata.xldutils.*
import cn.sinata.xldutils.rxutils.ResultException
import cn.sinata.xldutils.view.SwipeRefreshRecyclerLayout
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.help.Inputtips
import com.amap.api.services.help.InputtipsQuery
import com.amap.api.services.help.Tip
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.autonavi.amap.mapcore.Inner_3dMap_location
import com.kuanzhai.user.KuanzhaiApplication
import com.kuanzhai.user.db.HistoryDBManager
import com.kuanzhai.user.ui.TransparentStatusBarActivity
import com.kuanzhai.user.dialog.TipDialog
import com.kuanzhai.user.ui.trip.adapter.PositionAdapter
import io.reactivex.Flowable
import com.kuanzhai.user.R
import com.kuanzhai.user.network.entity.Anchor
import com.kuanzhai.user.ui.ChooseCityActivity
import com.kuanzhai.user.ui.crosscity.ConfirmPositionActivity
import com.kuanzhai.user.utils.Const
import io.reactivex.subscribers.DisposableSubscriber
import kotlinx.android.synthetic.main.activity_choose_position_with_map.*
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
 
class ChoosePositionWithMapActivity: TransparentStatusBarActivity() {
    override fun setContentView() = R.layout.activity_choose_position_with_map
 
    private val aMap by lazy {
        mMapView.map
    }
 
    private val isStart by lazy {
        intent.getBooleanExtra("isStart",true)
    }
    private val siteId by lazy { //如果不为零,代表是跨城搜索地址,城市不可切换
        intent.getIntExtra("siteId",0)
    }
    private val isLogistics by lazy { //true物流订单
        intent.getBooleanExtra("isLogistics",false)
    }
    private val footerView by lazy {
        layoutInflater.inflate(R.layout.footer_clear,lv_position,false)
    }
 
    private var disposable: DisposableSubscriber<List<Tip>>? = null
    private val mTips = ArrayList<Tip>() //搜索结果
    private val adapter by lazy {
        PositionAdapter(mTips)
    }
 
    private val cityName by lazy {
        intent.getStringExtra("cityName")
    }
    private val data by lazy { //跨城出行的电子围栏锚点
        intent.getParcelableArrayListExtra<Anchor>("data")
    }
 
 
    override fun initClick() {
        tv_city.setOnClickListener {
            if (siteId == 0)
                startActivityForResult<ChooseCityActivity>(1,"changeRoot" to false)
        }
        tv_back.setOnClickListener {
            finish()
        }
        adapter.setOnItemClickListener { view, position ->
            HistoryDBManager.saveHistory(this,mTips[position],tv_city.text.toString()) //保存搜索记录
            if (siteId!=0){ //跨城,需要跳转判断是否在站点范围内
                startActivityForResult<ConfirmPositionActivity>(2,"name" to mTips[position].name,
                    "address" to if (mTips[position].address.isEmpty()) mTips[position].district else mTips[position].address,
                    "lat" to mTips[position].point.latitude,"lon" to mTips[position].point.longitude,
                    "siteId" to siteId,"code" to mTips[position].adcode,"data" to data)
            }else{
                setResult(Activity.RESULT_OK,intent.putExtra("lat",mTips[position].point.latitude)
                    .putExtra("lon",mTips[position].point.longitude).putExtra("name",mTips[position].name)
                    .putExtra("code",mTips[position].adcode))
                finish()
            }
        }
        footerView.setOnClickListener {
            val tipDialog = TipDialog()
            tipDialog.arguments = bundleOf("msg" to "确定清除历史吗?","ok" to "确定","cancel" to "取消")
            tipDialog.setCallback(object : TipDialog.OnClickCallback{
                override fun onCancel() {
                }
 
                override fun onOk() {
                    HistoryDBManager.clearHistory(this@ChoosePositionWithMapActivity)
                    mTips.clear()
                    adapter.notifyDataSetChanged()
                    adapter.removeFooter()
                }
            })
            tipDialog.show(supportFragmentManager,"tip")
 
        }
    }
 
    override fun initView() {
        tv_city.text =  if (cityName.isNullOrEmpty()) KuanzhaiApplication.chooseCityName else cityName
        if (siteId!=0){ //跨城
            tv_city.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0)
        }
        lv_position.setMode(SwipeRefreshRecyclerLayout.Mode.None)
        lv_position.setLayoutManager(LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false))
        title = if (isLogistics) "设置领取点" else if(isStart) "设置上车点" else if (siteId!=0) "设置下车点" else "设置目的地"
        et_search.hint = if (isLogistics) "在哪里取货?" else if (isStart)  "您从哪里上车" else "您要去哪儿"
 
        lv_position.setAdapter(adapter)
        et_search.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (s.isNullOrEmpty()){
//                    mTips.addAll(HistoryDBManager.getAddressList(this@ChoosePositionWithMapActivity,if (siteId!=0) tv_city.text.toString() else ""))
//                    adapter.isSearch(false)
//                    tv_empty.gone()
//                    if (mTips.isNotEmpty())
//                        adapter.setFooterView(footerView)
                }else{
                    search(s.toString())
                }
            }
 
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
 
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
//        mTips.addAll(HistoryDBManager.getAddressList(this,if (siteId!=0) tv_city.text.toString() else ""))
//        adapter.notifyDataSetChanged()
//        if (mTips.isNotEmpty())
//            adapter.setFooterView(footerView)
        adapter.isSearch(true)
        initMap()
    }
 
    private fun search(keyword: String) {
        //取消以前的订阅
        if (disposable != null && !disposable!!.isDisposed) {
            disposable?.dispose()
        }
        val query = InputtipsQuery(keyword, tv_city.text.toString())
        query.cityLimit = true
        val inputtips = Inputtips(this, query)
        disposable = object : DisposableSubscriber<List<Tip>>() {
 
            override fun onComplete() {
 
            }
 
            override fun onNext(t: List<Tip>?) {
                sysErr("------t-->$t")
                mTips.clear()
                if (t == null) {
 
                } else {
                    mTips.addAll(t.filter { it.point != null && (it.point.latitude != 0.0 || it.point.longitude != 0.0) })
                }
                if (mTips.isEmpty())
                    tv_empty.visible()
                else
                    tv_empty.gone()
                adapter.isSearch(true)
                adapter.removeFooter()
            }
 
            override fun onError(t: Throwable?) {
                if (t is ResultException) {
                    toast(t.message.toString())
                } else {
                    toast("搜索出错啦!")
                }
            }
        }
        Flowable.just(inputtips).ioScheduler().flatMap {
            sysErr("----------inputtips----------")
            val list = try {
                it.requestInputtips()
            } catch (e: Exception) {
                null
            }
            sysErr("----list--->$list")
            if (list == null) {
                Flowable.error(ResultException("没有搜索到相关数据"))
            } else {
                Flowable.just(list)
            }
        }.defaultScheduler().subscribe(disposable)
    }
 
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK&&data!=null){
            if (requestCode == 1){
                tv_city.text = data.getStringExtra("name")
                aMap.animateCamera(
                    CameraUpdateFactory.newLatLngZoom(
                        LatLng(
                            data.getDoubleExtra("lat",0.0),
                            data.getDoubleExtra("lon",0.0)
                        ), 15f
                    )
                )
            } else{
                setResult(resultCode,data)
                finish()
            }
        }
    }
 
    private var locCount = 0L //定位次数
    private fun initMap() {
        val myLocationStyle = MyLocationStyle()
        myLocationStyle.strokeColor(resources.getColor(R.color.colorBrown))
        myLocationStyle.radiusFillColor(resources.getColor(R.color.colorTransBrown))
        myLocationStyle.interval(3000)
        myLocationStyle.anchor(0.5f, 0.5f)
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)//
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_coordinate))
        aMap.myLocationStyle = myLocationStyle//设置定位蓝点的Style
        aMap.uiSettings.isMyLocationButtonEnabled = false//设置默认定位按钮是否显示,非必需设置。
        aMap.uiSettings.setZoomInByScreenCenter(true)
        aMap.uiSettings.isZoomControlsEnabled = false
        aMap.uiSettings.isRotateGesturesEnabled = false
        aMap.uiSettings.isTiltGesturesEnabled = false
        aMap.isMyLocationEnabled = true
        aMap.setOnMyLocationChangeListener {
            it as Inner_3dMap_location
            Log.e(Const.Tag, "选择定位:lat:" + it.latitude + ",lon:" + it.longitude)
            KuanzhaiApplication.lat = it.latitude
            KuanzhaiApplication.lon = it.longitude
            KuanzhaiApplication.address = it.address
            KuanzhaiApplication.cityCode = it.extras.getString("adcode") ?: ""
            if (locCount < 1) {
                aMap.animateCamera(
                    CameraUpdateFactory.newLatLngZoom(
                        LatLng(
                            it.latitude,
                            it.longitude
                        ), 15f
                    )
                )
            }
            locCount++
        }
        aMap.setOnCameraChangeListener(object : AMap.OnCameraChangeListener {
            override fun onCameraChangeFinish(p0: CameraPosition?) {
                getPoi(p0?.target?.latitude ?: 0.0, p0?.target?.longitude ?: 0.0)
            }
 
            override fun onCameraChange(p0: CameraPosition?) {}
        })
    }
 
 
    /**
     *   获取poi信息
     */
    private var poiSearchDisposable: DisposableSubscriber<PoiResult>? = null
    fun getPoi(lat: Double?, lng: Double?) {
        if (lat == null || lng == null) {
            return
        }
        //如果上一次还没处理完,取消订阅
        if (poiSearchDisposable != null && !poiSearchDisposable!!.isDisposed) {
            poiSearchDisposable?.dispose()
        }
        poiSearchDisposable = object : DisposableSubscriber<PoiResult>() {
            override fun onComplete() {
 
            }
 
            override fun onNext(t: PoiResult?) {
                runOnUiThread {
                    mTips.clear()
                    if (t?.pois.isNullOrEmpty()){
                        tv_empty.visible()
                    }else{
                        mTips.addAll((t?.pois?: arrayListOf<PoiItem>()).map {
                            val tip = Tip()
                            tip.name = it.title
                            tip.address = it.snippet
                            tip.adcode = it.adCode
                            tip.setPostion(it.latLonPoint)
                            tip
                        })
                    }
                    adapter.notifyDataSetChanged()
                }
            }
 
            override fun onError(t: Throwable?) {
                runOnUiThread {
                    mTips.clear()
                    tv_empty.visible()
                    adapter.notifyDataSetChanged()
                }
            }
        }
        val query = PoiSearch.Query("", "190000", "")
        val poiSearch = PoiSearch(this, query)
        poiSearch.bound = PoiSearch.SearchBound(LatLonPoint(lat, lng), 1000)
        Flowable.just(poiSearch).ioScheduler().flatMap {
            try {
                val result = poiSearch.searchPOI()
                if (result == null) {
                    Flowable.error(ResultException(""))
                } else
                    Flowable.just(result)
            } catch (e: Exception) {
                e.printStackTrace()
                Flowable.error<PoiResult>(e)
            }
        }.subscribe(poiSearchDisposable)
    }
 
 
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mMapView.onCreate(savedInstanceState)
    }
 
    override fun onResume() {
        super.onResume()
        mMapView.onResume()
    }
 
    override fun onPause() {
        super.onPause()
        mMapView.onPause()
    }
 
    override fun onDestroy() {
        super.onDestroy()
        mMapView.onDestroy()
    }
 
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mMapView.onSaveInstanceState(outState)
    }
 
    override fun onLowMemory() {
        super.onLowMemory()
        mMapView.onLowMemory()
    }
}