//
//  ALActionSheet.swift
//  GMAlpha
//
//  Created by zhb on 2018/11/24.
//  Copyright © 2018 Gengmei. All rights reserved.
//

import UIKit
/// item文字的颜色
@objc enum ALActionSheetItemType: Int {
    case `default`   // 默认
    case cancel    // 取消
}

/// alertView item的数据
struct ALActionSheetItemObject {
    var title: String
    var type: ALActionSheetItemType
    var color: UIColor
    var handler: ItemClickBlock?
    init(title: String, type: ALActionSheetItemType, color: UIColor, block: ItemClickBlock?) {
        self.title = title
        self.type = type
        self.color = color
        self.handler = block
    }
}

typealias ItemClickBlock = (_ index: Int) -> Void



@objcMembers
class ALActionSheet: UIView {
    fileprivate let tableView = UITableView(frame: .zero, style: .grouped)
    fileprivate var itemObjs = [ALActionSheetItemObject]()
    fileprivate let coverBackView = UIView()
    fileprivate var alertTitle = ""
    fileprivate var cancelItemObj = ALActionSheetItemObject(title: "", type: .cancel, color: UIColor.headlineText, block: nil)
    
    
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setup()
    }
    
    func setup() {
        self.backgroundColor = UIColor.white
        coverBackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(coverBackTapAction)))
        coverBackView.backgroundColor = UIColor.black
        coverBackView.alpha = 0
        coverBackView.frame = Constant.screenBounds
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.registerCell(ALActionSheetCell.self)
        tableView.isScrollEnabled = false
        backgroundColor = UIColor.background
        addSubview(tableView)
        tableView.frame = CGRect(x: 0, y: 0, width: Constant.screenWidth, height: 0)
        tableView.rowHeight = 49
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    // 添加alert title
    func addAlertTitle(_ title: String, color: UIColor) {
        alertTitle = title
        if title.isEmpty {
            return
        }
        let header = UIView(frame: CGRect(x: 0, y: 0, width: Constant.screenWidth, height: 49))
        header.backgroundColor = UIColor.white
        let headerTitle = UILabel()
        headerTitle.textColor = color
        headerTitle.font = UIFont.systemFont(ofSize: 16)
        headerTitle.textAlignment = .center
        headerTitle.frame = CGRect(x: 0, y: 0, width: Constant.screenWidth, height: 49)
        headerTitle.text = title
        header.addSubview(headerTitle)
        header.addBottomLine()
        self.tableView.tableHeaderView = header
    }
    
    func addItem(title: String, style: ALActionSheetItemType, color: UIColor, handle: ItemClickBlock? = nil) {
        if style == .default {
            let itemObj = ALActionSheetItemObject(title: title, type: style, color: color, block: handle)
            itemObjs.append(itemObj)
        } else {
            cancelItemObj = ALActionSheetItemObject(title: title, type: style, color: color, block: handle)
        }
    }
}

// MARK: - UITableViewDataSource, UITableViewDelegate
@objc extension ALActionSheet: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return itemObjs.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeue(cell: ALActionSheetCell.self, for: indexPath) as! ALActionSheetCell
        if indexPath.section == 0 {
            let obj = itemObjs[indexPath.row]
            cell.label.text = obj.title
            cell.label.textColor = obj.color
            cell.bottomLine.isHidden = (indexPath.row == itemObjs.count - 1)
        } else {
            cell.label.text = cancelItemObj.title
            cell.label.textColor = cancelItemObj.color
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            return UIView()
        } else {
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 10
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if itemObjs[indexPath.row].handler != nil {
                itemObjs[indexPath.row].handler!(indexPath.row)
            }
            hide()
        } else {
            if cancelItemObj.handler != nil {
                cancelItemObj.handler!(indexPath.row)
            }
            hide()
        }
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        if newSuperview != nil {
            tableView.reloadData()
            var itemCout = 0
            if alertTitle.isEmpty {
                itemCout = itemObjs.count + 1
            } else {
                itemCout = itemObjs.count + 2
            }
            let alertViewHeight = itemCout * 49 + 10
            tableView.height = CGFloat(alertViewHeight)
            
            var resizedHeight = CGFloat(alertViewHeight)
            if #available(iOS 11.0, *) {
                resizedHeight += newSuperview!.safeAreaInsets.bottom
            }
            self.frame = CGRect(x: 0, y: Constant.screenHeight, width: Constant.screenWidth, height: resizedHeight)
            UIView.animate(withDuration: 0.25, animations: {
                self.top = Constant.screenHeight - self.height
                self.coverBackView.alpha = 0.5
            })
        }
    }
}

// MARK: - action
@objc extension ALActionSheet {
    @objc dynamic func show() {
        UIApplication.shared.keyWindow?.addSubview(coverBackView)
        UIApplication.shared.keyWindow?.addSubview(self)
    }
    
    @objc dynamic func hide() {
        UIView.animate(withDuration: 0.25, animations: {
            self.top = Constant.screenHeight
            self.coverBackView.alpha = 0
        }, completion: { (_) in
            self.removeFromSuperview()
            self.coverBackView.removeFromSuperview()
        })
    }
    
    @objc dynamic func coverBackTapAction() {
        hide()
    }
}

@objcMembers
final class ALActionSheetCell: UITableViewCell {
    lazy var label: UILabel = {
        let label = UILabel.init()
        label.backgroundColor = .clear
        label.textAlignment = .center
        label.textColor = UIColor.headlineText
        label.font = UIFont .systemFont(ofSize: 15)
        return label
    }()
    
    lazy var bottomLine: UIView = {
        let bottomLine = UIView()
        bottomLine.backgroundColor = UIColor.separatorLine
        return bottomLine
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setup() {
        contentView.addSubview(self.label)
        contentView.addSubview(self.bottomLine)
        label.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        bottomLine.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(1/UIScreen.main.scale)
        }
    }
}
