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

import UIKit
import AttributedString
import Lottie
import YYImage

class YHOffivialApprovalSuccessCheckView: UIView {
    
    typealias Block = (Int) -> Void
    var block: Block?
    
    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.6)
        return view
    }()
    
    lazy var animationView: LottieAnimationView = {
        let view = LottieAnimationView(name: "flower2")
        view.loopMode = .playOnce
        return view
    }()
    
    lazy var scrollBgImgV: YYAnimatedImageView =  {
        let img = YYImage(named: "officalsuccess.gif")
        let imgV = YYAnimatedImageView(image: img)
        imgV.autoPlayAnimatedImage = false
        imgV.currentAnimatedImageIndex = 0
        return imgV
    }()
    
    // 香港身份获批指引操作
    lazy var rewardBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(clickSureBtn), for: .touchUpInside)
        button.setImage(UIImage(named: "official_approval_btn"), for: .normal)
        button.setImage(UIImage(named: "official_approval_btn"), for: .disabled)
        button.isEnabled = false
        return button
    }()
    
    lazy var closeBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(clickCloseBtn), for: .touchUpInside)
        button.setImage(UIImage(named: "official_approval_close_btn"), for: .normal)
        button.isHidden = true
        return button
    }()
    
    lazy var bkgImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_bkg")
        imageV.contentMode = .scaleToFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    lazy var holdView: UIView = {
        let view  = UIView()
        return view
    }()
    
    lazy var titleLabel: UILabel =  {
        var label = UILabel()
        label.font = .PFSC_R(ofSize: 15)
        label.textColor = UIColor(hex: 0x671908, alpha: 1.0)
        label.text = ""
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        return label
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private var displayLink: CADisplayLink?
    private var currentIndex: Int = 0
    private var fullText: String = "恭喜您申请的【优秀人才入境计划】"
    private var centerText: String = "已获得港府的正式批准！"
    private var lastText: String = "从递交资料伊始，经历了235天，感谢您这一路以来对银河的信赖与包容！"
    
    var days: Int = 0 {
        didSet {
            lastText = "从递交资料伊始，经历了" + String(days) + "天，感谢您这一路以来对银河的信赖与包容！"
        }
    }
    
    var orderType: Int = 1 {
        didSet {
            if orderType == 1 {
                fullText = "恭喜您申请的【优秀人才入境计划】"
            } else if orderType == 2 {
                fullText = "恭喜您申请的【高才通人才计划】"
            } else if orderType == 3 {
                fullText = "恭喜您申请的【输入内地人才入境计划】"
            }
        }
    }
}

extension YHOffivialApprovalSuccessCheckView {
    
    static func sheetView() -> YHOffivialApprovalSuccessCheckView {
        let view = YHOffivialApprovalSuccessCheckView(frame: UIScreen.main.bounds)
        return view
    }
    
    func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func clickSureBtn() {
        self.block?(0)
        dismiss()
    }
    
    @objc func clickCloseBtn() {
        self.block?(1)
        dismiss()
    }
}

private extension YHOffivialApprovalSuccessCheckView {
    func setupUI() {
        addSubview(blackMaskView)
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        if let tmpImage = UIImage(named: "official_approval_bkg") {
            let scale = Double(tmpImage.size.height / tmpImage.size.width)
            let imageH = scale * KScreenWidth
            
            holdView.frame = CGRect(x: 0, y: KScreenHeight, width: KScreenWidth, height: imageH)
            addSubview(holdView)
            
            bkgImageV.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: imageH)
            holdView.addSubview(bkgImageV)
            
            holdView.addSubview(titleLabel)
            let gap = (KScreenWidth / 375.0) * 64
            titleLabel.snp.makeConstraints { make in
                make.top.equalTo(112)
                make.left.equalTo(gap)
                make.right.equalTo(-gap)
            }
            titleLabel.isHidden = true
            
            holdView.addSubview(rewardBtn)
            
            let topMargin0 = (KScreenHeight/812.0) * 233
            rewardBtn.snp.makeConstraints { make in
                make.top.equalTo(topMargin0)
                make.width.equalTo(196)
                make.height.equalTo(44)
                make.centerX.equalToSuperview()
            }
            
            holdView.addSubview(closeBtn)
            
            let topMargin = (KScreenHeight/812.0) * 156
            closeBtn.snp.makeConstraints { make in
                make.top.equalTo(rewardBtn.snp.bottom).offset(topMargin)
                make.width.height.equalTo(24.fix)
                make.centerX.equalToSuperview()
            }
            closeBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
            
            UIView.animate(withDuration: 1) {
                self.holdView.frame = CGRect(x: 0, y: (KScreenHeight-imageH)/2 + 20, width: KScreenWidth, height: imageH)
            } completion: { _ in
                self.titleLabel.isHidden = false
                self.startTypingEffect()
            }
        }
        
        addSubview(scrollBgImgV)
        scrollBgImgV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        self.scrollBgImgV.isHidden = false
        DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) {
            self.scrollBgImgV.animationRepeatCount = 2
            self.scrollBgImgV.startAnimating()
            Timer.scheduledTimer(withTimeInterval: 4, repeats: false) { timer in
                self.scrollBgImgV.stopAnimating()
                timer.invalidate()
                self.scrollBgImgV.isHidden = true
            }
        }
    }
    
    private func startTypingEffect() {
        displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
        displayLink?.preferredFramesPerSecond = Int(1 / 0.1) // 设置帧率
        displayLink?.add(to: .current, forMode: .common)
    }
    
    @objc private func handleDisplayLink(_ displayLink: CADisplayLink) {
        if currentIndex <= fullText.count + centerText.count + lastText.count {
            var index = currentIndex
            if currentIndex >= fullText.count {
                index = fullText.count
            }
            let attributedString = NSMutableAttributedString(string: String(fullText[..<index]),
                                                             attributes: [
                                                                NSAttributedString.Key.foregroundColor: UIColor(hex: 0x671908, alpha: 1.0),
                                                                NSAttributedString.Key.paragraphStyle: {
                                                                    let style = NSMutableParagraphStyle()
                                                                    style.lineSpacing = 6 // 控制行间距
                                                                    style.alignment = .left
                                                                    return style
                                                                }()
                                                             ])
            var centerIndex = 0
            if currentIndex >= fullText.count + centerText.count {
                centerIndex = centerText.count
            } else if currentIndex >= fullText.count {
                centerIndex = currentIndex - fullText.count
            }
            let centerattributedString = NSMutableAttributedString(string: String(centerText[..<centerIndex]),
                                                             attributes: [
                                                                NSAttributedString.Key.foregroundColor: UIColor(hex: 0xAE1616, alpha: 1.0),
                                                                NSAttributedString.Key.paragraphStyle: {
                                                                    let style = NSMutableParagraphStyle()
                                                                    style.lineSpacing = 6 // 控制行间距
                                                                    style.alignment = .left
                                                                    return style
                                                                }()
                                                             ])
            var lastIndex = 0
            if currentIndex >= fullText.count + centerText.count {
                lastIndex = currentIndex - fullText.count - centerText.count
            }
            let lastattributedString = NSMutableAttributedString(string: String(lastText[..<lastIndex]),
                                                             attributes: [
                                                                NSAttributedString.Key.foregroundColor: UIColor(hex: 0x671908, alpha: 1.0),
                                                                NSAttributedString.Key.paragraphStyle: {
                                                                    let style = NSMutableParagraphStyle()
                                                                    style.lineSpacing = 6 // 控制行间距
                                                                    style.alignment = .left
                                                                    return style
                                                                }()
                                                             ])
            let result = NSMutableAttributedString(attributedString: attributedString)
            result.append(centerattributedString)
            result.append(lastattributedString)
            self.titleLabel.attributedText = result
            
            currentIndex += 1
        } else {
            displayLink.invalidate()
            
            self.closeBtn.isHidden = false
            self.rewardBtn.isEnabled = true
        }
    }
}
