CNLiveShopGoodsSearchViewController.swift
22.9 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//
// CNLiveShopGoodsSearchViewController.swift
// metaCode
//
// Created by zx on 2023/12/25.
//
import Foundation
import MJRefresh
import QMUIKit
enum CNSearchType{
/// 搜索普通商品类型
case defaultGoods
/// 搜索关联商品类型
case associateGoods
}
class CNLiveShopGoodsSearchViewController:CNLiveBaseViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate{
/// 搜索历史最大缓存数量
let kCNLiveMaxCacheSearchKeywordKey = 30
/// 历史记录本地缓存key
let kDSSaveShopSearchHistroyData = "kDSSaveShopSearchHistroyData"
/// 搜索关键字
var keyWord:String?
var rightNavBtn:UIButton?
lazy var tableView : UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: KNavigationHeight, width: KSreenWidth, height: KSreenHeight-KNavigationHeight), style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = .white
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom:getSystemTabbarUiOffsetHeight , right: 0)
// tableView.emptyDataSetSource = self
// tableView.emptyDataSetDelegate = self
tableView.separatorStyle = .none
tableView.tableFooterView = UIView.init()
tableView.tableHeaderView = self.cn_tableHeaderView()
tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
self!.loadMoreAction()
})
tableView.mj_footer?.isHidden = true
tableView.register(CNLiveShopGoodsManageListTableViewCell.self, forCellReuseIdentifier: kDSShopGoodsManageListTableViewCellID)
tableView.register(CNLiveShopAssociatedGoodsTableViewCell.self, forCellReuseIdentifier: kDSShopAssociatedGoodsTableViewCellID)
return tableView
}()
/// 搜索结果数据源
lazy var dataArr: NSMutableArray = {
return NSMutableArray()
}()
/// 历史记录数据
lazy var hisDataArr = {
return NSMutableArray()
}()
var searchTextField:UITextField?
/// 页码
var page:Int = 0
var searchType:CNSearchType = .defaultGoods
/// 选中的关联商品
var selectAssociatedGoodsModel:ShopOrderAssociatedGoodsModel?
init(searchType:CNSearchType) {
super.init(nibName: nil, bundle: nil)
self.searchType = searchType
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
navigationBarHidden = false
self.initTopNav()
self.view.addSubview(self.tableView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.searchTextField?.becomeFirstResponder()
self.popGestureRecognizerEnable = false
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.popGestureRecognizerEnable = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tableView.frame = CGRect(x: 0, y: KNavigationHeight, width: KSreenWidth, height: self.view.height-KNavigationHeight)
}
// MARK: - initTopNav
func initTopNav(){
let searchBgView = CNLiveRoundedRectView(frame: CGRect(x: 52, y: get_system_statusBar_height()+(get_system_nav_ui_height()-30)/2, width: self.topNavView.width-52*2, height: 30))
searchBgView.fillColor = HexColor("#F2F2F2")
searchBgView.radius = searchBgView.height/2
self.topNavView.addSubview(searchBgView)
let searchImageView = UIImageView(frame: CGRect(x: 15, y: (searchBgView.height-16)/2, width: 16, height: 16))
searchImageView.clipsToBounds = true
searchImageView.contentMode = .scaleAspectFit
searchImageView.image = UIImage(named: "DS_goods_search_icon")
searchBgView.addSubview(searchImageView)
let searchLine = UIImageView(frame: CGRect(x: searchImageView.right+10, y: (searchBgView.height-11)/2, width: DS_RRV_ONE_PIXEL, height: 11))
searchLine.backgroundColor = HexColor("#999999")
searchBgView.addSubview(searchLine)
let searchTextField = UITextField(frame: CGRect(x: searchLine.right+10, y: 0, width: searchBgView.width-(searchLine.right+10+15), height: searchBgView.height))
searchTextField.attributedPlaceholder = NSAttributedString(string: "请输你要搜索的商品", attributes: [.foregroundColor: HexColor("#D2D2D2")!])
searchTextField.textColor = HexColor("#333333")
searchTextField.font = Font_13
searchTextField.delegate = self
searchTextField.returnKeyType = .search
searchTextField.clearButtonMode = .whileEditing
searchBgView.addSubview(searchTextField)
self.searchTextField = searchTextField
searchTextField.addTarget(self, action: #selector(textFieldDidOnClearAndBecomeFirstResponder), for: .editingChanged)
self.rightNavBtn = UIButton(type: .custom)
self.rightNavBtn?.setTitle("取消", for: .normal)
self.rightNavBtn?.frame = CGRect(x: 0, y: KStatusBarHeight, width: KNavigationHeight-KStatusBarHeight, height: KNavigationHeight-KStatusBarHeight)
self.rightNavBtn?.setTitleColor(HexColor("#ff725c"), for: .normal)
self.rightNavBtn?.addTarget(self, action: #selector(cancelNavBtnAction), for: .touchUpInside)
self.rightNavBtns = [self.rightNavBtn!]
let leftNavBtn = UIButton(type: .custom)
leftNavBtn.setImage(UIImage(named: "DS_goods_search_back_icon"), for: .normal)
leftNavBtn.addTarget(self, action: #selector(rightNavBtnAction), for: .touchUpInside)
self.leftNavBtns = [leftNavBtn]
}
// MARK: - UITableView 代理
func numberOfSections(in tableView: UITableView) -> Int {
if (self.dataArr.count == 0) {
return 0
}
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if self.searchType == .associateGoods{
guard let cell = tableView.dequeueReusableCell(withIdentifier: kDSShopAssociatedGoodsTableViewCellID) as? CNLiveShopAssociatedGoodsTableViewCell
else {
let cell = CNLiveShopAssociatedGoodsTableViewCell()
return cell
}
let goodsModel = self.dataArr[indexPath.row] as! ShopOrderAssociatedGoodsModel
var isSelect = false
if goodsModel.id == self.selectAssociatedGoodsModel!.id{
isSelect = true
}
cell.setModel(model: goodsModel, isSelect: isSelect, keyword: self.keyWord!)
return cell
}else{
guard let cell = tableView.dequeueReusableCell(withIdentifier: kDSShopGoodsManageListTableViewCellID) as? CNLiveShopGoodsManageListTableViewCell
else {
let cell = CNLiveShopGoodsManageListTableViewCell()
return cell
}
cell.editCallBack = { model in
self.editGoodsModel(goodsModel: model)
}
cell.operStateCallBack = { model ,state in
self.operStateWithGoodsModel(goodsModel: model, state: state)
}
cell.editCountCallBack = { model in
self.editGoodsCountModel(goodsModel: model)
}
let model = self.dataArr[indexPath.row] as! ShopOrderAssociatedGoodsModel
cell.setSearchModel(model: model, keyWork: self.keyWord!)
return cell
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let tempView = UIView(frame: CGRect(x: 0, y: 0, width: KSreenWidth, height: 50))
tempView.backgroundColor = .white
if section == 1{
tempView.height = 60
let topView = UIView(frame: CGRect(x: 0, y: 0, width: KSreenWidth, height: 10))
topView.backgroundColor = HexColor("#F9F9F9")
tempView.addSubview(topView)
}
let nameLabel = UILabel(frame: CGRect(x: 10, y: 12 + (section == 1 ? 10 : 0), width: KSreenWidth - 90, height: 26))
nameLabel.textColor = HexColor("#333333")
nameLabel.font = UIFont.boldSystemFont(ofSize: 16)
nameLabel.lineBreakMode = .byTruncatingTail
nameLabel.numberOfLines = 1
nameLabel.text = String(format: "%@-商品", self.keyWord!)
tempView.addSubview(nameLabel)
let lineLabel = UILabel(frame: CGRect(x: 10, y: 49 + (section == 1 ? 10 : 0), width: KSreenWidth - 20, height: DS_RRV_ONE_PIXEL))
lineLabel.backgroundColor = HexColor("#F2F2F2")
tempView.addSubview(lineLabel)
return tempView
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch self.searchType {
case .defaultGoods:
return 167//100
case .associateGoods:
return 167
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let goodsModel = self.dataArr[indexPath.row] as! ShopOrderAssociatedGoodsModel
switch self.searchType {
case .defaultGoods:
let vc = CNLiveShopGoodsDetailsViewController()
vc.goodsId = goodsModel.id
// navigationViewController().pushViewController(vc, animated: pushAnimated)
break
case .associateGoods:
self.selectAssociatedGoodsModel = goodsModel
self.rightNavBtn?.setTitle("确认", for: .normal)
self.tableView.reloadData()
}
}
// MARK: - UIScrollViewDelegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.view.endEditing(true)
}
// MARK: - UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.tag == 666{
let isAllow = (string as NSString).allowWriteString(string: "0123456789")
return !isAllow
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.text?.count ?? 0 > 20{
textField.text = (textField.text! as NSString).substring(to: 20)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.cn_skipGoodsListWithSearchKeyword(searchKeyword: textField.text ?? "")
return true
}
@objc func textFieldShouldClear(_ textField: UITextField) -> Bool {
self.textFieldDidOnClearAndBecomeFirstResponder(textField: textField)
return true
}
@objc func textFieldDidOnClearAndBecomeFirstResponder(textField:UITextField){
if textField.text?.count == 0{
self.rightNavBtn?.setTitle("取消", for: .normal)
self.dataArr.removeAllObjects()
self.tableView.mj_footer?.isHidden = true
self.searchTextField?.text = ""
self.tableView.tableHeaderView = self.cn_tableHeaderView()
self.tableView.reloadData()
self.searchTextField?.becomeFirstResponder()
}
if textField.text?.count ?? 0 > 20{
showMessage(message: "最长20个字!超出部分会在输入完成时自动删除")
}
}
// MARK: - response method
/// 点击历史记录
/// @param button
@objc func hisBtnClick(_ button:UIButton){
self.searchTextField?.text = button.titleLabel?.text
self.cn_skipGoodsListWithSearchKeyword(searchKeyword: button.titleLabel?.text ?? "")
}
/// 删除历史记录
@objc func deleteAllData(){
CNLiveFileManager.shared.deleteKey(resetKey: kDSSaveShopSearchHistroyData)
self.tableView.tableHeaderView = self.cn_tableHeaderView()
self.tableView.reloadData()
}
/// 返回事件
/// @param button 戳发按钮
@objc func rightNavBtnAction(_ button:UIButton){
navigationViewController().popViewController(animated: false)
}
/// 取消或确认选中的搜索商品 事件
/// @param button 戳发按钮
@objc func cancelNavBtnAction(_ button:UIButton){
if self.searchType == .associateGoods && self.selectAssociatedGoodsModel != nil{
// 搜索确认处理
NotificationCenter.default.post(name: Notification.Name.ShopGoodsManage.kDSSelectGoodsNotification, object: self.selectAssociatedGoodsModel)
let vcArray = self.navigationController?.viewControllers
for vc in vcArray!{
// if vc.isKind(of: CNDSDarenReleaseDynamicViewController.self){
// navigationViewController().popToViewController(vc, animated: true)
// return
// }
}
}else{
self.navigationController?.popViewController(animated: true)
}
}
func loadMoreAction(){
self.page += 1
self.requestSearchWordDataWithKeyword(keyword: self.keyWord!, page: self.page)
}
/// 编辑商品
/// @param goodsModel 商品数据
func editGoodsModel(goodsModel:ShopOrderAssociatedGoodsModel){
let vc = CNLiveShopNewProductController()
vc.type = .edit
vc.goodsId = goodsModel.id!
navigationViewController().pushViewController(vc, animated: true)
}
/// 编辑商品库存
/// @param goodsModel 商品数据
func editGoodsCountModel(goodsModel:ShopOrderAssociatedGoodsModel){
let alert = UIAlertController(title: "编辑商品库存", message: "请输入库存数量", preferredStyle: .alert)
alert.addTextField { textField in
textField.delegate = self
textField.keyboardType = .numberPad
textField.returnKeyType = .done
textField.tag = 666
}
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "修改", style: .default, handler: { action in
self.view.endEditing(true)
let textField = alert.textFields?.first
if textField?.text?.count == 0 || textField?.text?.count ?? 0 >= 6{
showMessage(message: "请输入有效的商品库存数量")
return
}
self.requsetEditGoodsCount(count: textField?.text ?? "", goodsModel: goodsModel)
}))
present(alert, animated: true, completion: nil)
}
/// 编辑商品上下架状态
/// @param goodsModel 商品数据
/// @param state 1:上架 2:下架
func operStateWithGoodsModel(goodsModel:ShopOrderAssociatedGoodsModel,state:Int){
var message = ""
if (state == 2) {
message = "确认下架?"
}else {
message = "确认上架?"
}
ConfigAlertManager.shared.presentAlert(title: "", message: message, actionTitles: ["取消","确认"]) { index in
if index == 1 {
showLoading(message: "")
CNLiveShopGoodListViewModel.postChangeGoodsStateWithGoodsId(goodsId: goodsModel.id!, state: "") { result, status in
if status == .success{
for (_,obj) in self.dataArr.enumerated(){
let model = obj as! ShopOrderAssociatedGoodsModel
if model.id == goodsModel.id{
if (model.state == "2") {
model.state = "1"
}else {
model.state = "2"
}
self.tableView.reloadData()
}
}
}else{
showMessage(message: "失败")
return
}
}
}
}
}
// MARK: - 网络请求
/// 搜索接口
/// @param keyword 关键字
func requestSearchWordDataWithKeyword(keyword:String,page:Int){
showLoading(message: "")
CNLiveShopGoodListViewModel.getGetGoodsListWithShopId(shopId: DSUserInfoManager.shared.dsUserInfo.id, sortType: "1", state: 0, categoryId: nil, keyword: keyword, page: page) { result, status in
hiddenLoading()
if status == .success{
let dataArr = result as! [ShopOrderAssociatedGoodsModel]
if (self.page == 1 && dataArr.count == 0) {
showMessage(message: "未搜索到相关结果")
self.dataArr.removeAllObjects()
self.tableView.tableHeaderView = self.cn_tableHeaderView()
self.tableView.reloadData()
self.rightNavBtn?.setTitle("取消", for: .normal)
self.searchTextField?.becomeFirstResponder()
}else{
if (page == 1) {
self.dataArr.removeAllObjects()
self.tableView.mj_footer?.isHidden = false
}
/**没有更多数据判断依据为:每页数据默认为20条,如果当前获取的这页数据小于20条,说明没有下页数据*/
if (dataArr.count < 20) {
self.tableView.mj_footer?.isHidden = true
}
self.dataArr.addObjects(from: dataArr)
self.tableView.tableHeaderView = UIView()
self.tableView.reloadData()
}
}else{
showMessage(message: "搜索失败")
}
}
}
/// 设置库存数
/// @param count 库存数
/// @param goodsModel 商品数据
func requsetEditGoodsCount(count:String,goodsModel:ShopOrderAssociatedGoodsModel){
showLoading(message: "")
CNLiveShopGoodListViewModel.postGoodsEditAttrWithShopId(shopId: DSUserInfoManager.shared.dsUserInfo.id!, goodsId: goodsModel.id!, type: 1, value: count) { result, status in
if status == .success{
goodsModel.count = count
self.tableView.reloadData()
}else{
showMessage(message: "操作失败")
}
}
}
func cn_tableHeaderView() -> UIView{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: KSreenWidth, height: 0))
let whiteView = UIView(frame: CGRect(x: 0, y: 0, width: KSreenWidth, height: 0))
whiteView.backgroundColor = .white
headerView.addSubview(whiteView)
let markLab = UILabel(frame: CGRect(x: 25, y: 10, width: KSreenWidth-50, height: 30))
markLab.textColor = HexColor("#898989")
markLab.text = "历史搜索"
markLab.font = Font_15
whiteView.addSubview(markLab)
self.hisDataArr.removeAllObjects()
if (CNLiveFileManager.shared.takeDataKey(key: kDSSaveShopSearchHistroyData)) != nil {
let arr = CNLiveFileManager.shared.takeDataKey(key: kDSSaveShopSearchHistroyData)!
self.hisDataArr.addObjects(from: arr)
}
if self.hisDataArr.count == 0{
whiteView.height = markLab.bottom
headerView.height = whiteView.bottom + 5
return whiteView
}
let floatLayoutView = QMUIFloatLayoutView()
floatLayoutView.padding = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
floatLayoutView.itemMargins = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)
floatLayoutView.minimumItemSize = CGSizeMake(40, 29)// 以2个字的按钮作为最小宽度
whiteView.addSubview(floatLayoutView)
for i in 0..<self.hisDataArr.count{
let button = UIButton(type: .custom)
button.backgroundColor = HexColor("#F9F9F9")
button.setTitleColor(HexColor("#666666"), for: .normal)
button.layer.cornerRadius = 5
button.titleLabel?.lineBreakMode = .byTruncatingTail
button.setTitle(self.hisDataArr[i] as? String, for: .normal)
button.titleLabel?.font = Font_13
button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 10, bottom: 6, right: 10)
button.addTarget(self, action: #selector(hisBtnClick), for: .touchUpInside)
floatLayoutView.addSubview(button)
}
let padding = UIEdgeInsets(top: markLab.bottom, left: 10, bottom: 100, right: 10)
let contentWidth = whiteView.width - UIEdgeInsetsGetHorizontalValue(padding)
let floatLayoutViewSize = floatLayoutView.sizeThatFits(CGSize(width: contentWidth, height: CGFLOAT_MAX))
floatLayoutView.frame = CGRect(x: padding.left, y: padding.top, width: contentWidth, height: floatLayoutViewSize.height)
let lineView = UIView(frame: CGRect(x: 10, y: floatLayoutView.bottom, width: KSreenWidth-20, height: DS_RRV_ONE_PIXEL))
lineView.backgroundColor = HexColor("#F2F2F2")
whiteView.addSubview(lineView)
let deleteAllBtn = UIButton(type: .custom)
deleteAllBtn.frame = CGRect(x: 10, y: lineView.bottom+10, width: KSreenWidth-20, height: 30)
deleteAllBtn.addTarget(self, action: #selector(deleteAllData), for: .touchUpInside)
deleteAllBtn.titleLabel?.font = Font_15
deleteAllBtn.setTitleColor(HexColor("#f5a623"), for: .normal)
deleteAllBtn.setTitle("清除搜索历史", for: .normal)
whiteView.addSubview(deleteAllBtn)
whiteView.height = deleteAllBtn.bottom+10
headerView.height = whiteView.bottom+5
return headerView
}
func cn_skipGoodsListWithSearchKeyword(searchKeyword:String){
var searchKeywordStr = searchKeyword
let text = searchKeywordStr.replacingOccurrences(of: "\u{FFFC}", with: "")
//去除掉首尾的空白字符和换行字符
searchKeywordStr = searchKeywordStr.trimmingCharacters(in: .whitespacesAndNewlines)
if (searchKeywordStr.isEmpty) {
showMessage(message: "搜索关键字不能为空")
return
}
self.view.endEditing(true)
if self.hisDataArr.contains(searchKeywordStr){
self.hisDataArr.remove(searchKeywordStr)
}
self.hisDataArr.insert(searchKeyword, at: 0)
if self.hisDataArr.count > kCNLiveMaxCacheSearchKeywordKey{
self.hisDataArr.removeObjects(in: NSMakeRange(kCNLiveMaxCacheSearchKeywordKey - 1, self.hisDataArr.count - (kCNLiveMaxCacheSearchKeywordKey - 1) - 1))
}
CNLiveFileManager.shared.saveData(object: Array(self.hisDataArr), key: kDSSaveShopSearchHistroyData)
self.page = 1
self.keyWord = searchKeywordStr
self.requestSearchWordDataWithKeyword(keyword: self.keyWord!, page: self.page)
}
}