//
//  YHHKVisaRenewalApplicationVC.swift
//  galaxy
//
//  Created by alexzzw on 2025/3/6.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

import AttributedString
import Photos
import SafariServices
class YHHKVisaRenewalApplicationVC: YHBaseViewController {
    private lazy var headerView: YHHKVisaRenewalApplicationHeader = {
        let view = YHHKVisaRenewalApplicationHeader(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: YHHKVisaRenewalApplicationHeader.viewHeight))
        return view
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .grouped)
        view.estimatedSectionHeaderHeight = 16.0
        view.estimatedSectionFooterHeight = 0.01
        view.sectionHeaderHeight = 16.0
        view.sectionFooterHeight = 0.01
        view.contentInsetAdjustmentBehavior = .never
        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(YHVisaRenewalSectionHeaderCell.self, forCellReuseIdentifier: YHVisaRenewalSectionHeaderCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayMethodUrlCell.self, forCellReuseIdentifier: YHVisaRenewalPayMethodUrlCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayMethodQrcodeCell.self, forCellReuseIdentifier: YHVisaRenewalPayMethodQrcodeCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayOccupyingSpaceCell.self, forCellReuseIdentifier: YHVisaRenewalPayOccupyingSpaceCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayMemberCell.self, forCellReuseIdentifier: YHVisaRenewalPayMemberCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayInfoCell.self, forCellReuseIdentifier: YHVisaRenewalPayInfoCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayContentCell.self, forCellReuseIdentifier: YHVisaRenewalPayContentCell.cellReuseIdentifier)
        return view
    }()

    private lazy var datas: [[YHVisaRenewalInfoItemDetailType]] = []
    private lazy var viewModel = YHHKVisaRenewalPaymentViewModel()

    private var id: Int = 0
    private var isEdit: Int = 0

    init(id: Int, isEdit: Int) {
        self.id = id
        self.isEdit = isEdit
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestData()
    }
}

extension YHHKVisaRenewalApplicationVC {
    private func setupUI() {
        gk_navTitle = "续签申请缴费"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(tableView)

        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview()
        }

        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: kMargin))
        tableView.tableHeaderView = headerView
    }

    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getPaymentInfo(id: id, isEdit: isEdit) { [weak self] paymentListModel, error in
            guard let self = self else {
                return
            }
            if isNeedLoading {
                YHHUD.hide()
            }
            guard let paymentListModel = paymentListModel else {
                printLog("YHHKVisaRenewalApplicationVC:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.datas = []
                self.tableView.reloadData()
                return
            }

            var sections: [[YHVisaRenewalInfoItemDetailType]] = []
            var paymentMembers: [YHVisaRenewalInfoItemDetailType] = []
            paymentListModel.list.forEach { [weak self] person in
                guard let self = self else {
                    return
                }
//                paymentMembers.append(.occupyingSpace)
                paymentMembers.append(.subHeader(person.name))
                paymentMembers.append(.subInfo("临时档案号：", person.file_num, "复制", .top, nil, false, { [weak self] in
                    guard let self = self else {
                        return
                    }
                    self.copyToPasteBoard(person.file_num, message: "已复制临时档案号")
                }))
//                let dateString = self.getShortDate(person.birthday)
                paymentMembers.append(.subInfo("申请人出生日期：", "\(person.birthday)", nil))
                paymentMembers.append(.subInfo("缴费金额：", "\(person.fee_money)", nil, .bottom))
            }

            if paymentMembers.count > 0 {
                paymentMembers.append(.occupyingSpace)
            }

            let webPageUrl = paymentListModel.payment_url
            if webPageUrl.count > 0, URL(string: webPageUrl) != nil {
                let payMethodSection: [YHVisaRenewalInfoItemDetailType] = [.sectionHeader("港府官网缴费方式", "", {
                }), .occupyingSpace, .payMethodUrl("方式一", "点击下方链接，跳转浏览器，进入港府官网操作缴费", webPageUrl, { [weak self] in
                    guard let self = self else {
                        return
                    }
                    printLog("点击下方链接，跳转浏览器")
                    self.gotoWebVC(webPageUrl)
                }), .payMethodQrcode("方式二", "用其他设备直接扫码，或长按保存图片，通过微信识别打开", webPageUrl)]
                sections.append(payMethodSection)
            }
            var payMembersSection: [YHVisaRenewalInfoItemDetailType] = [.sectionHeader("缴费成员", "", {
            })]
            payMembersSection.append(contentsOf: paymentMembers)
            sections.append(payMembersSection)
            self.datas = sections
            self.tableView.reloadData()
        }
    }
    
    private func getShortDate(_ originalDate: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        if let date = formatter.date(from: originalDate) {
            formatter.dateFormat = "yyyy-MM-dd"
            let result = formatter.string(from: date)
            return result
        } else {
            return originalDate
        }
    }

    private func showAlertView(confirmBlock: (() -> Void)?) {
        let alert = YHVisaRenewalPayConfirmingPresenceAlertView.alertView()
        alert.confirmBlock = {
            confirmBlock?()
        }
        alert.show()
    }

    private func gotoWebVC(_ urlString: String) {
        guard let url = URL(string: urlString) else {
            printLog("无法打开链接")
            return
        }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            // 显示一个提示，告知用户无法打开链接
            printLog("无法打开链接")
            YHHUD.flash(message: "无法打开链接")
        }
    }

    private func gotoPreview(_ urlString: String) {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getRealUsefulUrl(urlString) { [weak self] resultUrl in
            YHHUD.hide()
            guard let self = self, let url = URL(string: resultUrl) else { return }
            let safariViewController = SFSafariViewController(url: url)
            safariViewController.dismissButtonStyle = .close
            safariViewController.modalPresentationStyle = .fullScreen
            self.present(safariViewController, animated: true, completion: nil)
        }
    }

    private func copyToPasteBoard(_ text: String, message: String = "复制成功") {
        let pasteBoard = UIPasteboard.general
        pasteBoard.string = text
        YHHUD.flash(message: message)
    }

    private func saveImage(_ image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存UIImage对象到相册
                DispatchQueue.main.async {
                    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
                }
            } else {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "保存失败，请检查系统权限")
                }
            }
        }
    }

    @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeMutableRawPointer?) {
        // 保存完成后的处理逻辑
        if let error = error {
            printLog("保存照片失败：\(error.localizedDescription)")
            YHHUD.flash(message: "保存失败")
        } else {
            printLog("保存照片成功")

            YHHUD.flash(message: "保存成功")
        }
    }
}

extension YHHKVisaRenewalApplicationVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        let sectionArr = datas[section]
        return sectionArr.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return UITableViewCell()
        }
        let row = sectionArr[indexPath.row]

        switch row {
        case let .sectionHeader(title, actionTitle, action):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalSectionHeaderCell.cellReuseIdentifier) as? YHVisaRenewalSectionHeaderCell {
                cell.setupCellInfo(title: title, buttonTitle: actionTitle)
                cell.rightButtonEvent = {
                    action?()
                }
                return cell
            }
        case let .payMethodUrl(title, detail, url, action):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayMethodUrlCell.cellReuseIdentifier) as? YHVisaRenewalPayMethodUrlCell {
                cell.setupCellInfo(title: title, tips: detail, url: url)
                cell.urlClicked = { _ in
                    action?()
                }
                return cell
            }
        case let .payMethodQrcode(title, detail, qrCodeUrl):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayMethodQrcodeCell.cellReuseIdentifier) as? YHVisaRenewalPayMethodQrcodeCell {
                cell.setupCellInfo(title: title, tips: detail, qrCode: qrCodeUrl)
                cell.onLongPressEvent = { [weak self] image in
                    self?.saveImage(image)
                }
                return cell
            }
        case let .subHeader(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayMemberCell.cellReuseIdentifier) as? YHVisaRenewalPayMemberCell {
                cell.setupCellInfo(title: title)
                return cell
            }
        case let .subInfo(title, detail, actionTitle, cellType, defaultMargin, showBottomLine, action):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayInfoCell.cellReuseIdentifier) as? YHVisaRenewalPayInfoCell {
                cell.setupCellInfo(title: title, detail: detail, rightButtonTitle: actionTitle, cellType: cellType, defaultMargin: defaultMargin, showBottomLine: showBottomLine)
                cell.rightButtonEvent = {
                    action?()
                }
                return cell
            }
        case let .subContent(title, detail, actionTitle, cellType, action):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayContentCell.cellReuseIdentifier) as? YHVisaRenewalPayContentCell {
                cell.setupCellInfo(title: title, detail: detail, rightButtonTitle: actionTitle, cellType: cellType)
                cell.rightButtonEvent = {
                    action?()
                }
                return cell
            }
        case .occupyingSpace:
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayOccupyingSpaceCell.cellReuseIdentifier) as? YHVisaRenewalPayOccupyingSpaceCell {
                let isBottom = indexPath.row == sectionArr.count - 1
                cell.setupCellInfo(isBottom: isBottom)
                return cell
            }
        }
        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 16.0
    }

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

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

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
}
