//
//  YHOffivialApprovalGuildLineCheckView.swift
//  galaxy
//
//  Created by davidhuangA on 2024/8/7.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
class YHOffivialApprovalGuildLineCheckView: UIView {
    
    typealias Block = () -> Void
    var block: Block?
    
    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
    }()
    
    lazy var myScrollView: UIScrollView = {
        let view = UIScrollView()
        view.backgroundColor = .clear
        view.showsVerticalScrollIndicator = false
        view.delegate = self
        return view
    }()
    
    lazy var bkgImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_guideline")
        imageV.contentMode = .scaleToFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    lazy var bkgImageV2: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_guideline_bkg")
        imageV.contentMode = .scaleToFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    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 YHOffivialApprovalGuildLineCheckView {
    
    static func sheetView() -> YHOffivialApprovalGuildLineCheckView {
        let view = YHOffivialApprovalGuildLineCheckView(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 YHOffivialApprovalGuildLineCheckView {
    
    @objc func timerFired() {
            // 定时器触发时执行的代码
            print("Timer fired")
        self.maxCount -= 1
        if self.maxCount < 1 {
            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: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        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)
        
        whiteContentView.addSubview(bkgImageV2)
        bkgImageV2.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(375)
        }
        
        whiteContentView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(98)
        }
        
        whiteContentView.addSubview(myScrollView)
        myScrollView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.right.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(whiteHeight-98 - 20)
        }
        
        if let tmpImage = UIImage(named: "official_approval_guideline") {
            let scale = Double(tmpImage.size.height / tmpImage.size.width)
            let imageH = scale * KScreenWidth
            
            myScrollView.addSubview(bkgImageV)
            bkgImageV.snp.makeConstraints { make in
                make.top.left.equalToSuperview()
                make.width.equalTo(KScreenWidth)
                make.height.equalTo(imageH)
            }
            myScrollView.contentSize = CGSize(width: KScreenWidth, height: imageH)
        }
    }
}

extension YHOffivialApprovalGuildLineCheckView: 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 {
               // 没有滚动到底部
           }
        }
    }
}
