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

import UIKit
import AttributedString

class YHVisaRenewalGuideVC: YHBaseViewController {
    static private let showCardGuideKey = "VisaRenewalGuideVCDidShow"
    
    static var didShowGuide: Bool {
        UserDefaults.standard.value(forKey: showCardGuideKey) as? Bool == true
    }
    
    enum TableRow {
        case header
        case paragraph(_ title: String, _ detail: String)
        case indent(_ title: String, _ detail: String)
        case tips(_ title: String, _ detail: ASAttributedString)
        case remark(_ detail: String)
    }
    
    private lazy var bgIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "resign_visa_guide_bg")
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.rowHeight = UITableView.automaticDimension
        view.estimatedRowHeight = 52.0
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(YHVisaRenewalGuideHeaderCell.self, forCellReuseIdentifier: YHVisaRenewalGuideHeaderCell.cellReuseIdentifier)
        view.register(YHVisaRenewalGuideParagraphCell.self, forCellReuseIdentifier: YHVisaRenewalGuideParagraphCell.cellReuseIdentifier)
        view.register(YHVisaRenewalGuideRemarkCell.self, forCellReuseIdentifier: YHVisaRenewalGuideRemarkCell.cellReuseIdentifier)
        view.register(YHVisaRenewalGuideIndentCell.self, forCellReuseIdentifier: YHVisaRenewalGuideIndentCell.cellReuseIdentifier)
        view.register(YHVisaRenewalGuideTipsCell.self, forCellReuseIdentifier: YHVisaRenewalGuideTipsCell.cellReuseIdentifier)
        
        return view
    }()
    
    private lazy var sureButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        button.setTitle("请上滑看完指引后操作（5s）", for: .disabled)
        button.setTitle("我已知悉，确认", for: .normal)
        button.setTitle("我已知悉，确认", for: .highlighted)
        button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
        button.setTitleColor( UIColor(hex:0xffffff), for: .highlighted)
        button.setTitleColor( UIColor(hex:0xffffff), for: .disabled)
        button.addTarget(self, action: #selector(clickSureButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        let isEnable = YHVisaRenewalGuideVC.didShowGuide
        button.backgroundColor = isEnable ? .brandMainColor : UIColor(hex: 0xB7C0CC, alpha: 1.0)
        button.isEnabled = isEnable
        return button
    }()
    
    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    var sureButtonEvent: (() -> Void)?
    
    private lazy var datas: [TableRow] = []
    
    private var isStartTimer: Bool = false
    private let maxCount = 5
    private var timer: DispatchSourceTimer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupDatas()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if !isStartTimer {
            isStartTimer = true
            let didShowGuide = YHVisaRenewalGuideVC.didShowGuide
            if !didShowGuide {
                setupTimer()
            }
        }
    }
    
    deinit {
        cancelTimer()
    }

}

extension YHVisaRenewalGuideVC {
    
    @objc private func clickSureButton() {
        sureButtonEvent?()
    }
    
    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor.white
        view.addSubview(bgIcon)
        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.addSubview(sureButton)
        bgIcon.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(bgIcon).multipliedBy(1)
        }
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.height.equalTo(64)
        }
        
        sureButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kMargin)
            make.right.equalToSuperview().offset(-kMargin)
            make.centerY.equalToSuperview()
            make.height.equalTo(48)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.bottom.equalTo(bottomView.snp.top)
        }
        tableView.tableFooterView = UIView(frame: CGRect.init(x: 0, y: 0, width: KScreenWidth, height: 82))
        preferredContentSize = CGSize(width: KScreenWidth, height: KScreenHeight - k_Height_NavigationtBarAndStatuBar)
    }
    
    private func setupDatas() {
        datas.append(.header)
        datas.append(.paragraph("二、原签证未过期但已离境，需赴港缴费领取新签证", "携带港澳通行证逗留D签注（如是护照申请则为护照）、香港身份证；香港关请务必走香港居民通道"))
        datas.append(.indent("内地关", "使用港澳通行证逗留D签注"))
        datas.append(.indent("香港关", "已有香港身份证则使用香港身份证走香港居民通道；未满11岁无香港身份证，则使用对应旅行证件和电子签证走香港居民人工通道"))
        datas.append(.paragraph("三、原签证已过期且已离境，需赴港缴费领取新签证", "携带港澳通行证旅游签注（如护照申请，则同时携带护照）、香港身份证；香港关也走访客通道"))
        
        datas.append(.indent("内地关", "使用港澳通行证旅游签注"))
        datas.append(.indent("香港关", "使用港澳通行证旅游签注（如护照申请则使用护照）走访客通道"))
        datas.append(.remark("备注：如用中国护照申请，从内地赴港，在非需前往其他国家的情况下可能无法直接持护照过关，需提前办理港澳通行证旅游签注备用；建议联合其他国行程，香港作为中转，即可护照顺利入境"))
        let firstAtt: ASAttributedString = .init(string: "1、信用卡（只接受VISA、万事达卡、银联卡及JCB），缴费灵，「转数快」或内地电子钱包（只接受支付宝、微信支付及云闪付App）缴付。付款成功后，申请人随即可自行下载或打印「电子签证」\n\n2、缴费过程中或需填写获批者的出生日期与旅行证件号码，请提前准备\n\n3、手机端电脑端都可缴费，建议使用电脑端（每位获批者都需单独缴费一次）", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor70), .paragraph(.lineHeightMultiple(1.07)))
        datas.append(.tips("缴费注意事项：", firstAtt))
        
        let secLine1a: ASAttributedString = .init(string: "1、涉及的申请人若已在港，并在赴港时使用正确证件，走正确通道才可以去缴费查看签证；未入境前一旦尝试缴费签证就会被锁；若刚入境香港，", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor70))
        let secLine1b: ASAttributedString = .init(string: "至少2个小时后再进行缴费", .font(UIFont.PFSC_M(ofSize: 13)), .foreground(UIColor.brandMainColor))
        let secLine1c: ASAttributedString = .init(string: "，避免海关还未识别到入境记录，导致签证被锁\n\n", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor70))
        let secLine2a: ASAttributedString = .init(string: "2、签证过期后，再入境香港缴费只能以访客身份入境，会有签证被锁的风险。", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor70))
        let secLine2b: ASAttributedString = .init(string: "建议尽量在工作日到港缴费", .font(UIFont.PFSC_M(ofSize: 13)), .foreground(UIColor.brandMainColor))
        let secLine2c: ASAttributedString = .init(string: "，如遇签证被锁情况方便去入境处核实情况及申请重发，目前重发周期预计是3-6周，重发后需要再次来港缴费", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor70))
        
        let secAtt: ASAttributedString = (secLine1a + secLine1b + secLine1c + secLine2a + secLine2b + secLine2c).add(attributes: .paragraph(.lineHeightMultiple(1.07)))
        datas.append(.tips("风险提示：", secAtt))
        tableView.reloadData()
    }
    
    /// 设置定时器
    private func setupTimer() {
        var countDown = maxCount + 1
        timer = DispatchSource.makeTimerSource(queue: .main)
        timer?.schedule(deadline: .now(), repeating: .seconds(1))
        timer?.setEventHandler(handler: { [weak self] in
            guard let self = self else {
                return
            }
            DispatchQueue.main.async {
                countDown -= 1
                if countDown == 0 {
                    self.didReadGuide()
                    return
                }
                self.sureButton.isEnabled = false
                self.sureButton.setTitle("请上滑看完指引后操作（\(countDown)s）", for: .disabled)
                self.sureButton.backgroundColor = UIColor(hex: 0xB7C0CC, alpha: 1.0)
            }
        })
        timer?.resume()
    }
    
    /// 取消定时器
    private func cancelTimer() {
        if timer != nil {
            timer?.cancel()
            timer = nil
        }
    }
    
    private func didReadGuide() {
        cancelTimer()
        sureButton.isEnabled = true
        sureButton.backgroundColor = .brandMainColor
        UserDefaults.standard.set(true, forKey: YHVisaRenewalGuideVC.showCardGuideKey)
        UserDefaults.standard.synchronize()
    }
}

extension YHVisaRenewalGuideVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count > 0 ? 1 : 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.row else {
            return UITableViewCell()
        }
        let tableRow = datas[indexPath.row]
        switch tableRow {
        case .header:
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalGuideHeaderCell.cellReuseIdentifier) as? YHVisaRenewalGuideHeaderCell {
                return cell
            }
        case let .paragraph(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalGuideParagraphCell.cellReuseIdentifier) as? YHVisaRenewalGuideParagraphCell {
                cell.setupCellInfo(title: title, detail: detail)
                return cell
            }
        case let .indent(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalGuideIndentCell.cellReuseIdentifier) as? YHVisaRenewalGuideIndentCell {
                cell.setupCellInfo(title: title, detail: detail)
                return cell
            }
        case let .tips(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalGuideTipsCell.cellReuseIdentifier) as? YHVisaRenewalGuideTipsCell {
                cell.setupCellInfo(title: title, detail: detail)
                return cell
            }
        case let .remark(detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalGuideRemarkCell.cellReuseIdentifier) as? YHVisaRenewalGuideRemarkCell {
                cell.setupCellInfo(detail: detail)
                return cell
            }
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard !YHVisaRenewalGuideVC.didShowGuide else {
            return
        }
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
        let height = scrollView.frame.size.height
        
        if offsetY > contentHeight - height {
            printLog("Reached bottom!")
            // 在这里执行到达底部时的操作
            didReadGuide()
        }
    }
}
