//
//  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 = () -> Void
    var block: Block?
    var isShow: Bool = true
    var type: Int = 0
    var tableView: UITableView!
    var image: String = "service_order_guideline_one"
    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 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 {
            tableView.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(100)
                make.left.right.equalToSuperview()
                make.width.equalTo(KScreenWidth)
                make.height.equalTo(KScreenHeight - k_Height_NavigationtBarAndStatuBar - 98 - 120)
            }
        } else {
            tableView.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
        image = "service_order_guideline_one"
        tableView.reloadData()
    }
    
    @objc func clickRightBtn() {
        leftBtn.isSelected = false
        rightBtn.isSelected = true
        image = "service_order_guideline_two"
        tableView.reloadData()
    }
}

private extension YHServiceOrderGuideTipsView {
    
    @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.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.fix)
        }
        
        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)
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.showsHorizontalScrollIndicator = false
            tableView.showsVerticalScrollIndicator = false
            tableView.dataSource = self
            tableView.delegate = self
            tableView.register(cellWithClass: YHServiceOrderGuideTableViewCell.self)
            return tableView
        }()
        
        whiteContentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(100)
            make.right.left.equalToSuperview()
            make.height.equalTo(whiteHeight - 98 - 120)
        }
        
    }
}

extension YHServiceOrderGuideTipsView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHServiceOrderGuideTableViewCell.self)
        cell.dataSource = image
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 1024.fix
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 6
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
}

class YHServiceOrderGuideTableViewCell: UITableViewCell {
    var centerImageView: UIImageView!

    var dataSource: String? {
        didSet {
            centerImageView.image = UIImage(named: dataSource ?? "")
        }
    }
    
    var imageUrl: String? {
        didSet {
            guard let url = URL(string: imageUrl) else { return }
            centerImageView.kf.setImage(with: url)
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        self.backgroundColor = .white
        centerImageView = {
            let imageView = UIImageView()
            imageView.isUserInteractionEnabled = true
            imageView.image = UIImage(named: "invitation_with_gifts_first")
            imageView.contentMode = .scaleAspectFill
            return imageView
        }()
        contentView.addSubview(centerImageView)
        centerImageView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
    }
}
