//
//  YHAIPictureMessageCell.swift
//  galaxy
//
//  Created by Dufet on 2024/12/3.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SDWebImage
import Photos
import PhotosUI

class YHAIPictureMessageCell: UITableViewCell {

    static let cellReuseIdentifier = "YHAIPictureMessageCell"
    var updateBlock: (() -> Void)?
    var imgInfo = YHAIImageInfo() {
        didSet {
            
            if imgInfo.imageType == YHAIImageType.url.rawValue {
                
                // 尝试从缓存中获取图片
                if let cachedImage = SDImageCache.shared.imageFromCache(forKey: imgInfo.imageUrl) {
                    // 如果缓存中有图片，则直接使用
                    imgView.image = cachedImage
                    let size = self.getShowSize(image: cachedImage)
                    self.imgView.snp.updateConstraints { make in
                        make.width.equalTo(size.width)
                        make.height.equalTo(size.height)
                    }

                } else {
                    imgView.sd_setImage(with: URL(string: imgInfo.imageUrl), placeholderImage: UIImage(named: "global_default_image"), options: [], completed: { (_, _, _, _) in
                        self.updateBlock?()
                    })
                }
                
            } else if imgInfo.imageType == YHAIImageType.local.rawValue {
                if let img = UIImage(named: imgInfo.localImageName) {
                    imgView.image = img
                    self.imgView.snp.updateConstraints { make in
                        make.width.equalTo(img.size.width)
                        make.height.equalTo(img.size.height)
                    }
                } else {
                    imgView.image = UIImage(named: "global_default_image")
                    self.imgView.snp.updateConstraints { make in
                        make.width.equalTo(200)
                        make.height.equalTo(200)
                    }
                }
            }
            
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    func getShowSize(image: UIImage?) -> CGSize {
        
        let imgW = 220.0
        var imgH = 220.0
        var ratio = 1.0
        
        guard let img = image else {
            return CGSize(width: imgW, height: imgH)
        }
        if img.size.width > 0, img.size.height > 0 {
            ratio = img.size.width/img.size.height
        }
        imgH = imgW/ratio
        return CGSize(width: imgW, height: imgH)
    }

    lazy var imgView: UIImageView = {
        let v = UIImageView(image: UIImage(named: "global_default_image"))
        return v
    }()
    
    lazy var downloadBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ai_chat_img_download"), for: .normal)
        btn.addTarget(self, action: #selector(didDownloadBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = 6.0
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        return btn
    }()
    
    lazy var whiteContentView: UIView = {
        let v = UIView()
        let tap = UITapGestureRecognizer(target: self, action: #selector(didMessageClicked))
        v.addGestureRecognizer(tap)
        return v
    }()
    
    lazy var shadowView: YHAIChatShadowView = {
        let v = YHAIChatShadowView()
        return v
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        roundCorners(keepTopLeft: true)
    }
    
    func setupUI() {
        
        selectionStyle = .none
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        contentView.addSubview(shadowView)
        contentView.addSubview(whiteContentView)
        whiteContentView.addSubview(imgView)
        whiteContentView.addSubview(downloadBtn)
        
        whiteContentView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(20)
            make.bottom.equalTo(0)
        }
        
        imgView.snp.makeConstraints { make in
            make.width.equalTo(220)
            make.height.equalTo(220)
            make.edges.equalToSuperview()
        }
        
        downloadBtn.snp.makeConstraints { make in
            make.width.equalTo(26)
            make.height.equalTo(26)
            make.left.equalTo(16)
            make.bottom.equalTo(-16)
        }
        
        shadowView.snp.makeConstraints { make in
            make.left.equalTo(whiteContentView).offset(-0)
            make.right.equalTo(whiteContentView).offset(0)
            make.top.equalTo(whiteContentView).offset(-0)
            make.bottom.equalTo(whiteContentView).offset(0)
        }
    }
    
    @objc func didMessageClicked() {
        
        UIApplication.shared.yhKeyWindow()?.endEditing(true)
        YHPictureReviewManager.shared.showNetWorkPicturs(curIndex: 0, arrPicturs: [imgInfo.imageUrl])
    }
    
    @objc func didDownloadBtnClicked() {
        
        if imgInfo.imageType == YHAIImageType.url.rawValue {
            // 尝试从缓存中获取图片
            let cachedImage = SDImageCache.shared.imageFromCache(forKey: imgInfo.imageUrl)
            downloadImage(cachedImage, urlString: imgInfo.imageDownloadUrl)
                
        } else if imgInfo.imageType == YHAIImageType.local.rawValue {
            let img = UIImage(named: imgInfo.localImageName)
            downloadImage(img, urlString: imgInfo.imageDownloadUrl)
        }
    }
    
    func downloadImage(_ img: UIImage?, urlString: String) {
        
        if let img = img {
            saveImage(img)
            return
        }
        
        guard let url = URL(string: urlString) else {
            YHHUD.flash(message: "保存失败")
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) {
            [weak self] data, _, _ in
            DispatchQueue.main.async {
                guard let self = self else { return }
                guard let data = data else {
                    YHHUD.flash(message: "保存失败")
                    return
                }
                let image = UIImage(data: data)
                if let image = image {
                    self.saveImage(image)
                }
            }
        }
        task.resume()
    }
    
    func saveImage(_ 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 roundCorners(keepTopLeft: Bool) {
          let path = UIBezierPath()
          let radius: CGFloat = 6.0 // 圆角半径

          // 设置路径
          path.move(to: CGPoint(x: keepTopLeft ? 0 : radius, y: 0)) // 从左上角开始，视情况决定是否切圆角
          
          // 左上角
          if keepTopLeft {
              path.addLine(to: CGPoint(x: 0, y: 0)) // 不切左上角
          } else {
              path.addArc(withCenter: CGPoint(x: radius, y: radius), radius: radius, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)
          }

          // 右上角
          path.addLine(to: CGPoint(x: self.bounds.width, y: 0))
          path.addArc(withCenter: CGPoint(x: self.bounds.width - radius, y: radius), radius: radius, startAngle: .pi * 1.5, endAngle: 0, clockwise: true)

          // 右下角
          path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height))
          path.addArc(withCenter: CGPoint(x: self.bounds.width - radius, y: self.bounds.height - radius), radius: radius, startAngle: 0, endAngle: .pi / 2, clockwise: true)

          // 左下角
          path.addLine(to: CGPoint(x: 0, y: self.bounds.height))
          path.addArc(withCenter: CGPoint(x: radius, y: self.bounds.height - radius), radius: radius, startAngle: .pi / 2, endAngle: .pi, clockwise: true)

          path.close() // 关闭路径

          // 创建 CAShapeLayer
          let maskLayer = CAShapeLayer()
          maskLayer.path = path.cgPath
          self.whiteContentView.layer.mask = maskLayer // 设置 UIView 的 mask
      }
}
