//
//  SHRecordDetailsVC.swift
//  ShorthandMaster
//
//  Created by 明津李 on 2020/9/23.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit

class SHRecordDetailsVC: SHBaseViewController {

    @IBOutlet weak var tableView: UITableView?
    @IBOutlet weak var tableFooterView: UIView?
    @IBOutlet weak var tableFooterAlertBgView: UIView?
    @IBOutlet weak var maskView: UIView?
    @IBOutlet weak var bottomHeightConstraint: NSLayoutConstraint?
    @IBOutlet weak var markAlertView: UIView?
    
    let bottomView = SHRecordDetailsBottomView.loadFromNibAndClass(SHRecordDetailsBottomView.self)
    var edit: Bool = false
    var currentModel = SHRecordFolderModel()
    var selectRecordModels:[SHRecordModel] = []
    let keyValueStore = NSUbiquitousKeyValueStore.default
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        updateocloudUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        bottomView?.isHidden = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        bottomView?.isHidden = true
    }

    override func setupUI() {
        self.navigationItem.title = currentModel.name
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "编辑", style: .done, target: self, action: #selector(editClick))
        self.navigationItem.rightBarButtonItem?.tintColor = UIColor.init(hexStr: "4183F4")
        
        tableView?.estimatedRowHeight = 44
        tableView?.rowHeight = UITableView.automaticDimension
        tableView?.separatorStyle = .none
        
        bottomView?.frame = CGRect.init(x: -tableFooterView!.frame.width, y: 0, width: tableFooterView!.frame.width*2, height: tableFooterView!.frame.height)
        tableFooterAlertBgView?.addSubview(bottomView!)
        
        bottomView?.selectCallBack = { [self] (index, selected) in
            switch index {
            case 100:
                for (_, model) in currentModel.dataSources.enumerated(){
                    model.selected = selected
                    if selected == true {
                        if selectRecordModels.contains(model) != true{
                            selectRecordModels.append(model)
                        }
                    }else{
                        if selectRecordModels.contains(model) == true{
                            if let index = selectRecordModels.firstIndex(of: model) {
                                selectRecordModels.remove(at: index)
                            }
                        }
                    }
                }
                tableView?.reloadData()
                break
            case 101:
                self.moveFile()
                break
            case 102:
                self.deleteFile()
                break
            case 103:
                self.markAlertViewShow(selected)
                break
            default:
                break
            }
        }
    }
    //MARK:XXXXXXXXX
    func updateocloudUI(_ update: Bool = true){
        
        switch CRUserDefaults.sortType {
        case 0:
            currentModel.dataSources.sort { (model0, model1) -> Bool in
                return model0.createDate.compare(model1.createDate) == ComparisonResult.orderedDescending
            }
            break
        default:
            currentModel.dataSources.sort { (model0, model1) -> Bool in
                return model0.modifyDate.compare(model1.modifyDate) == ComparisonResult.orderedDescending
            }
            break
        }
        
        for recordModel in self.currentModel.dataSources {
            recordModel.icloud = false
        }
        for folderModel in SHCloudManager.shared.icloudFolderModels{
            if self.currentModel.id == folderModel.id {
                for recordModel in self.currentModel.dataSources {
                    for icloudRecordModel in folderModel.dataSources {
                        if recordModel.pathFile == icloudRecordModel.pathFile {
                            recordModel.icloud = icloudRecordModel.icloud
                        }
                    }
                }
            }
        }
        if update {
            DispatchQueue.main.async {
                self.tableView?.reloadData()
            }
        }
    }
    
    @objc func editClick(_ restore:Bool){
        
        if restore == false{
            if currentModel.dataSources.count == 0 {
                return
            }
            
            edit = !edit
        }else {
            edit = false
        }

        if edit {
            
            for model in currentModel.dataSources{
                model.selected = false
            }
            self.selectRecordModels = []
            
            self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "完成", style: .done, target: self, action: #selector(editClick))
            
            UIView.animate(withDuration: 0.25) {
                self.bottomView?.frame = CGRect.init(x: 0, y: 0, width: self.tableFooterView!.frame.width*2, height: self.tableFooterView!.frame.height)
            }
            
        }else{
            self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "编辑", style: .done, target: self, action: #selector(editClick))
            UIView.animate(withDuration: 0.25) {
                self.bottomView?.frame = CGRect.init(x: -self.tableFooterView!.frame.width, y: 0, width: self.tableFooterView!.frame.width*2, height: self.tableFooterView!.frame.height)
            }
            self.bottomView?.deleteSelected = false
        }
        self.navigationItem.rightBarButtonItem?.tintColor = UIColor.init(hexStr: "4183F4")
        self.tableView?.reloadData()
    }
}

//MARK:bottomSelector
extension SHRecordDetailsVC {
    //MARK:选中Models
    func selectModel(_ index:NSInteger, selected:Bool){
        let model = currentModel.dataSources[index]
        model.selected = selected
        
        if model.selected == true {
            selectRecordModels.append(model)
        }else{
            if let index = selectRecordModels.firstIndex(where: { $0.pathFile == model.pathFile}) {
                selectRecordModels.remove(at: index)
            }
        }
        if selectRecordModels.count == currentModel.dataSources.count {
            bottomView?.deleteSelected = true
        } else {
            bottomView?.deleteSelected = false
        }
    }
    
    //MARK:转移Models
    func moveFile(){
        if selectRecordModels.count == 0 {
            return
        }
        
        let move = UIStoryboard.init(name: "Record", bundle: nil).instantiateViewController(withIdentifier: "SHRecordMoveFileVC") as! SHRecordMoveFileVC
        move.currentModel = currentModel
        move.moveFiles = selectRecordModels
        let nav = SHBaseNavigationController.init(rootViewController: move)
        self.navigationController?.present(nav, animated: true, completion: nil)
        move.saveSuccessCallBack = { model in
            self.currentModel = model
            for model in self.currentModel.dataSources {
                model.selected = false
            }
            self.selectRecordModels = []
            DispatchQueue.main.async {
                self.editClick(true)
                self.updateocloudUI()
            }
        }
    }
    //MARK:icloud上传Models
    func icloundUpload(_ index:NSInteger){
        let model = currentModel.dataSources[index]

        var contains = false
        for folderModel in SHCloudManager.shared.icloudFolderModels {
            if currentModel.id == folderModel.id {
                contains = true
                break
            }
        }
        
        if contains {
            SHCloudManager.shared.addNewRecord(model) { (result, models) in
                if result {
                    model.icloud = true
                    SHCloudManager.shared.modifyFolder(self.currentModel) { (result, models) in
                        if result {
                            self.updateocloudUI()
                        }
                    }
                }
            }
        } else {
            SHCloudManager.shared.addNewRecord(model) { (result, models) in
                if result {
                    model.icloud = true
                    SHCloudManager.shared.addNewFolder(self.currentModel) { (result, models) in
                        if result {
                            self.updateocloudUI()
                        }
                    }
                }
            }
        }
    }
    //MARK:icloud 移除 Models
    func icloundRemove(_ index:NSInteger){
        let model = currentModel.dataSources[index]

        SHCloudManager.shared.deleteRecord(model) { (result, models) in
            if result {
                model.icloud = false
                SHCloudManager.shared.modifyFolder(self.currentModel) { (result, models) in
                    if result {
                        self.updateocloudUI()
                    }
                }
            }
        }
    }
    //MARK:删除Models
    func deleteFile(){
        if selectRecordModels.count == 0 {
            return
        }
        
        let nowDate = Date()
        for model in selectRecordModels {
            if currentModel.dataSources.contains(model) {
                if let index = currentModel.dataSources.firstIndex(where: { $0.pathFile == model.pathFile}) {
                    currentModel.dataSources.remove(at: index)
                }
            }
        }
        
        let list = CRUserDefaults.recordList
        if var recordList = list{
            for (index, subDict) in recordList.enumerated(){
                let subFolderModel:SHRecordFolderModel = getDataDictWith(dict: subDict)
                if subFolderModel.id == currentModel.id {
                    subFolderModel.modifyDate = nowDate
                    subFolderModel.dataSources = currentModel.dataSources
                    let dic = getDictWith(obj: subFolderModel)
                    recordList[index] = dic
                    break
                }
            }
            CRUserDefaults.recordList = recordList
        }
        
        for model in selectRecordModels {
            SHCloudManager.shared.deleteRecord(model) { (result, models) in
                if result {
    
                }
            }
        }
        SHCloudManager.shared.modifyFolder(self.currentModel) { (result, models) in
            if result {
                self.updateocloudUI()
            }
        }

        if currentModel.dataSources.count == 0 {
            self.editClick(true)
            self.markAlertViewShow(false)
            bottomView?.cancel = true
        }
        selectRecordModels = []
//        edit = false
        tableView?.reloadData()
    }
    //MARK:笔记弹框
    func markAlertViewShow(_ selected:Bool){
        
        self.view.layoutIfNeeded()
        if selected == false {
            UIView.animate(withDuration: 0.25) {
                self.bottomHeightConstraint?.constant = 60
                self.view.layoutIfNeeded()
            }
        }else{
            UIView.animate(withDuration: 0.25) {
                self.bottomHeightConstraint?.constant = 120
                self.view.layoutIfNeeded()
            }
        }
    }
    //MARK:笔记弹框入口
    @IBAction func markAlertBtnClick(_ sender:UIButton){
        self.markAlertViewShow(false)
        bottomView?.cancel = true
        switch sender.tag {
        case 200:
            let input = SHInputController.init()
            input.folderModel = currentModel
            self.navigationController?.pushViewController(input, animated: true)
            
            input.saveSuccessCallBack = { model in
                self.currentModel = model
                self.updateocloudUI()
            }
            
            break
        default:
            let record = UIStoryboard.init(name: "Record", bundle: nil).instantiateViewController(withIdentifier: "SHRecordViewController") as! SHRecordViewController
            record.folderModel = currentModel
            self.navigationController?.pushViewController(record, animated: true)
            
            record.saveSuccessCallBack = { model in
                self.currentModel = model
                self.updateocloudUI()
            }
            break
        }
    }
}

extension SHRecordDetailsVC: UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if currentModel.dataSources.count == 0 {
            self.view.bringSubviewToFront(maskView!)
            self.view.bringSubviewToFront(tableFooterView!)
        }else {
            self.view.sendSubviewToBack(maskView!)
        }
        bottomView?.recordCount = self.currentModel.dataSources.count
        return currentModel.dataSources.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "SHRecordDetailsCell", for: indexPath) as! SHRecordDetailsCell
        let model = currentModel.dataSources[indexPath.row]
        cell.model = model
        cell.edit = edit
        cell.selectCallBack = { (type, selected) in
            if type == 0 {
                self.selectModel(indexPath.row, selected: selected)
            }else{
                if model.icloud == false{
                    self.icloundUpload(indexPath.row)
                }else{
                    self.icloundRemove(indexPath.row)
                }
            }
        }
        
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                
//        let show = UIStoryboard.init(name: "Record", bundle: nil).instantiateViewController(withIdentifier: "SHRecordShowViewController") as! SHRecordShowViewController
//        show.model = currentModel.dataSources[indexPath.row]
//        self.navigationController?.pushViewController(show, animated: true)
        
        let input = SHInputController.init()
        input.folderModel = currentModel
        input.dataModel = currentModel.dataSources[indexPath.row]
        self.navigationController?.pushViewController(input, animated: true)
        
        input.saveSuccessCallBack = { model in
            self.currentModel = model
            self.updateocloudUI()
        }
        
    }
}
