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

import UIKit

class YHServiceOrderGuideTipsView: UIView {
    
    typealias Block = () -> ()
    var block: Block?
    var isShow: Bool = true
    var type: Int = 0
    
    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 buttonContentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.contentBkgColor
        return view
    }()
    
    lazy var leftBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("优才", for: .normal)
        button.setTitleColor(UIColor(hex: 0x8893a2), for: .normal)
        button.setTitleColor(UIColor.mainTextColor, for: .selected)
        button.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
        button.setBackgroundColor(color: UIColor.white, forState: .selected)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(clickLeftBtn), for: .touchUpInside)
        button.backgroundColor = UIColor.brandMainColor
        return button
    }()
    
    lazy var rightBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("高才", for: .normal)
        button.setTitleColor(UIColor(hex: 0x8893a2), for: .normal)
        button.setTitleColor(UIColor.mainTextColor, for: .selected)
        button.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
        button.setBackgroundColor(color: UIColor.white, forState: .selected)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(clickRightBtn), for: .touchUpInside)
        button.backgroundColor = UIColor.brandMainColor
        return button
    }()
    
    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: "service_order_guideline_one")
//        service_order_guideline_two
//        imageV.contentMode = .scaleToFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    lazy var bkgImageV2: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "service_order_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()
            }
        }
    }
    
    func isShow(flag: Bool) {
        buttonContentView.isHidden = !flag
        if flag {
            myScrollView.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(120)
                make.left.right.equalToSuperview()
                make.width.equalTo(KScreenWidth)
                make.height.equalTo(KScreenHeight - k_Height_NavigationtBarAndStatuBar - 98 - 120)
            }
        } else {
            myScrollView.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(68)
                make.left.right.equalToSuperview()
                make.height.equalTo(KScreenHeight - k_Height_NavigationtBarAndStatuBar - 98 - 68)
            }
        }
    }
}

extension YHServiceOrderGuideTipsView  {
    
    static func sheetView(_ isShow: Bool = true, _ selectType: Int = 0) -> YHServiceOrderGuideTipsView {
        let view = YHServiceOrderGuideTipsView(frame:UIScreen.main.bounds)
        view.isShow = isShow
        view.type = selectType
        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)
            self.isShow(flag: self.isShow)
            if self.type == 1 {
                self.clickLeftBtn()
            } else {
                self.clickRightBtn()
            }
        }
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func clickSureBtn() {
        self.block?()
        dismiss()
    }
    
    @objc func clickLeftBtn() {
        leftBtn.isSelected = true
        rightBtn.isSelected = false
        if let tmpImage = UIImage(named:"service_order_guideline_one") {
            let scale = Double(tmpImage.size.height / tmpImage.size.width)
            let imageH = scale * (KScreenWidth - 40)
            
            bkgImageV.snp.remakeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.height.equalTo(imageH)
            }
            bkgImageV.image = tmpImage
            myScrollView.contentSize = CGSize(width: KScreenWidth, height: imageH)
        }
    }
    
    @objc func clickRightBtn() {
        leftBtn.isSelected = false
        rightBtn.isSelected = true
        if let tmpImage = UIImage(named:"service_order_guideline_two") {
            let scale = Double(tmpImage.size.height / tmpImage.size.width)
            let imageH = scale * (KScreenWidth - 40)
            
            bkgImageV.snp.remakeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.height.equalTo(imageH)
            }
            bkgImageV.image = tmpImage
            myScrollView.contentSize = CGSize(width: KScreenWidth, height: imageH)
        }
    }
}

private extension YHServiceOrderGuideTipsView {
    
    @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(68)
        }
        
        whiteContentView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(98)
        }
        
        whiteContentView.addSubview(buttonContentView)
        buttonContentView.snp.makeConstraints { make in
            make.top.equalTo(64)
            make.centerX.equalToSuperview()
            make.height.equalTo(36)
            make.width.equalTo(223)
        }
        
        buttonContentView.addSubview(leftBtn)
        leftBtn.snp.makeConstraints { make in
            make.left.equalTo(3)
            make.centerY.equalToSuperview()
            make.height.equalTo(30)
            make.width.equalTo(108)
        }
        
        buttonContentView.addSubview(rightBtn)
        rightBtn.snp.makeConstraints { make in
            make.right.equalTo(-3)
            make.centerY.equalToSuperview()
            make.height.equalTo(30)
            make.width.equalTo(108)
        }
        
        whiteContentView.addSubview(myScrollView)
        myScrollView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(120)
            make.right.left.equalToSuperview()
            make.height.equalTo(whiteHeight - 98 - 120)
        }
        
        if let tmpImage = UIImage(named:"service_order_guideline_one") {
            let scale = Double(tmpImage.size.height / tmpImage.size.width)
            let imageH = scale * (KScreenWidth - 40)
            
            myScrollView.addSubview(bkgImageV)
            bkgImageV.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.height.equalTo(imageH)
            }
            myScrollView.contentSize = CGSize(width: KScreenWidth, height: imageH)
        }
    }
}

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