//
//  YHShareAlertView.swift
//  galaxy
//
//  Created by EDY on 2024/11/30.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString
import Photos

class YHShareAlertView: UIView {
    var fromAiSale: Bool = false
    var centerView: UIView!
    var leftButton: YHShareButton!
    var centerButton: YHShareButton!
    var rightButton: YHShareButton!
    var cannalButton: UIButton!
    var tableView: UITableView!
    var shareView: UIImageView!
    var mainImageView: UIImageView!
    var titleLabel: UILabel!
    var messageLabel: UILabel!
    var bottomView: UIImageView!
    var bottomTitleLabel: UILabel!
    var flagImageView: UIImageView!
    var liveView: UIImageView!
    var image: String = "" {
        didSet {
            mainImageView.kf.setImage(with: URL(string: image))
        }
    }
    var title: String = "" {
        didSet {
            titleLabel.text = title
        }
    }
    var subMessage: String = "" {
        didSet {
            messageLabel.text = subMessage
        }
    }
    var linkUrl: String = "" {
        didSet {
            let qrString = linkUrl
            if let qrCode = qrString.generateQRCode() {
                // 可以将qrCode设置为UIImageView的image属性来显示二维码
                flagImageView.image = qrCode
            }
        }
    }
    var isLive: Bool = false {
        didSet {
            liveView.isHidden = !isLive
        }
    }

    var dataSource: [String] = [] {
        didSet {
            self.tableView.reloadData()
        }
    }
    var selectItem: Int = 10000
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.5, alpha: 0.1)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func setView() {
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(dismiss), name: YhConstant.YhNotification.closeShareUIInLiveRoomNotifiction, object: nil)
        
        backgroundColor = UIColor(hex: 0x0000, alpha: 0.5)
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(216)
        }
        
        leftButton = {
            let button = YHShareButton()
            button.setContent("invitation_with_gifts_share_center", "微信")
            button.addTarget(self, action: #selector(wxClick), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(leftButton)
        leftButton.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.left.equalTo(42)
            make.height.equalTo(74)
            make.width.equalTo(52)
        }
        
        centerButton = {
            let button = YHShareButton()
            button.setContent("invitation_with_gifts_share_link", "复制链接")
            button.addTarget(self, action: #selector(linkClick), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(centerButton)
        centerButton.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.centerX.equalToSuperview()
            make.height.equalTo(74)
            make.width.equalTo(52)
        }
        
        rightButton = {
            let button = YHShareButton()
            button.setContent("invitation_with_gifts_share_save", "保存图片")
            button.addTarget(self, action: #selector(saveClick), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(rightButton)
        rightButton.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.right.equalTo(-42)
            make.height.equalTo(74)
            make.width.equalTo(52)
        }
        
        cannalButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.contentBkgColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
            button.contentHorizontalAlignment = .center
            button.setTitle("取消", for: .normal)
            button.setTitleColor( UIColor.mainTextColor, for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(cannalButton)
        cannalButton.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(126)
            make.height.equalTo(44)
            make.right.equalTo(-16)
        }
        
        shareView = {
            let view = UIImageView()
            view.backgroundColor = .white
            return view
        }()
        addSubview(shareView)
        shareView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(432)
            make.width.equalTo(271)
            make.bottom.equalTo(centerView.snp.top).offset(-67)
        }
        
        mainImageView = {
            let view = UIImageView()
            return view
        }()
        shareView.addSubview(mainImageView)
        mainImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.height.equalTo(239)
            make.top.equalTo(16)
        }
        
        titleLabel = {
            let label = UILabel()
            label.textColor = UIColor.mainTextColor
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.text = "香港事业星陪伴(7)"
            return label
        }()
        shareView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(mainImageView.snp.bottom).offset(16)
            make.left.equalTo(16)
            make.right.equalTo(16)
        }
        
        messageLabel = {
            let label = UILabel()
            label.textColor = UIColor(hex: 0x6d788a)
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.text = "香港入境计划申请到永居全流程服务)"
            label.numberOfLines = 2
            return label
        }()
        shareView.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(6)
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }
        
        bottomView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_share_bg_bottom")
            return view
        }()
        shareView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(92)
        }
        
        bottomTitleLabel = {
            let label = UILabel()
            label.numberOfLines = 0
            let a: ASAttributedString = .init("银河", .font(UIFont.PFSC_B(ofSize: 13)),.foreground(UIColor.mainTextColor))
            let b: ASAttributedString = .init("港生活\n", .font(UIFont.PFSC_B(ofSize: 13)),.foreground(UIColor.brandMainColor))
            let c: ASAttributedString = .init("美好新生活从这里开始", .font(UIFont.PFSC_R(ofSize: 10)),.foreground(UIColor(hex: 0x8993a2)))
            label.attributed.text = a + b + c
            return label
        }()
        bottomView.addSubview(bottomTitleLabel)
        bottomTitleLabel.snp.makeConstraints { make in
            make.bottom.equalTo(-20)
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }
        
        flagImageView = {
            let view = UIImageView()
            return view
        }()
        bottomView.addSubview(flagImageView)
        flagImageView.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.width.height.equalTo(72)
            make.bottom.equalTo(-16)
        }
        
        liveView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_share_live")
            return view
        }()
        mainImageView.addSubview(liveView)
        liveView.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.bottom.equalTo(-12)
            make.height.equalTo(16)
            make.width.equalTo(51)
        }
        
        centerView.layoutIfNeeded()
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(kCornerRadius6, kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = centerView.bounds
        layer.path = path.cgPath
        centerView.layer.mask = layer
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        dismiss()
    }
    
    static func show(image: String = "", title: String = "", subMessage: String = "", linkUrl: String = "", isLive: Bool = false, fromAiSale: Bool = false) {
        let view = YHShareAlertView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.image = image
        view.title = title
        view.subMessage = subMessage
        view.linkUrl = linkUrl
        view.isLive = isLive
        view.fromAiSale = fromAiSale
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
    @objc func saveClick() {
        guard let combinedImage = combinedImageFrom(imageView: shareView) else { return }
        saveImageToPhotosAlbum(image: combinedImage)
    }
    
    @objc func linkClick() {
        let textToCopy = linkUrl
        UIPasteboard.general.string = textToCopy
        YHHUD.flash(message: "复制成功")
    }
    
    @objc func wxClick() {
        if fromAiSale {
//            let content = isLive ? "\(title)正在直播中，快来围观吧～" : "点击查看详情讲解～"
            let content = isLive ? "分享您一个直播间，快来看看吧～" : "点击查看详情讲解～"
            YHShareManager.shared.sendLinkContent(subMessage, content, mainImageView.image ?? UIImage(), link: linkUrl)
        } else {
            YHShareManager.shared.sendLinkContent(title, subMessage, mainImageView.image ?? UIImage(), link: linkUrl)
        }
    }
    
    func saveImageToPhotosAlbum(image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                DispatchQueue.main.async {
                    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                    YHHUD.flash(message: "保存成功")
                }
            } else {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "保存失败，请检查系统权限")
                }
            }
        }
    }
    
    func combinedImageFrom(imageView: UIImageView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 0.0)
        // 首先绘制 imageView 的内容
        imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
        // 获取合成后的图像
        let combinedImage = UIGraphicsGetImageFromCurrentImageContext()

        // 结束绘图上下文
        UIGraphicsEndImageContext()

        return combinedImage
    }
}

extension YHShareAlertView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer:UIGestureRecognizer, shouldReceive touch:UITouch) -> Bool {
        if touch.view == self {
            return true
        }
        return false
    }
}
