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

import UIKit
import AttributedString
import SafariServices
import Photos

class YHHKVisaRenewalPaymentVC: YHBaseViewController {
    
    private lazy var stepView: YHHKVisaRenewalPaymentStepView = {
        let view = YHHKVisaRenewalPaymentStepView.init(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 74))
        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(YHVisaRenewalTipsCell.self, forCellReuseIdentifier: YHVisaRenewalTipsCell.cellReuseIdentifier)
        view.register(YHVisaRenewalResidenceActionCell.self, forCellReuseIdentifier: YHVisaRenewalResidenceActionCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayMethodUrlCell.self, forCellReuseIdentifier: YHVisaRenewalPayMethodUrlCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayMethodQrcodeCell.self, forCellReuseIdentifier: YHVisaRenewalPayMethodQrcodeCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayOccupyingSpaceCell.self, forCellReuseIdentifier: YHVisaRenewalPayOccupyingSpaceCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayStatusCell.self, forCellReuseIdentifier: YHVisaRenewalPayStatusCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayInfoCell.self, forCellReuseIdentifier: YHVisaRenewalPayInfoCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayContentCell.self, forCellReuseIdentifier: YHVisaRenewalPayContentCell.cellReuseIdentifier)
        view.register(YHVisaRenewalPayTipsCell.self, forCellReuseIdentifier: YHVisaRenewalPayTipsCell.cellReuseIdentifier)
        return view
    }()
    
    private lazy var guideButton: UIControl = {
        let button = UIControl()
        let titleLabel = UILabel()
        titleLabel.text = "领取续签指引"
        titleLabel.textColor = .mainTextColor
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.PFSC_R(ofSize: 11)
        let image = UIImage(named: "resign_visa_pay_guide")
        let imageView = UIImageView(image: image)
        button.addSubview(titleLabel)
        button.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(24)
        }
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(imageView.snp.bottom)
            make.centerX.equalTo(imageView)
        }
        button.addTarget(self, action: #selector(clickGuideButton), for: .touchUpInside)
        return button
    }()
    
    private lazy var sureButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        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
        button.backgroundColor = .brandMainColor
        button.alpha = 0.3
        button.isEnabled = false
        return button
    }()
    
    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var datas: [[YHVisaRenewalItemDetailType]] = []
    
    private var didShowGuideVC = false
    
    private lazy var viewModel = YHHKVisaRenewalPaymentViewModel()
    
    private let orderId: Int
    private let renewalId: Int
    init(orderId: Int, renewalId: Int) {
        self.orderId = orderId
        self.renewalId = renewalId
        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()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if !didShowGuideVC {
            didShowGuideVC = true
            let didShowGuide = YHVisaRenewalGuideVC.didShowGuide
            if !didShowGuide {
                showGuideVC()
            }
        }
    }
}

extension YHHKVisaRenewalPaymentVC {
    @objc private func clickGuideButton() {
        showGuideVC()
    }
    
    @objc private func clickSureButton() {
        let vc = YHResignUploadTravelCardListViewController()
        vc.orderId = orderId
        vc.batchId = renewalId
        navigationController?.pushViewController(vc)
    }
    
    private func setupUI() {
        gk_navTitle = "签证缴费"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(stepView)
        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.addSubview(sureButton)
        bottomView.addSubview(guideButton)
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-64)
        }
        
        guideButton.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(64)
            make.width.equalTo(106)
        }
        
        sureButton.snp.makeConstraints { make in
            make.left.equalTo(guideButton.snp.right)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(8)
            make.height.equalTo(48)
        }
        stepView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(74)
        }
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(stepView.snp.bottom)
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        tableView.tableFooterView = UIView(frame: CGRect.init(x: 0, y: 0, width: KScreenWidth, height: kMargin))
    }
    
    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getPaymentList(orderId: orderId, renewalId: renewalId) { [weak self] paymentListModel, error in
            guard let self = self else {
                return
            }
            if isNeedLoading {
                YHHUD.hide()
            }
            guard let paymentListModel = paymentListModel else {
                printLog("YHHKVisaRenewalPaymentVC:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.datas = []
                self.tableView.reloadData()
                return
            }
            
            let approvalPendingMsg = "申请人暂未获批，无法在港缴费"
            let confirmedPresenceMsg = "申请人已在港"
            var sections: [[YHVisaRenewalItemDetailType]] = []
            let confirmingPresenceTips: ASAttributedString = .init(string: "提示：", .foreground(UIColor.yhOrangeColor)) + .init(string: "缴费前请先确认涉及到的") + .init(string: "申请人在香港", .foreground(UIColor.yhOrangeColor))
            var confirmingPresenceSection: [YHVisaRenewalItemDetailType] = [.sectionHeader("确认申请人在港", nil), .tips(confirmingPresenceTips)]
            var actionMembers: [YHVisaRenewalItemDetailType] = []
            var paymentMembers: [YHVisaRenewalItemDetailType] = []
            self.updateSureButtonState(false)
            paymentListModel.list.forEach { [weak self] person in
                guard let self = self else {
                    return
                }
                guard let presenceStatus = YHVisaRenewalPresenceStatus(rawValue: person.confirm_hk_status) else { return }
                let member = YHVisaRenewalItemDetailType.residenceAction(person.name, presenceStatus, .mid) { [weak self] in
                    guard let self = self else {
                        return
                    }
                    switch presenceStatus {
                    case .approvalPending:
                        YHHUD.flash(message: approvalPendingMsg)
                    case .confirmingPresence:
                        self.showAlertView(confirmBlock: { [weak self] in
                            guard let self = self else {
                                return
                            }
                            YHHUD.show(.progress(message: "确认中..."))
                            self.viewModel.confirmInHK(orderId: self.orderId, renewalId: self.renewalId, uid: person.id, type: person.type) { [weak self] success, error in
                                guard let self = self else {
                                    return
                                }
                                YHHUD.hide()
                                if success {
                                    YHHUD.flash(message: "已确认在港")
                                    self.requestData(isNeedLoading: true)
                                } else {
                                    if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                                        YHHUD.flash(message: errorMsg)
                                    }
                                }
                            }
                        })
                    case .confirmedPresence:
                        YHHUD.flash(message: confirmedPresenceMsg)
                    }
                }
                actionMembers.append(member)
                
                guard let paymentStatus = YHVisaRenewalPaymentStatus(rawValue: person.pay_status) else {
                    return
                }
                switch paymentStatus {
                case .pendingPayment:
                    paymentMembers.append(.occupyingSpace)
                    paymentMembers.append(.subHeader(person.name, .pendingPayment))
                    switch presenceStatus {
                    case .approvalPending:
                        paymentMembers.append(.subRemark("续签申请暂未正式获批，请耐心等待"))
                    case .confirmingPresence:
                        paymentMembers.append(.subInfo("档案号：", "-", nil))
                        paymentMembers.append(.subInfo("可缴费时间段：", "\(person.min_pay_time) - \(person.max_pay_time)", nil))
                        paymentMembers.append(.subInfo("缴费金额：", "\(person.fee_hkd)港币（≈\(person.fee_rmb)人民币)", nil))
                        paymentMembers.append(.subRemark("请先确认用户完成确认在港"))
                    case .confirmedPresence:
                        paymentMembers.append(.subInfo("档案号：", person.file_num, "复制", .mid, nil, false, { [weak self] in
                            guard let self = self else {
                                return
                            }
                            self.copyToPasteBoard(person.file_num, message: "已复制档案号")
                        }))
                        paymentMembers.append(.subInfo("可缴费时间段：", "\(person.min_pay_time) - \(person.max_pay_time)", nil))
                        paymentMembers.append(.subInfo("缴费金额：", "\(person.fee_hkd)港币（≈\(person.fee_rmb)人民币)", nil))
                        paymentMembers.append(.subRemark("请复制档案号去港府官网缴费"))
                    }
                case .paid:
                    var fileName = person.receipt
                    if fileName.count > 0, let url = URL(string: fileName) {
                        fileName = url.lastPathComponent
                    }
                    paymentMembers.append(.occupyingSpace)
                    paymentMembers.append(.subHeader(person.name, .paid))
                    paymentMembers.append(.subInfo("档案号：", person.file_num, "复制", .mid, 12, true, { [weak self] in
                        guard let self = self else {
                            return
                        }
                        self.copyToPasteBoard(person.file_num, message: "已复制档案号")
                    }))
                    paymentMembers.append(.subInfo("缴费金额：", "\(person.fee_hkd)港币（≈\(person.fee_rmb)人民币)", nil))
                    paymentMembers.append(.subContent("缴费电子签证：", fileName, "查看", .bottom, { [weak self] in
                        guard let self = self else {
                            return
                        }
                        self.gotoPreview(person.receipt)
                    }))
                    self.updateSureButtonState(true)
                    
                case .expired:
                    paymentMembers.append(.occupyingSpace)
                    paymentMembers.append(.subHeader(person.name, .expired))
                    paymentMembers.append(.subInfo("档案号：", person.file_num, "复制", .mid, nil, false, { [weak self] in
                        guard let self = self else {
                            return
                        }
                        self.copyToPasteBoard(person.file_num, message: "已复制档案号")
                    }))
                    paymentMembers.append(.subInfo("可缴费时间段：", "\(person.min_pay_time) - \(person.max_pay_time)", nil))
                    paymentMembers.append(.subInfo("缴费金额：", "\(person.fee_hkd)港币（≈\(person.fee_rmb)人民币)", nil))
                case .pendingApproval:
                    paymentMembers.append(.occupyingSpace)
                    paymentMembers.append(.subHeader(person.name, .pendingApproval))
                    paymentMembers.append(.subRemark("续签申请暂未正式获批，请耐心等待"))
                }
            }
            if let lastMember = actionMembers.last, case let.residenceAction(name, status, _, action) = lastMember {
                actionMembers[actionMembers.count - 1] = .residenceAction(name, status, .bottom, action)
                confirmingPresenceSection.append(contentsOf: actionMembers)
            }
            
            if paymentMembers.count > 0 {
                paymentMembers.append(.occupyingSpace)
            }
            sections.append(confirmingPresenceSection)
            let payMethodTips: ASAttributedString = .init(string: "提示：", .foreground(UIColor.yhOrangeColor)) + .init(string: "请先到下方“缴费成员”处") + .init(string: "复制档案号", .foreground(UIColor.yhOrangeColor)) + .init(string: "再缴费")
            let webPageUrl = paymentListModel.payment_url
            if webPageUrl.count > 0, URL(string: webPageUrl) != nil {
                let payMethodSection: [YHVisaRenewalItemDetailType] = [.sectionHeader("港府官网缴费方式", "缴费遇到问题?", { [weak self] in
                    guard let self = self else {
                        return
                    }
                    printLog("缴费遇到问题")
                    self.showTroubleshootingGuideVC()
                }), .tips(payMethodTips), .payMethodUrl("方式一", "点击下方链接，跳转浏览器，进入港府官网操作缴费", webPageUrl, { [weak self] in
                    guard let self = self else {
                        return
                    }
                    printLog("点击下方链接，跳转浏览器")
                    self.gotoWebVC(webPageUrl)
                }), .payMethodQrcode("方式二", "用其他设备直接扫码，或长按保存图片，通过微信识别打开", webPageUrl)]
                sections.append(payMethodSection)
            }
            var payMembersSection: [YHVisaRenewalItemDetailType] = [.sectionHeader("缴费成员", "电子签证范例", { [weak self] in
                guard let self = self else {
                    return
                }
                self.gotoPreview(paymentListModel.evisa_example_url)
            })]
            payMembersSection.append(contentsOf: paymentMembers)
            sections.append(payMembersSection)
            self.datas = sections
            self.tableView.reloadData()
        }
    }
    
    private func updateSureButtonState(_ isEnabled: Bool = false) {
        sureButton.alpha = isEnabled ? 1 : 0.3
        sureButton.isEnabled = isEnabled
    }
    
    private func showAlertView(confirmBlock: (() -> Void)?) {
        let alert = YHVisaRenewalPayConfirmingPresenceAlertView.alertView()
        alert.confirmBlock = {
            confirmBlock?()
        }
        alert.show()
    }
    
    private func showGuideVC() {
        let vc = YHVisaRenewalGuideVC()
        let pc = YHBottomPresentationController(presentedViewController: vc, presenting: self)
        pc.customRadius = 16.0
        vc.transitioningDelegate = pc
        vc.sureButtonEvent = { [weak vc] in
            vc?.dismiss(animated: true)
        }
        present(vc, animated: true, completion: nil)
    }
    
    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 showTroubleshootingGuideVC() {
        let vc = YHVisaRenewalTroubleshootingGuideVC()
        let pc = YHBottomPresentationController(presentedViewController: vc, presenting: self)
        pc.customRadius = 16.0
        vc.transitioningDelegate = pc
        vc.sureButtonEvent = { [weak vc] in
            vc?.dismiss(animated: true)
        }
        present(vc, 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 YHHKVisaRenewalPaymentVC: 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 .tips(detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalTipsCell.cellReuseIdentifier) as? YHVisaRenewalTipsCell {
                cell.setupCellInfo(detail: detail)
                return cell
            }
        case let .residenceAction(title, status, cellType, action):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalResidenceActionCell.cellReuseIdentifier) as? YHVisaRenewalResidenceActionCell {
                cell.setupCellInfo(title: title, presenceStatus: status, cellType: cellType)
                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, status):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayStatusCell.cellReuseIdentifier) as? YHVisaRenewalPayStatusCell {
                cell.setupCellInfo(title: title, status: status)
                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 let .subRemark(detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHVisaRenewalPayTipsCell.cellReuseIdentifier) as? YHVisaRenewalPayTipsCell {
                cell.setupCellInfo(detail: detail)
                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
    }
}
