//
//  SHRecordListViewController.swift
//  ShorthandMaster
//
//  Created by 明津李 on 2020/8/24.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit
import CloudKit
import IQKeyboardManagerSwift

class SHRecordListViewController: SHBaseViewController {
    
    @IBOutlet weak var tableHeaderView: UIView?
    @IBOutlet weak var tableView: UITableView?
    
    @IBOutlet weak var maskView: UIView!
    @IBOutlet weak var maskHintLab: UILabel?
    @IBOutlet weak var maskHintImv: UIImageView?
    
    @IBOutlet weak var markCountLab: UILabel?
    @IBOutlet weak var advertBtn: UIButton?
    @IBOutlet weak var bottomHeight: NSLayoutConstraint?
    
    let keyValueStore = NSUbiquitousKeyValueStore.default
    var dataSources: Array<SHRecordFolderModel> = []
    var searchDataSource: Array<Array<AnyObject>> = []
    var topDataSources: Array<SHRecordFolderModel> = []
    var recordsDataSource: Array<SHRecordModel> = []
    
    var searchView: UISearchBar!
    lazy var searchBarVC: UISearchController = {
        let searchBarVC = UISearchController.init(searchResultsController: nil)
        searchBarVC.delegate = self
        searchBarVC.searchBar.delegate = self
        searchBarVC.searchResultsUpdater = self
        searchBarVC.dimsBackgroundDuringPresentation = false
        searchBarVC.hidesNavigationBarDuringPresentation = true
        searchBarVC.searchBar.placeholder = "搜索";
        searchBarVC.searchBar.searchBarStyle = .minimal;
        UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "    取消    "
        
        self.definesPresentationContext = true
        return searchBarVC
    }()
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        prepareDateSource()
        self.tableView?.reloadData()
        
        advertBtn?.isHidden = SHUserAccountManager.shared.isMember
        bottomHeight?.constant = SHUserAccountManager.shared.isMember ? 44 : 84
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.searchBarVC.isActive = false
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()

//        let s:Bool = "asdasdas🐂aadsasddadas".isContainEmoji()
        
        SHCloudManager.shared.getAllFolderDataSource { (result, models) in
            if result{

                var localFolder:[SHRecordFolderModel] = []
                if var list = CRUserDefaults.recordList {
                    for dict in list {
                        var folderModel = SHRecordFolderModel()
                        folderModel = getDataDictWith(dict: dict)
                        localFolder.append(folderModel)
                    }
                    for model in models{
                        let containModel = localFolder.filter { $0.id == model.id }.first
                        if containModel == nil {
                            list.append(getDictWith(obj: model))
                        }
                    }
                    CRUserDefaults.recordList = list
                }else{
                    var list:[Dictionary<String, Any>] = []
                    for model in models{
                        list.append(getDictWith(obj: model))
                    }
                    CRUserDefaults.recordList = list
                }
                DispatchQueue.main.async {
                    self.prepareDateSource()
                }
            }
        }
        
        setupUI()
        preposeMember()
        MobClick.event("tab_imp")
        SHUserAccountManager.shared.logCollection(with: .tabImp)
    }
    
    override func setupUI(){
        
        self.navigationItem.title = "笔记本"
        let rightImage = UIImage.init(named: "record_nav_user")?.withRenderingMode(.alwaysOriginal)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: rightImage, style: .plain, target: self, action: #selector(userCilck))
        let leftImage = UIImage.init(named: "record_nav_setting")?.withRenderingMode(.alwaysOriginal)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: leftImage, style: .plain, target: self, action: #selector(mineCilck))
        
        searchView = searchBarVC.searchBar
        searchView.frame = CGRect(x: 8, y: 0, width: SCREEN_WIDTH-16, height: 56)
        self.tableHeaderView?.addSubview(searchView)

        tableView?.tableFooterView = UIView.init()
        
        tableView?.estimatedRowHeight = 44
        tableView?.rowHeight = UITableView.automaticDimension
    }
    
    func prepareDateSource(){
        //TODO:刷新数据
        dataSources = []
        topDataSources = []
        
        if CRUserDefaults.sortType == nil{
            CRUserDefaults.sortType = 0
        }
        
        let nowDate = Date()
        if let list = CRUserDefaults.recordList {
            
            var folderModel = SHRecordFolderModel()
            if let sub = list.first{
                folderModel = getDataDictWith(dict: sub)
                if folderModel.id.length == 0 {
                    folderModel.createDate = nowDate
                    folderModel.modifyDate = nowDate
                    folderModel.name = "默认笔记本";
                    folderModel.id = nowDate.milliStamp
                    
                    for dic in list.reversed(){
                        var model = SHRecordModel()
                        model = getDataDictWith(dict: dic)
                        folderModel.dataSources.append(model)
                    }
                    
                    let modifyDateSortDataSources = folderModel.dataSources.sorted { (model0, model1) -> Bool in
                        return model0.modifyDate.compare(model1.modifyDate) == ComparisonResult.orderedDescending
                    }
                    folderModel.modifyDate = modifyDateSortDataSources.first?.modifyDate ?? nowDate
                    
                    let modelDict = getDictWith(obj: folderModel)
                    CRUserDefaults.recordList = [modelDict]
                }
            }
            
            for dict in list.reversed(){
                var model = SHRecordFolderModel()
                model = getDataDictWith(dict: dict)
                if model.top == true {
                    topDataSources.append(model)
                }else{
                    dataSources.append(model)
                }
            }
        }

        switch CRUserDefaults.sortType {
        case 0:
            dataSources.sort { (model0, model1) -> Bool in
                return model0.createDate.compare(model1.createDate) == ComparisonResult.orderedDescending
            }
            topDataSources.sort { (model0, model1) -> Bool in
                return model0.createDate.compare(model1.createDate) == ComparisonResult.orderedDescending
            }
            break
        default:
            dataSources.sort { (model0, model1) -> Bool in
                return model0.modifyDate.compare(model1.modifyDate) == ComparisonResult.orderedDescending
            }
            topDataSources.sort { (model0, model1) -> Bool in
                return model0.modifyDate.compare(model1.modifyDate) == ComparisonResult.orderedDescending
            }
            break
        }
        
        dataSources = topDataSources+dataSources
        
        /*
        let path = DocumentPath + "/" + DefaultRecordName
        if dataSources.count == 0 && FileManager.default.fileExists(atPath: path) == false{
            
            //没有 先创建
            try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            
            let folderModel = SHRecordFolderModel()
            folderModel.createDate = nowDate
            folderModel.modifyDate = nowDate
            folderModel.name = DefaultRecordName
            folderModel.id = DefaultRecordName + "000"
            
            let recordModel = SHRecordModel()
            recordModel.recordingType = 0
            recordModel.createDate = nowDate
            recordModel.modifyDate = nowDate
            recordModel.address = "默认笔记"
            recordModel.rename = "默认笔记"
            recordModel.txt = ""
            recordModel.pathFile = "/" + DefaultRecordName + RecordMp3
            recordModel.pcmPathFile = ""
            recordModel.during = 0
            recordModel.imagesPath = []
            recordModel.imagesIndex = []
            
//            let images = ["goods_bg"]
//            let indexs = [0]
//            for (index, imageStr) in images.enumerated(){
//                let image = UIImage.init(named: imageStr)
//                let filePath = DocumentPath+"/"+DefaultRecordName+"/"+"\(index).jpeg"
//                let imageData = image!.jpegData(compressionQuality: 1)
//                try? imageData?.write(to: URL(fileURLWithPath: filePath))
//                recordModel.imagesPath.append("/"+DefaultRecordName+"/"+"\(index).jpeg")
//                recordModel.imagesIndex.append(indexs[index])
//            }
//
//            let mp3Path = Bundle.main.path(forResource: "callRing", ofType: "mp3")
//            //路径找不到就会报内存错误的
//            let soundUrl = URL(fileURLWithPath: mp3Path!)
//            if let videoData = try? Data(contentsOf: soundUrl){
//                SHMp3RecordManager.shared().write(videoData, path: DocumentPath + "/" + DefaultRecordName + RecordMp3)
//            }
            
            let modelDict = getDictWith(obj: folderModel)
            CRUserDefaults.recordList = [modelDict]
            
            dataSources.append(folderModel)
        }
 */
        
        recordsDataSource = []
        for folder in dataSources{
            for model in folder.dataSources{
                recordsDataSource.append(model)
            }
        }
        
        tableView?.reloadData()
        
        maskHintLab?.text = "点击右上角添加笔记本"
        maskHintImv?.image = UIImage.init(named: "recordlist_no_data")
        if dataSources.count == 0 {
            self.view.bringSubviewToFront(maskView)
        }else {
            CRUserDefaults.isFirstRecord = true
            self.view.sendSubviewToBack(maskView)
        }
        markCountLab?.text = "笔记本总数：\(dataSources.count)"
    }
    
    @objc func mineCilck(){
        let mine = UIStoryboard.init(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "SHMineViewController") as! SHMineViewController
        self.navigationController?.pushViewController(mine, animated: true)
    }
    
    @objc func userCilck(){
        /*
        let contains = self.dataSources.contains(where: { $0.id == DefaultRecordName + "000" })
        
        if SHUserAccountManager.shared.isMember == false {
            if self.dataSources.count > 1 && contains == true {
                self.goGoods("new_notebook_add")
                return
            }
            if self.dataSources.count > 0 && contains == false {
                self.goGoods("new_notebook_add")
                return
            }
        }
        */
        if SHUserAccountManager.shared.isMember == false && self.dataSources.count > 0{
            self.goGoods("new_notebook_add")
            return
        }
        addModel()
    }
    
    @objc func preposeMember(){
        SHUserAccountManager.shared.getUserInfo({ (model) in
            
            SHUserAccountManager.shared.getNovelInfo { (json) in
                if SHUserAccountManager.shared.isMember == false && SHUserAccountManager.shared.isStartFront == true{
                    self.goGoods("home_pop")
                }
            }
            
            self.advertBtn?.isHidden = SHUserAccountManager.shared.isMember
            self.bottomHeight?.constant = SHUserAccountManager.shared.isMember ? 44 : 84
            
        }, failure: {
            
        })
    }
    
    @IBAction func advertBtnClick(){
        if SHUserAccountManager.shared.isMember == false{
            self.goGoods("home_pay")
            return
        }
    }
}

//MARK: 删、重命名、置顶、添加    文件夹
extension SHRecordListViewController {
    func removeModel(_ indexPath: IndexPath){
        AlertControllerTool.alertController(withTitle: "提示", message: "确定要删除此文件夹吗？", cancelTitle: "取消", cancel: {

        }, confirmTitle: "删除", confirmTitleColor: UIColor.red, confirmBlock: { message in

            let deleteModel = self.dataSources[indexPath.row]

            if var list = CRUserDefaults.recordList {
                for (index, dic) in list.enumerated(){
                    if dic["id"] as! String == deleteModel.id{
                        list.remove(at: index)
                        break
                    }
                }
                CRUserDefaults.recordList = list
            }
            
            if deleteModel.dataSources.count == 0 {
                SHCloudManager.shared.deleteFolder(deleteModel) { (result, models) in

                }
            }

            self.dataSources.remove(at: indexPath.row)
            self.tableView?.beginUpdates()
            self.tableView?.deleteRows(at: [indexPath], with: .left)
            self.tableView?.endUpdates()

            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(333)) {
                self.prepareDateSource()
            }

        }, finish: nil)
    }
    
    func renameModel(_ indexPath: IndexPath){
        
        let selectModel = self.dataSources[indexPath.row]

        AlertControllerTool.alertController(withTitle: nil, message: nil, alertType: .actionSheet, cancelTitle: "取消", cancel: {

        }, confirmTitle: "重命名", confirmTitleColor: UIColor.init(hexStr: "222222"), confirmBlock: { (message) in

            let rename = SHRecordRenameAlertView.loadFromNibAndClass(SHRecordRenameAlertView.self)!
            rename.placeHolder = selectModel.name
            rename.frame = UIApplication.shared.keyWindow!.bounds
            UIApplication.shared.keyWindow!.addSubview(rename)

            rename.confirmCallBack = { renameStr in

                if var list = CRUserDefaults.recordList {
                    for (index, dic) in list.enumerated(){
                        if dic["id"] as! String == selectModel.id{
                            var subDic = dic
                            subDic["name"] = renameStr
                            list[index] = subDic
        
                            selectModel.name = renameStr
                            break
                        }
                    }
                    CRUserDefaults.recordList = list
                }
                
                SHCloudManager.shared.modifyFolder(selectModel) { (result, models) in
                    
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(333)) {
                    self.prepareDateSource()
                }
            }

        }, finish: nil)
    }
    
    func topModel(_ indexPath: IndexPath){
        
        let deleteModel = self.dataSources[indexPath.row]

        if var list = CRUserDefaults.recordList {
            for (index, dic) in list.enumerated(){
                if dic["id"] as! String == deleteModel.id{
                    var subDic = dic
                    subDic["top"] = !deleteModel.top
                    list[index] = subDic
                    break
                }
            }
            CRUserDefaults.recordList = list
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(333)) {
            self.prepareDateSource()
        }
    }
    
    @objc func addModel(){
        let newFolder = SHRecordRenameAlertView.loadFromNibAndClass(SHRecordRenameAlertView.self)!
        newFolder.placeHolder = "笔记本名称"
        newFolder.title = "新笔记本"
        newFolder.frame = self.view.window?.bounds ?? CGRect.zero
//        self.view.addSubview(newFolder)
        self.navigationController?.view.addSubview(newFolder)

        newFolder.confirmCallBack = { newFolderStr in

            let nowDate = Date()
            let folderModel = SHRecordFolderModel()
            folderModel.createDate = nowDate
            folderModel.modifyDate = nowDate
            folderModel.name = newFolderStr;
            folderModel.id = nowDate.milliStamp
            folderModel.dataSources = []

            let modelDict = getDictWith(obj: folderModel)
  
            if var list = CRUserDefaults.recordList {
                list.append(modelDict)
                CRUserDefaults.recordList = list
            }else{
                let list = [modelDict]
                CRUserDefaults.recordList = list
            }

            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(333)) {
                self.prepareDateSource()
            }
        }
    }
}

//MARK: tableView delegate
extension SHRecordListViewController: UITableViewDelegate, UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.searchBarVC.isActive {
            return 2
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.searchBarVC.isActive {

            return searchDataSource[section].count

        }
        return dataSources.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return kAutoWidth*60
        } else {
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.searchBarVC.isActive {
            if indexPath.section == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "SHRecordListCell", for: indexPath) as! SHRecordListCell
                let folders:[SHRecordFolderModel] = searchDataSource[indexPath.section] as! [SHRecordFolderModel]
                cell.model = folders[indexPath.row]
                cell.searchStr = self.searchBarVC.searchBar.text ?? ""
                cell.selectionStyle = .none
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "SHRecordDetailsCell", for: indexPath) as! SHRecordDetailsCell
                let records:[SHRecordModel] = searchDataSource[indexPath.section] as! [SHRecordModel]
                let model = records[indexPath.row]
                cell.model = model
                cell.edit = false
                cell.icloudBtn?.isHidden = true
                cell.searchStr = self.searchBarVC.searchBar.text ?? ""
                cell.selectionStyle = .none
                cell.separatorInset = UIEdgeInsets.init(top: 0, left: kScreenWidth/2, bottom: 0, right: kScreenWidth/2)
                return cell
            }
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "SHRecordListCell", for: indexPath) as! SHRecordListCell
            cell.model = dataSources[indexPath.row]
            
            cell.selectionStyle = .none
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                
        if self.searchBarVC.isActive {
            if indexPath.section == 0{
                let details = UIStoryboard.init(name: "Record", bundle: nil).instantiateViewController(withIdentifier: "SHRecordDetailsVC") as! SHRecordDetailsVC
                let folders:[SHRecordFolderModel] = searchDataSource[indexPath.section] as! [SHRecordFolderModel]
                details.currentModel = folders[indexPath.row]
                self.navigationController?.pushViewController(details, animated: true)
            } else {
                
                let records:[SHRecordModel] = searchDataSource[indexPath.section] as! [SHRecordModel]
                let recordModel = records[indexPath.row]
                
                let folderModel = self.dataSources.filter({
                    let record = $0.dataSources.filter({ $0.pathFile == recordModel.pathFile }).first
                    if record != nil {
                        return true
                    } else {
                        return false
                    }
                }).first
                
                let input = SHInputController.init()
                input.folderModel = folderModel
                input.dataModel = recordModel
                self.navigationController?.pushViewController(input, animated: true)
                
                input.saveSuccessCallBack = { model in
                    self.searchBarVC.searchBar.text = ""
                    self.prepareDateSource()
                    self.tableView?.reloadData()
                }
            }
        }else{
            let details = UIStoryboard.init(name: "Record", bundle: nil).instantiateViewController(withIdentifier: "SHRecordDetailsVC") as! SHRecordDetailsVC
            details.currentModel = dataSources[indexPath.row]
            self.navigationController?.pushViewController(details, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.searchBarVC.isActive {
            return 50
        }
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if self.searchBarVC.isActive {
            let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 50))
            view.backgroundColor = UIColor.groupTableViewBackground
            let bottomView = UIView.init(frame: CGRect.init(x: 0, y: 10, width: kScreenWidth, height: 40))
            bottomView.backgroundColor = UIColor.white
            view.addSubview(bottomView)
            let lab = UILabel.init(frame: CGRect.init(x: 20, y: 0, width: kScreenWidth-20, height: 40))
            lab.text = section == 0 ? "笔记本" : "笔记"
            lab.font = UIFont.systemFont(ofSize: 14)
            lab.textColor = UIColor.init(hexStr: "999999")
            let line = UIView.init(frame: CGRect.init(x: 20, y: 39, width: kScreenWidth-20, height: 1))
            line.backgroundColor = UIColor.groupTableViewBackground
            bottomView.addSubview(lab)
            bottomView.addSubview(line)
            
            return view
        }else{
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if self.searchBarVC.isActive {
            return false
        }
        return true
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        self.removeModel(indexPath)
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let deleteAction = UITableViewRowAction.init(style: .destructive, title: "删除") { (action, indexPath) in
            self.removeModel(indexPath)
        }
        let renameAction = UITableViewRowAction.init(style: .destructive, title: "重命名") { (action, indexPath) in
            self.renameModel(indexPath)
        }
        
        return [deleteAction, renameAction]
    }
    
    @available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let deleteAction = UIContextualAction.init(style: .destructive, title: "删除") { (action, _, completionHandler) in
            
            self.removeModel(indexPath)
            
            completionHandler(false)
        }
        deleteAction.image = UIImage.init(named: "recordlist_delete")
        deleteAction.backgroundColor = UIColor.init(hexStr: "E93425")
        
        let renameAction = UIContextualAction.init(style: .destructive, title: "重命名") { (action, _, completionHandler) in
            
            self.renameModel(indexPath)
            
            completionHandler(false)
        }
        renameAction.image = UIImage.init(named: "recordlist_rename")
        renameAction.backgroundColor = UIColor.init(hexStr: "BCBCBC")
        
        let config = UISwipeActionsConfiguration.init(actions: [deleteAction, renameAction])
        return config
    }
    
    @available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let selectModel = self.dataSources[indexPath.row]
        
        let deleteAction = UIContextualAction.init(style: .destructive, title: "置顶") { (action, _, completionHandler) in
            
            self.topModel(indexPath)
            
            completionHandler(true)
        }
        deleteAction.image = selectModel.top ? UIImage.init(named: "recordlist_top_cancel") : UIImage.init(named: "recordlist_top")
        deleteAction.backgroundColor = UIColor.init(hexStr: "E93425")

        let config = UISwipeActionsConfiguration.init(actions: [deleteAction])
        return config
    }
}

//MARK: searchBar delegate
extension SHRecordListViewController: UISearchResultsUpdating, UISearchBarDelegate{
    func updateSearchResults(for searchController: UISearchController) {
        
        searchDataSource.removeAll()
        var folderSearchArr: Array<SHRecordFolderModel> = []
        folderSearchArr = ZYPinYinSearch.search(withOriginalArray: dataSources, andSearchText: searchController.searchBar.text, andSearchByPropertyName: "name") as! Array<SHRecordFolderModel>
        
        var recordSearchTitleArr: Array<SHRecordModel> = []
        recordSearchTitleArr = ZYPinYinSearch.search(withOriginalArray: recordsDataSource, andSearchText: searchController.searchBar.text, andSearchByPropertyName: "rename") as! Array<SHRecordModel>
        
        var recordSearchTxtArr: Array<SHRecordModel> = []
        recordSearchTxtArr = ZYPinYinSearch.search(withOriginalArray: recordsDataSource, andSearchText: searchController.searchBar.text, andSearchByPropertyName: "txt") as! Array<SHRecordModel>
        
        let recordSearchArr: Array<SHRecordModel> = (recordSearchTitleArr+recordSearchTxtArr).filterDuplicates({$0.pathFile})
        
        if searchController.searchBar.text?.length == 0 {
            searchDataSource.append(dataSources)
            searchDataSource.append(recordsDataSource)
        }else {
            searchDataSource.append(folderSearchArr)
            searchDataSource.append(recordSearchArr)
        }

        if self.searchBarVC.isActive{
            maskHintLab?.text = "没有找到相关的内容"
            maskHintImv?.image = UIImage.init(named: "recordlist_no_data_search")
            if searchDataSource.count == 0 {
                self.view.bringSubviewToFront(maskView)
            }else {
                self.view.sendSubviewToBack(maskView)
            }
            if self.searchBarVC.searchBar.text?.length == 0 {
                markCountLab?.text = "笔记总数：\(recordsDataSource.count)"
            }else{
                markCountLab?.text = "笔记总数：\(recordSearchArr.count)"
            }
        }
        self.tableView?.reloadData()
    }
}

extension SHRecordListViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.searchBarVC.isActive{
            if #available(iOS 13.0, *) {
                self.searchBarVC.searchBar.searchTextField.resignFirstResponder()
            } else {
                self.view.endEditing(true)
            }
        }
    }
}

//MARK: searchController delegate
extension SHRecordListViewController: UISearchControllerDelegate{
    func willPresentSearchController(_ searchController: UISearchController){
        IQKeyboardManager.shared.enable = false
        UIView.animate(withDuration: 0.25) {
            self.searchView.frame = CGRect(x:0, y: 0, width: SCREEN_WIDTH, height: 56)
 
        
        } completion: { (result) in

        }
    }

    func didPresentSearchController(_ searchController: UISearchController){
        self.searchView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 56)
    }

    func willDismissSearchController(_ searchController: UISearchController){
        IQKeyboardManager.shared.enable = true
        UIView.animate(withDuration: 0.25) {
            self.searchView.frame = CGRect(x: 8, y: 0, width: SCREEN_WIDTH-16, height: 56)
        } completion: { (result) in

        }
    }

    func didDismissSearchController(_ searchController: UISearchController){
        markCountLab?.text = "笔记本总数：\(dataSources.count)"
        searchView.frame = CGRect(x: 8, y: 0, width: SCREEN_WIDTH-16, height: 56)
    }

    func presentSearchController(_ searchController: UISearchController){

    }
}
