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

import UIKit
import CloudKit

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?
    
    let keyValueStore = NSUbiquitousKeyValueStore.default
    var dataSources: Array<SHRecordFolderModel> = []
    var searchDataSource: Array<SHRecordFolderModel> = []
    var topDataSources: Array<SHRecordFolderModel> = []

    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()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.searchBarVC.isActive = false
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        SHAVAudioManager.shared.start()
        
        let url = FileManager.default.url(forUbiquityContainerIdentifier: nil)
        print(url as Any)
        
        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()
    }
    
    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)
                }
            }
        }

        var list = keyValueStore.object(forKey: "Folderlist") as? [Dictionary<String, Any>]
        if list == nil {
            list = keyValueStore.object(forKey: "list") as? [Dictionary<String, Any>]
        }
        list = nil
        if let list = list {
            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)
                    
                    keyValueStore.set([modelDict], forKey: "Folderlist")
                    keyValueStore.synchronize()
                    print("synchronize ===  \(keyValueStore.synchronize())")
                }
            }
            
//            let modityList = keyValueStore.object(forKey: "Folderlist") as? [Dictionary<String, Any>]
//            if let list = modityList {
//                for dict in list.reversed(){
//                    var model = SHRecordFolderModel()
//                    model = getDataDictWith(dict: dict)
//                    if model.top == true {
//                        topDataSources.append(model)
//                    }else{
//                        dataSources.append(model)
//                    }
//                }
//            }
            
            dataSources = dataSources.filterDuplicates({$0.id})
            topDataSources = topDataSources.filterDuplicates({$0.id})
            
            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
            }
        }else{
            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
        
        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(){
        
//        if SHUserAccountManager.shared.isMember == false {
//            self.goGoods("home_pop")
//        }
        addModel()
    }
    
    @objc func preposeMember(){
        SHUserAccountManager.shared.getNovelInfo { (json) in
            if SHUserAccountManager.shared.isMember == false && SHUserAccountManager.shared.isStartFront == true{
                self.goGoods("home_pay")
            }
        }
    }
    
    @IBAction func advertBtnClick(){
        
    }
    
    @IBAction func goRecord(){
        if CRUserDefaults.isFirstRecord == true{
            if SHUserAccountManager.shared.isMember == false{
                self.goGoods("home_record")
                return
            }
        }

        let record = UIStoryboard.init(name: "Record", bundle: nil).instantiateViewController(withIdentifier: "SHRecordViewController") as! SHRecordViewController
        self.navigationController?.pushViewController(record, animated: true)
    }
}

//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
            }

//            let list = self.keyValueStore.object(forKey: "Folderlist") as? [Dictionary<String, Any>]
//
//            if var list = list {
//                for (index, dic) in list.enumerated(){
//                    if dic["id"] as! String == deleteModel.id{
//                        list.remove(at: index)
//                        break
//                    }
//                }
//                self.keyValueStore.set(list, forKey: "Folderlist")
//                self.keyValueStore.synchronize()
//            }

            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
                            break
                        }
                    }
                    CRUserDefaults.recordList = list
                }

//                let list = self.keyValueStore.object(forKey: "Folderlist") as? [Dictionary<String, Any>]
//
//                if var list = list {
//                    for (index, dic) in list.enumerated(){
//                        if dic["id"] as! String == selectModel.id{
//                            var subDic = dic
//                            subDic["name"] = renameStr
//                            list[index] = subDic
//                            break
//                        }
//                    }
//                    self.keyValueStore.set(list, forKey: "Folderlist")
//                    self.keyValueStore.synchronize()
//                }

                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
        }

//        let list = keyValueStore.object(forKey: "Folderlist") as? [Dictionary<String, Any>]
//
//        if var list = list {
//            for (index, dic) in list.enumerated(){
//                if dic["id"] as! String == deleteModel.id{
//                    var subDic = dic
//                    subDic["top"] = !deleteModel.top
//                    list[index] = subDic
//                    break
//                }
//            }
//            keyValueStore.set(list, forKey: "Folderlist")
//            keyValueStore.synchronize()
//        }

        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(333)) {
            self.prepareDateSource()
        }
    }
    
    @objc func addModel(){
        let newFolder = SHRecordRenameAlertView.loadFromNibAndClass(SHRecordRenameAlertView.self)!
        newFolder.placeHolder = "这是一个新的笔记本名称"
        newFolder.title = "新笔记本"
        newFolder.frame = UIApplication.shared.keyWindow!.bounds
        UIApplication.shared.keyWindow!.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
            }

//            let list = self.keyValueStore.object(forKey: "Folderlist") as? [Dictionary<String, Any>]
//
//            if var list = list {
//                list.append(modelDict)
//                self.keyValueStore.set(list, forKey: "Folderlist")
//                self.keyValueStore.synchronize()
//            }else{
//                let list = [modelDict]
//                self.keyValueStore.set(list, forKey: "Folderlist")
//                self.keyValueStore.synchronize()
//            }

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

//MARK: tableView delegate
extension SHRecordListViewController: UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.searchBarVC.isActive {
            return searchDataSource.count
        }
        return dataSources.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kAutoWidth*60
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "SHRecordListCell", for: indexPath) as! SHRecordListCell

        if self.searchBarVC.isActive {
            cell.model = searchDataSource[indexPath.row]
        }else{
            cell.model = dataSources[indexPath.row]
        }
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                
        let details = UIStoryboard.init(name: "Record", bundle: nil).instantiateViewController(withIdentifier: "SHRecordDetailsVC") as! SHRecordDetailsVC
        if self.searchBarVC.isActive {
            details.currentModel = searchDataSource[indexPath.row]
        }else{
            details.currentModel = dataSources[indexPath.row]
        }
        self.navigationController?.pushViewController(details, animated: true)
    }
    
    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(true)
        }
        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(true)
        }
        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 searchArr: Array<SHRecordFolderModel> = []
        searchArr = ZYPinYinSearch.search(withOriginalArray: dataSources, andSearchText: searchController.searchBar.text, andSearchByPropertyName: "name") as! Array<SHRecordFolderModel>
        
        if searchController.searchBar.text?.length == 0 {
            searchDataSource.append(contentsOf: dataSources)
        }else {
            searchDataSource.append(contentsOf: searchArr)
        }
        self.tableView?.reloadData()

        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)
            }
            markCountLab?.text = "笔记本总数：\(searchDataSource.count)"
        }
    }
}

//MARK: searchController delegate
extension SHRecordListViewController: UISearchControllerDelegate{
    func willPresentSearchController(_ searchController: UISearchController){
        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){
        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){
        searchView.frame = CGRect(x: 8, y: 0, width: SCREEN_WIDTH-16, height: 56)
    }

    func presentSearchController(_ searchController: UISearchController){

    }
}
