//
//  YHAdopterCardOtherGuideView.swift
//  galaxy
//
//  Created by EDY on 2024/8/21.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHAdopterCardOtherGuideView: UIView {
    
    typealias Block = () -> ()
    var block: Block?
    var titleLabel: UILabel!
    var lineView: UIView!
    var tableView: UITableView!
    var data: [String] = ["service_adopter_example_other","service_adopter_example_other1", "service_adopter_example_other2","service_adopter_example_other3","service_adopter_example_other4"]

    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
//        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
//        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        view.addSubview(self.rewardBtn)
        self.rewardBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(44)
        }
        view.layer.zPosition = 10
        return view
    }()
    
    //我已悉知，确认
    lazy var rewardBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("我已悉知，确认", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(clickSureBtn), for: .touchUpInside)
        button.backgroundColor = UIColor.brandMainColor
        return button
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    
    
    private var timer : Timer?
    private var maxCount : Int = 5
    
    //之前是否展示过
    var ischeckBeforeFlag : Bool = false {
        didSet {
            if ischeckBeforeFlag {
                setButtonEnable(true)
            } else {
                setButtonEnable(false)
                startTimer()
            }
        }
    }
}

extension YHAdopterCardOtherGuideView  {
    
    static func sheetView() -> YHAdopterCardOtherGuideView {
        let view = YHAdopterCardOtherGuideView(frame:UIScreen.main.bounds)
        return view
    }
    
    func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
        
        UIView.animate(withDuration: 0.5) {
            let whiteHeight = KScreenHeight - k_Height_NavigationtBarAndStatuBar
            self.whiteContentView.frame = CGRect(x: 0, y: KScreenHeight - whiteHeight, width: KScreenWidth, height: whiteHeight)
        }
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func clickSureBtn() {
        self.block?()
        dismiss()
    }
}

private extension YHAdopterCardOtherGuideView {
    
    @objc func timerFired() {
            // 定时器触发时执行的代码
            print("Timer fired")
        self.maxCount = self.maxCount - 1
        if self.maxCount < 0 {
            self.stopTimer()
            self.setButtonEnable(true)
        } else {
            rewardBtn.setTitle("请上滑看完指引后操作（\(maxCount)s）", for: .normal)
        }
    }
    
    func startTimer() {
        stopTimer()
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .common)
    }
    
    func stopTimer() {
        maxCount = 5
        timer?.invalidate()
        timer = nil
    }
    
    
    func setButtonEnable(_ enable : Bool) {
        rewardBtn.isEnabled = enable
        if enable {
            rewardBtn.setTitle("我已悉知，确认", for: .normal)
            rewardBtn.backgroundColor = UIColor.brandMainColor
        } else {
            rewardBtn.setTitle("请上滑看完指引后操作（5s）", for: .normal)
            rewardBtn.backgroundColor = UIColor(hex: 0xB7C0CC, alpha: 1.0)
            
        }
    }
    
    func setupUI() {
        self.addSubview(blackMaskView)
        self.addSubview(whiteContentView)

        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(16.0, 16.0));
        let layer = CAShapeLayer();
        layer.frame = whiteContentView.bounds;
        layer.path = path.cgPath;
        whiteContentView.layer.mask = layer;
        whiteContentView.clipsToBounds = true
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let whiteHeight = KScreenHeight - k_Height_NavigationtBarAndStatuBar
//        whiteContentView.snp.makeConstraints { make in
//            make.left.right.bottom.equalToSuperview()
//            make.height.equalTo(whiteHeight)
//        }
        whiteContentView.frame = CGRect(x: 0, y: KScreenHeight, width: KScreenWidth, height: whiteHeight)
        titleLabel = {
            let label = UILabel()
            label.text = "其他相关证件说明"
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .left
            return label
        }()
        whiteContentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(21)
            make.right.equalTo(-21)
            make.height.equalTo(21)
            make.top.equalTo(16)
        }
        
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        whiteContentView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(52)
            make.height.equalTo(1)
            make.right.equalTo(-18)
        }
        
        tableView = {
            let tableView = UITableView(frame:.zero, style:.plain)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .white
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHAdopterCardExampleViewTableViewCell.self)
            return tableView
        }()
        whiteContentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(73)
            make.bottom.equalTo(-103)
            make.left.right.equalToSuperview()
        }
        
        whiteContentView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(98)
        }
    }
}

extension YHAdopterCardOtherGuideView : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if !ischeckBeforeFlag {
            let scrollViewContentHeight = scrollView.contentSize.height
            let scrollOffsetThreshold = scrollViewContentHeight - scrollView.bounds.size.height
            
           // 当前滚动位置
           let currentOffset = scrollView.contentOffset.y
           if currentOffset > scrollOffsetThreshold { // 接近底部
               // 滚动到了底部
               ischeckBeforeFlag = true
               stopTimer()
               setButtonEnable(true)
           } else {
               // 没有滚动到底部
           }
        }
    }
}

extension YHAdopterCardOtherGuideView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHAdopterCardExampleViewTableViewCell.self)
        cell.imageName = data[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 1 {
            return 204 + 20
        }
        if indexPath.row == 2 {
            return 147 + 20
        }
        if indexPath.row == 3 {
            return 91 + 20
        }
        if indexPath.row == 4 {
            return 91 + 20
        }
        
        return 68 + 20
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
}
