//
//  TWDocumentList_Vc.swift
//  TWIM
//
//  Created by YouT on 2020/9/2.
//  Copyright © 2020 fsToone. All rights reserved.
//

import UIKit
import YTBaseKit

 class TWDocumentList_Cell: UITableViewCell {
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var selBtn: UIButton!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var infoLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        selBtn.setImage(UIImage.loadImageFromBundle(in: YTDocumentTool.TYTDocumentImgBundle, nameed: "selbox_normal"), for: UIControl.State.normal)
        selBtn.setImage(UIImage.loadImageFromBundle(in: YTDocumentTool.TYTDocumentImgBundle, nameed: "selbox_sel"), for: UIControl.State.selected)
    }
    
    func configData(_ theModel: TWDocumentModel) {
        selBtn.isSelected = theModel.isSel
        titleLabel.text = theModel.fileName
        infoLabel.text = theModel.fileDate
        iconView.image = UIImage(named: DocumentTools.fileExtension(theModel.fileName))
    }
    
}

public struct TWDocumentModel {
   public var fileName:String
   public var filePath:String
   public var fileDate:String
   public var fileCount:CGFloat
   public var isSel:Bool
    
    mutating func selStateChanged() {
        isSel.toggle()
    }
}


public class TWDocumentList_Vc: UIViewController {
    @IBOutlet weak var curSearchField: UITextField!
    @IBOutlet weak var curTableView: UITableView!
    
    // 列表数据
    private var listDataArr = [TWDocumentModel]()
    // 选择回调
    public var callBack:(([TWDocumentModel])->())?
    public var selectedBlock:((TWDocumentModel)->())?
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "本地文件"
        addCustomerBackItem()
//        addNavRightItem("确定")
        requestLocalData()
    }
    
    func addCustomerBackItem(_ titleStr:String = "") {
        let backBtn = UIButton(type: UIButton.ButtonType.custom)
        backBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        if titleStr.isEmpty {
            backBtn.setImage(UIImage(named: "icon_back_black"), for: .normal)
        }else{
            backBtn.setTitle(titleStr, for: .normal)
            backBtn.setTitleColor(UIColor(hexString: "#333333"), for: UIControl.State.normal)
            backBtn.titleLabel?.font = UIFont(name: "PingFangSC-Medium",size: 16)
        }
        backBtn.addTarget(self, action: #selector(self.backItemAction), for: UIControl.Event.touchUpInside)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
    }
    
    func addNavRightItem(_ titleStr:String = "") {
        let backBtn = UIButton(type: UIButton.ButtonType.custom)
        backBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        backBtn.setTitle(titleStr, for: .normal)
        backBtn.setTitleColor(UIColor(hexString: "#333333"), for: UIControl.State.normal)
        backBtn.titleLabel?.font = UIFont(name: "PingFangSC-Medium",size: 16)
        backBtn.addTarget(self, action: #selector(self.sendAction), for: UIControl.Event.touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: backBtn)
    }
    
    // 读取本地数据
    func requestLocalData() {
        var curListModels = [TWDocumentModel]()
        let localFile = DocumentTools().fileArr
        localFile?.forEach({ (item) in
            if let itemDict = item as? [String:Any] {
                let aModel = TWDocumentModel(fileName: itemDict.stringForKey("name"), filePath: itemDict.stringForKey("fullpath"), fileDate: itemDict.stringForKey("time"), fileCount: itemDict.stringForKey("count").floatValue(), isSel: false)
                curListModels.append(aModel)
            }
        })
        listDataArr = curListModels
        curTableView.reloadData()
    }
    
    @objc func sendAction() {
        let selArr = listDataArr.filter {
            $0.isSel == true
        }
        callBack?(selArr)
        navigationController?.popViewController(animated: true)
    }
    
    @objc func backItemAction() {
        if let navigationC = navigationController {
            if navigationC.viewControllers.count == 1 {
                dismiss(animated: true, completion: nil)
            }else{
                navigationController?.popViewController(animated: true)
            }
        }
    }
    
}

extension TWDocumentList_Vc:UITableViewDelegate, UITableViewDataSource {
    
    public func numberOfSections(in tableView: UITableView) -> Int {
        return listDataArr.count
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TWDocumentList_Cell", for: indexPath) as! TWDocumentList_Cell
        let model = listDataArr[indexPath.section]
        cell.configData(model)
        cell.selBtn.tag = indexPath.section
        cell.selBtn.addTarget(self, action: #selector(self.itemDidSel(_:)), for: UIControl.Event.touchUpInside)
        return cell
    }
    
    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = listDataArr[indexPath.section]
        selectedBlock?(model)
        navigationController?.popViewController(animated: true)
    }
    
    @objc func itemDidSel(_ sender: UIButton) {
        listDataArr[sender.tag].selStateChanged()
        curTableView.reloadData()
    }
    
}


