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

import UIKit

class YHResignUploadTravelGuideView: UIView {
    
    typealias Block = () -> ()
    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: "resign_upload_guideline")
        imageV.contentMode = .scaleToFill
        imageV.isUserInteractionEnabled = true
        imageV.clipsToBounds = true
        return imageV
    }()
    
    lazy var bkgImageV2: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "resign_upload_guideline_bkg")
        imageV.contentMode = .scaleToFill
        imageV.clipsToBounds = true
        imageV.isUserInteractionEnabled = 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 YHResignUploadTravelGuideView  {
    
    static func sheetView() -> YHResignUploadTravelGuideView {
        let view = YHResignUploadTravelGuideView(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()
    }
    
    @objc func clicklinkBtn() {
//        self.block?()
        dismiss()
        let vc = YHH5WebViewVC()
        vc.url = "https://www.ctshk.com/mep/zh/"
        vc.isFullScreenFlag = false
        UIViewController.current?.navigationController?.pushViewController(vc)
    }
   
}

private extension YHResignUploadTravelGuideView {
    
    @objc func timerFired() {
            // 定时器触发时执行的代码
            print("Timer fired")
        self.maxCount = 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:CGSizeMake(kCornerRadius6, 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(269.fix)
        }
        
        whiteContentView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(98)
        }
        
        let sublineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        whiteContentView.addSubview(sublineView)
        sublineView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
            make.height.equalTo(1)
        }
        
        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 - 21)
        }
        
        if let tmpImage = UIImage(named:"resign_upload_guideline") {
            myScrollView.addSubview(bkgImageV)
            bkgImageV.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.centerX.equalToSuperview()
                make.width.equalTo(336.fix)
                make.height.equalTo(1356.fix)
            }
            myScrollView.contentSize = CGSize(width: KScreenWidth, height: 1356.fix)
            
            let button = UIButton(type: .custom)
            button.addTarget(self, action: #selector(clicklinkBtn), for: .touchUpInside)
            myScrollView.addSubview(button)
            button.snp.makeConstraints { make in
                make.left.equalTo(44)
                make.height.equalTo(40)
                make.width.equalTo(255.fix)
                make.top.equalTo(756.fix)
            }
        }
        
        let button = UIButton(type: .custom)
        button.setBackgroundImage(UIImage(named: "service_card_close"), for: .normal)
        button.addTarget(self, action: #selector(clickSureBtn), for: .touchUpInside)
        whiteContentView.addSubview(button)
        button.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.width.height.equalTo(24)
            make.top.equalTo(16)
        }
    }
}

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