CNLiveMineAddInfoViewController.swift 15.8 KB
//
//  CNLiveMineAddInfoViewController.swift
//  metaCode
//
//  Created by open on 2023/6/7.
//

import Foundation
import EmptyDataSet_Swift
import MJRefresh

enum CNLiveMineInfoShowType {
    case add//添加身份
    case info//身份信息
    case message//消息中心
}


class CNLiveMineAddInfoViewController : CNLiveBaseViewController, UITableViewDelegate, UITableViewDataSource, UITableViewDragDelegate, UITableViewDropDelegate, EmptyDataSetSource, EmptyDataSetDelegate{
    
    let kCNLiveMineInfoLListTableViewIdentifier = "kCNLiveMineInfoLListTableViewIdentifier"
    let kCNLiveMineStandInfoTableViewIdentifier = "kCNLiveMineStandInfoTableViewIdentifier"
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.dragDelegate = self
        tableView.dropDelegate = self
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        tableView.backgroundColor = HexColor("#F7F8FA")
        tableView.tableFooterView = UIView.init()
        tableView.rowHeight = 100
        tableView.contentInsetAdjustmentBehavior = .scrollableAxes
        tableView.separatorStyle = .none
        tableView.register(MineInfoLListTableViewCell.self, forCellReuseIdentifier: kCNLiveMineInfoLListTableViewIdentifier)
        tableView.register(MineStandInfoTableViewCell.self, forCellReuseIdentifier: kCNLiveMineStandInfoTableViewIdentifier)
        return tableView
    }()
    
    lazy var dataArray: NSMutableArray = {
        var dataArray = NSMutableArray()
        return dataArray
    }()
    
    private lazy var listArray: Array<NewsListModel> = {
        let listArray = Array<NewsListModel>()
        return listArray
    }()
    
    lazy var setButton = {
        let setButton = UIButton.init(type: .custom)
        setButton.frame = CGRectMake(KSreenWidth - 35, (get_system_nav_height() - (get_system_statusBar_height() + 20))/2 + get_system_statusBar_height(), 20, 20)
        setButton.backgroundColor = .white
        setButton.setImage(UIImage(named: "mine_sub_header_note_set"), for: .normal)
        setButton.imageView?.contentMode = .scaleToFill
        setButton.addTarget(self, action: #selector(noteSetAction), for: .touchUpInside)
        return setButton
    }()
    
    lazy var copyButton = {
        let copyButton = UIButton.init(type: .custom)
        copyButton.frame = CGRectMake(KSreenWidth - 70, (get_system_nav_height() - (get_system_statusBar_height() + 20))/2 + get_system_statusBar_height(), 20, 20)
        copyButton.backgroundColor = .white
        copyButton.setImage(UIImage(named: "mine_sub_header_back_up_copy"), for: .normal)
        copyButton.imageView?.contentMode = .scaleToFill
        copyButton.addTarget(self, action: #selector(backCopyAction), for: .touchUpInside)
        return copyButton
    }()
    
    var pageNum: NSInteger
    var network_type: CNLiveMineResponseType!
    var _show_type:CNLiveMineInfoShowType!
    init(show_type:CNLiveMineInfoShowType) {
        self.pageNum = 1
       super.init(nibName:nil, bundle:nil)
        _show_type = show_type
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        switch _show_type {
        case .add:
            titleName = "添加身份"
        case .info:
            titleName = "身份信息"
            tableView.dragInteractionEnabled = true
        case .message:
            titleName = "消息中心"
//            topNavView.addSubview(setButton)
//            topNavView.addSubview(copyButton)
        case .none:
            break
        }
        if _show_type == .info || _show_type == .add {
            showLoading(message: "")
            NotificationCenter.default.addObserver(self, selector: #selector(StandAuthNotificationSuccessAction), name: Notification.Name.StandAuth.StandAuthNotificationSuccess, object: nil)
        }
        loadData()
        addRefreshView()
        navigationBarHidden = false
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(KNavigationHeight)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: Notification.Name.StandAuth.StandAuthNotificationSuccess, object: nil)
    }
    
    private func loadData() {
        if _show_type == .add {
            CNLiveMineViewModel.requestAuthStandList(page: self.pageNum) { [weak self] result, respStatue in
                if respStatue == .success {
                    let listBaseModel = result as! StandListBaseModel
                    if listBaseModel.pageNum == 1 {
                        self!.dataArray.removeAllObjects()
                        self!.dataArray.addObjects(from: (result as! StandListBaseModel).list)
                    }
                    if listBaseModel.pageNum > 1 {
                        self!.dataArray.addObjects(from: (result as! StandListBaseModel).list)
                    }
                    if self!.dataArray.count > 0 {
                        self!.checkAlreadyAuthStatue()
                    }
                    self!.tableView.reloadData()
                    self!.tableView.mj_header?.endRefreshing()
                    self!.tableView.mj_footer?.endRefreshing()
                    if listBaseModel.total == listBaseModel.pageNum {
                        self!.tableView.mj_footer?.endRefreshing()
                        self!.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        self!.tableView.reloadData()
                    }
                }else if (respStatue == .noNetwork) {
                    self!.network_type = .noNetwork
                    self!.tableView.reloadEmptyDataSet()
                } else {
                    self!.network_type = .failed
                    self!.tableView.reloadEmptyDataSet()
                }
            }
        }
        if _show_type == .message {
            CNLiveMineViewModel.requestMessage { [weak self] result, respStatue in
                self!.network_type = respStatue
                if respStatue == .success {
                    self!.listArray = (result as! NewsModel).list
                    self!.tableView.reloadData()
                }else{
                    self!.tableView.reloadEmptyDataSet()
                }
            }
        }
        if _show_type == .info {
            CNLiveMineViewModel.requestsGETAuthInfoList(page: pageNum) { [weak self] result, respStatue in
                if respStatue == .success {
                    let listBaseModel = result as! MineAuthListBaseModel
                    if listBaseModel.pageNum == 1 {
                        self!.dataArray.removeAllObjects()
                        self!.dataArray.addObjects(from: (result as! MineAuthListBaseModel).list)
                    }
                    if listBaseModel.pageNum > 1 {
                        self!.dataArray.addObjects(from: (result as! MineAuthListBaseModel).list)
                    }
                    self!.tableView.reloadData()
                    self!.tableView.mj_header?.endRefreshing()
                    self!.tableView.mj_footer?.endRefreshing()
                    if listBaseModel.total == listBaseModel.pageNum {
                        self!.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        self!.tableView.reloadData()
                    }
                }else if (respStatue == .noNetwork) {
                    self!.network_type = .noNetwork
                    self!.tableView.reloadEmptyDataSet()
                } else {
                    self!.network_type = .failed
                    self!.tableView.reloadEmptyDataSet()
                }
            }
        }
    }
    
    private func addRefreshView() {
        if _show_type == .add || _show_type == .info {
            tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
                self!.pageNum = 1
                self!.loadData()
            })
            
            tableView.mj_footer = MJRefreshBackFooter.init(refreshingBlock: {[weak self] in
                self!.pageNum += 1
                self!.loadData()
            })
        }
    }
    
    /// 判断是不是有已经有认证的情况
    func checkAlreadyAuthStatue() {
        for item in self.dataArray {
            let authModel = item as! StandListModel
            if authModel.auth {
                NotificationCenter.default.post(name: Notification.Name.StandAuth.StandAuthSortNotificationResult, object: nil)
                break
            }
        }
    }
    
    @objc func StandAuthNotificationSuccessAction() {
        self.tableView.mj_header?.beginRefreshing()
    }
    
    
    @objc func noteSetAction() {}
    @objc func backCopyAction() {}
}

extension CNLiveMineAddInfoViewController {
    
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        if network_type == .failed  || network_type == .unkonw {
            return UIImage(named: "mine_list_source_unusual_failed")
        }
        if _show_type == .message && listArray.count == 0 {
            return UIImage(named: "mine_list_source_unusual_empty")
        }
        if network_type == .noNetwork {
            return UIImage(named: "mine_list_source_unusual_noNet")
        }
        return UIImage(named: "mine_list_source_unusual_empty")
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        var defult_string = ""
        if network_type == .failed  || network_type == .unkonw {
            defult_string = "接口请求错误,刷新试试~"
        }
        if network_type == .noNetwork {
            defult_string = "网络开小差了,刷新试试~"
        }
        switch _show_type {
        case .add:
            defult_string = "暂时没有可添加的身份~"
        case .info:
            defult_string = "暂时没有身份信息~"
        case .message:
            if listArray.count == 0 && network_type == .success{
                defult_string = "暂时没有可读的消息~"
            }
        case .none:
            break
        }
        return NSAttributedString(string: defult_string, attributes: [.font: Font_17,.foregroundColor: HexColor("#666666")!])
    }
    
    func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {
        if _show_type == .message && (network_type == .failed || network_type == .noNetwork) {
            let attributes = [NSAttributedString.Key.font:Font_16_Fit,
                              NSAttributedString.Key.foregroundColor: HexColor("#609BFF")]
            return NSAttributedString(string: "刷新", attributes: attributes as [NSAttributedString.Key : Any])
        }
        return nil
    }
    
    func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) {
        loadData()
    }
    
}

extension CNLiveMineAddInfoViewController {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if _show_type == .message {
            return listArray.count
        }
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if _show_type == .add {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: kCNLiveMineInfoLListTableViewIdentifier) as? MineInfoLListTableViewCell else {
                return MineInfoLListTableViewCell()
            }
            let listModel = dataArray[indexPath.row] as! StandListModel
            cell.setupWithDataSource(icon: listModel.icon!, name: listModel.name!, is_auth: listModel.auth)
            cell.userInteractionEnabledWhileDragging = true
            return cell
            
        } else if _show_type == .message {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: kCNLiveMineStandInfoTableViewIdentifier) as? MineStandInfoTableViewCell else {
                return MineStandInfoTableViewCell()
            }
            let listModel = listArray[indexPath.row]
            cell.setupWithMessageDataSource(icon: listModel.poster, name: listModel.title,number: listModel.subTitle, time: listModel.createTimeString)
            cell.userInteractionEnabledWhileDragging = true
            return cell
        } else {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: kCNLiveMineStandInfoTableViewIdentifier) as? MineStandInfoTableViewCell else {
                return MineStandInfoTableViewCell()
            }
            let authModel = dataArray[indexPath.row] as! MineAuthListModel
            cell.setupWithAuthDataSource(icon: authModel.icon!, name: authModel.name!,number: authModel.code!)
            cell.userInteractionEnabledWhileDragging = false
            return cell
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if _show_type == .message {
            let listModel = listArray[indexPath.row]
            self.navigationController?.pushViewController(CNLiveMineMessageViewController.init(listModel: listModel), animated: true)
        }
        if _show_type == .add {
            let listModel = dataArray[indexPath.row] as! StandListModel
            if listModel.auth {
                showMessage(message: "您已添加此身份,请直接使用")
                return
            }
            if listModel.id == 9 {
                CNLiveMineViewModel.requestApplyShopInfo { [weak self] result, respStatue in
                    if respStatue == .success {
                        self?.navigationController?.pushViewController(CNLiveMineShopViewController.init(showType: .one, listModel: listModel, tempArray: []), animated: true)
                    }
                }
            } else {
                self.navigationController?.pushViewController(CNLiveMineInputViewController.init(listModel: listModel), animated: true)
            }
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if _show_type == .message {
            let listModel = listArray[indexPath.row]
            return 76 + listModel.textHeight
        }
        return 100
    }
    func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        let item = UIDragItem(itemProvider: NSItemProvider(object: UIImage()))
        return [item]
    }
    // MARK: UITableViewDropDelegate
    func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {}
    func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
        return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
    }
    func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
        // Only receive image data
        return session.canLoadObjects(ofClass: UIImage.self)
    }
    //移动cell事件
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath,
                   to destinationIndexPath: IndexPath) {
        objc_sync_enter(self)
        if dataArray.count > 1 {
            NotificationCenter.default.post(name: Notification.Name.StandAuth.StandAuthSortNotificationResult, object: nil)
            swap(&dataArray[sourceIndexPath.row], &dataArray[destinationIndexPath.row])
            let tempArray = NSMutableArray()
            for model in dataArray {
                let m = model as! MineAuthListModel
                tempArray.add(m.identityId)
            }
            StandSortManager.insertSortData(indexs: tempArray)
        }
        objc_sync_exit(self)
    }
}