//
//  YHUploadContentVC.swift
//  galaxy
//
//  Created by edy on 2024/3/12.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

class YHUploadContentVC: YHBaseViewController {
    
    var items:[String] = ["1", "2", "2", "2", "2", "2", "2", "2"]
    
    var renameInputView: YHFileRenameInputView = {
        let view = YHFileRenameInputView.inputView(defalutText:"adfasfsf", editBlock: {
            text in
            print("\(text)")
        })
        return view
    }()

    lazy var blackMaskView: UIView = {
        let view = UIView(frame:UIScreen.main.bounds)
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissed))
        view.addGestureRecognizer(tap)
        view.isHidden = true
        return view
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateNameCell.self, forCellReuseIdentifier: YHCertificateNameCell.cellReuseIdentifier)
        let size = headView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
        let rect = CGRect(x: 0, y: 0, width: 0, height: size.height)
        headView.frame = rect
        tableView.tableHeaderView = headView

        return tableView
    }()
    
    lazy var headView:UIView = {
        let view = UIView()
        view.addSubview(templateTitleLabel)
        view.addSubview(tipsLabel)
        view.addSubview(templateView)
        
        templateTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(16)
            make.height.equalTo(24.0)
        }
        tipsLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(templateTitleLabel.snp.bottom).offset(5)
            make.height.equalTo(44)
        }
        templateView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(tipsLabel.snp.bottom).offset(15)
            make.height.equalTo(62.0)
            make.bottom.equalToSuperview().offset(-34)
        }
        return view
    }()
    
    lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.labelTextColor2
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize:12)
        label.numberOfLines = 0
        label.text = "注意事项：这里是上传应该注意的事项这里是上传应该注意的事项这里是上传应该注意的事项。"
        return label
    }()
    
    lazy var templateTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .left
        label.font = UIFont.PFSC_M(ofSize:17)
        label.text = "身份证示例模版"
        return label
    }()
    
    lazy var templateView: YHCertificateSampleTemplateView = {
        let view = YHCertificateSampleTemplateView(frame:CGRectZero)
//        let tap = UITapGestureRecognizer(target:self, action:#selector(action(_:)))
//        view.addGestureRecognizer(tap)
        return view
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "上传内容"
        addKeyBoardNotify()
        createUI()
    }
    
    deinit {
        removeNotify()
    }
    
    func createUI() {

        view.addSubview(tableView)
        view.addSubview(blackMaskView)
        view.addSubview(renameInputView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalTo(view)
            make.bottom.equalToSuperview().offset(-k_Height_safeAreaInsetsBottom())
        }
        renameInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHFileRenameInputView.height)
            make.bottom.equalToSuperview().offset(YHFileRenameInputView.height)
        }
    }
}

extension YHUploadContentVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let item = items[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateNameCell.cellReuseIdentifier, for: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55.0
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 24.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .left
        label.font = UIFont.PFSC_M(ofSize:17)
        label.text = "身份证件"
        view.addSubview(label)
        
        let statusLabel = UILabel()
        statusLabel.textColor = .warnColor
        statusLabel.backgroundColor = .warnColor8
        statusLabel.textAlignment = .center
        statusLabel.font = UIFont.PFSC_M(ofSize:10)
        statusLabel.text = "审核中"
        view.addSubview(statusLabel)
        
        label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(24.0)
            make.centerY.equalToSuperview()
        }
        
        statusLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(label.snp.right).offset(4)
            make.height.equalTo(16)
            make.width.equalTo(38)
        }

        return view
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 60.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        
        let label = UILabel(frame: CGRect(x: 0, y: 20, width:KScreenWidth, height:20))
        label.textColor = UIColor.labelTextColor2
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize:12)
        label.text = "*最多上传5/99张图片或文件"
        view.addSubview(label)
        
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if true {
            let items = [YHCertificateEditItem(type:.rename, title:"重命名"),
                         YHCertificateEditItem(type:.preview, title:"预览"),
                         YHCertificateEditItem(type:.delete, title:"删除"),
                         YHCertificateEditItem(type:.cancel, title:"取消")]
            YHCertificateEditSheetView.sheetView(items:items) {
                [weak self] editType in
                guard let self = self else { return }
                print("editType:\(editType.rawValue)")
                if editType == .rename {
                    IQKeyboardManager.shared.enable = false
                    renameInputView.textField.becomeFirstResponder()
                }
            }.show()
            return
        }
    }
    
    @objc func dismissed() {
        renameInputView.textField.resignFirstResponder()
    }
}

extension YHUploadContentVC {
    
    func addKeyBoardNotify() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func removeNotify() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if let userInfo = notification.userInfo {
            
            guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {return }

            let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
            self.blackMaskView.isHidden = !isKeyboardShow
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileRenameInputView.height)
            
            if !isKeyboardShow {
                IQKeyboardManager.shared.enable = true
            }
            
            self.renameInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}
