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

import UIKit
import AttributedString
import Photos

class YHVisaPayTypeCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHVisaPayTypeCell"
    
    var dataModel: YHVisaPaymentListModel? {
        didSet {
            updataUI()
        }
    }
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius6
        view.clipsToBounds = true
        view.backgroundColor = .white
        return view
    }()
    
    lazy var linkLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textColor = UIColor.brandMainColor
        label.font = UIFont.PFSC_R(ofSize: 12)
        let linkTxt: String = "https://www.gov.hk/tc/residents/immigration/nonpermanent/onlinepaymentforevisa.htm"
        return label
    }()
    
    lazy var qrCodeImageView: UIImageView = {
        let qrCode: UIImageView = UIImageView()
        qrCode.contentMode = .scaleAspectFill
        qrCode.isUserInteractionEnabled = false
        qrCode.addGestureRecognizer(longPress)
        return qrCode
    }()
    
    /// 已添加的长按手势
    private lazy var longPress: UILongPressGestureRecognizer = {
        return UILongPressGestureRecognizer(target: self, action: #selector(onLongPress(_:)))
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
}

private extension YHVisaPayTypeCell {
    
    func updataUI() {
        guard let model = dataModel else { return }
        
        let linkTxt: String = model.payment_url
        
        let aa: ASAttributedString = .init(NSAttributedString(string: linkTxt), .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.brandMainColor), .underline([.single], color: UIColor.brandMainColor), .action {
            if let url = URL(string: linkTxt) {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    // 显示一个提示，告知用户无法打开链接
                    print("无法打开链接")
                }
            }
        })
        linkLabel.attributed.text = aa
        
        let qrString = linkTxt
        if let qrCode = qrString.generateQRCode() {
            // 可以将qrCode设置为UIImageView的image属性来显示二维码
            self.qrCodeImageView.image = qrCode
            self.qrCodeImageView.isUserInteractionEnabled = true
        }
        
    }
    
    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 {
            print("保存照片失败：\(error.localizedDescription)")
            YHHUD.flash(message: "保存失败")
        } else {
            print("保存照片成功")
            
            YHHUD.flash(message: "保存成功")
        }
    }
    
    /// 长按
    @objc func onLongPress(_ press: UILongPressGestureRecognizer) {
        if press.state == .began {
            if let image = self.qrCodeImageView.image {
                saveImage(image)
            } else {
                YHHUD.flash(message: "保存失败")
            }
            
        }
    }
    
    func setupUI() {
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        contentView.addSubview(whiteContentView)
        
        whiteContentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        //
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_M(ofSize: 17)
        label.text = "港府官网缴费方式"
        
        whiteContentView.addSubview(label)
        label.snp.makeConstraints { make in
            make.top.equalTo(kMargin)
            make.left.equalTo(kMargin)
            make.height.equalTo(24)
        }
        
        let line = UIView()
        line.backgroundColor = .separatorColor
        whiteContentView.addSubview(line)
        
        line.snp.makeConstraints { make in
            make.top.equalTo(label.snp.bottom).offset(12)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(1)
        }
        
        let label1 = UILabel()
        label1.textColor = UIColor.mainTextColor
        label1.font = UIFont.PFSC_M(ofSize: 14)
        label1.text = "方式一"
        
        whiteContentView.addSubview(label1)
        label1.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(kMargin)
            make.left.equalTo(kMargin)
            make.height.equalTo(20)
        }
        
        let label2 = UILabel()
        label2.textColor = UIColor.mainTextColor50
        label2.font = UIFont.PFSC_R(ofSize: 12)
        label2.text = "点击下方链接，跳转浏览器，进入港府官网操作缴费"
        
        whiteContentView.addSubview(label2)
        label2.snp.makeConstraints { make in
            make.top.equalTo(label1.snp.bottom).offset(6)
            make.left.equalTo(kMargin)
            make.height.equalTo(17)
        }
        
        let holdView = UIView()
        holdView.backgroundColor = .contentBkgColor
        holdView.layer.cornerRadius = kCornerRadius4
        holdView.clipsToBounds = true
        whiteContentView.addSubview(holdView)
        
        holdView.snp.makeConstraints { make in
            make.top.equalTo(label2.snp.bottom).offset(6)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(66)
        }
        
        holdView.addSubview(linkLabel)
        linkLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
        }
        
        let line2 = UIView()
        line2.backgroundColor = .separatorColor
        whiteContentView.addSubview(line2)
        
        line2.snp.makeConstraints { make in
            make.top.equalTo(holdView.snp.bottom).offset(16)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(1)
        }
        
        whiteContentView.addSubview(qrCodeImageView)
        qrCodeImageView.snp.makeConstraints { make in
            make.top.equalTo(line2.snp.bottom).offset(18)
            make.right.equalTo(-kMargin)
            make.height.width.equalTo(86)
            make.bottom.equalToSuperview().offset(-kMargin)
        }
        
        let label3 = UILabel()
        label3.textColor = UIColor.mainTextColor
        label3.font = UIFont.PFSC_M(ofSize: 14)
        label3.text = "方式二"
        
        whiteContentView.addSubview(label3)
        label3.snp.makeConstraints { make in
            make.top.equalTo(qrCodeImageView.snp.top).offset(12)
            make.left.equalTo(kMargin)
            make.height.equalTo(20)
        }
        
        let label4 = UILabel()
        label4.numberOfLines = 0
        label4.lineBreakMode = .byWordWrapping
        label4.textColor = UIColor.mainTextColor50
        label4.font = UIFont.PFSC_R(ofSize: 12)
        label4.text = "用其他设备直接扫码，或长按保存图片，通过微信识别打开"
        
        whiteContentView.addSubview(label4)
        label4.snp.makeConstraints { make in
            make.top.equalTo(label3.snp.bottom).offset(6)
            make.left.equalTo(kMargin)
            make.right.equalTo(qrCodeImageView.snp.left).offset(-kMargin)
        }
        
        let linkTxt: String = "https://www.gov.hk/tc/residents/immigration/nonpermanent/onlinepaymentforevisa.htm"
        let aa: ASAttributedString = .init(NSAttributedString(string: linkTxt), .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.brandMainColor), .underline([.single], color: UIColor.brandMainColor), .action {
            if let url = URL(string: linkTxt) {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    // 显示一个提示，告知用户无法打开链接
                    print("无法打开链接")
                }
            }
        })
        linkLabel.attributed.text = aa
    }
}
