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

import Kingfisher
import UIKit
import Photos
import PhotosUI
// 这是一个无效的提交
class YHLongtapPictureSheetView: UIView {
    private var uploadTypeArr = ["分享图片", "保存图片", "取消"]
//    private let testUrl = "https://img1.baidu.com/it/u=2032777443,4245182967&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1422"
    var myUrl: String = ""
    
    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var topView: UIView = {
        let view = UIView()
        view.addSubview(titleLabel)
        view.addSubview(closeBtn)
        
        let line = UIView()
        line.backgroundColor = .separatorColor
        view.addSubview(line)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.left.right.equalToSuperview()
            make.height.equalTo(24)
        }
        closeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.right.equalToSuperview().offset(-20)
            make.width.height.equalTo(24)
        }
        line.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_B(ofSize: 17)
        label.text = "请选择"
        return label
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "my_cer_sheet_close"), for: .normal)
        btn.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
        return btn
    }()
    
    lazy var shareBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(share), for: .touchUpInside)
        btn.setTitle("分享图片", for: .normal)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        return btn
    }()
    
    lazy var saveBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(save), for: .touchUpInside)
        btn.setTitle("保存图片", for: .normal)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        return btn
    }()
    
    lazy var closeBtn2: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
        btn.setTitle("取消", for: .normal)
        btn.setTitleColor(UIColor(hex: 0x909090, alpha: 1.0), for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        return btn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    static func sheetView() -> YHLongtapPictureSheetView {
        let view = YHLongtapPictureSheetView(frame: UIScreen.main.bounds)
        return view
    }

    func createUI() {
        
        self.addSubview(blackMaskView)
        self.addSubview(whiteContentView)
        whiteContentView.addSubview(topView)
        
        whiteContentView.addSubview(shareBtn)
        
        let line = UIView()
        line.backgroundColor = .separatorColor
        whiteContentView.addSubview(line)
        whiteContentView.addSubview(saveBtn)
        
        let line2 = UIView()
        line2.backgroundColor = .separatorColor
        whiteContentView.addSubview(line2)
        
        whiteContentView.addSubview(closeBtn2)

        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = whiteContentView.bounds
        layer.path = path.cgPath
        whiteContentView.layer.mask = layer
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let whiteHeight = calculateHeight()
        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(whiteHeight)
        }
        topView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(53)
        }
        
        shareBtn.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(52)
        }
        
        line.snp.makeConstraints { make in
            make.top.equalTo(shareBtn.snp.bottom)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
        }
        
        saveBtn.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(52)
        }
        
        line2.snp.makeConstraints { make in
            make.top.equalTo(saveBtn.snp.bottom)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
        }
        
        closeBtn2.snp.makeConstraints { make in
            make.top.equalTo(line2.snp.bottom)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(52)
        }
        
    }
    
    func calculateHeight() -> CGFloat {
        // 底部四个操作行高度之和
        let tableViewHeight = 52.0 * Double(self.uploadTypeArr.count) + (Double(self.uploadTypeArr.count - 1)) * 1
        // 白色View总高度
        let totalHeight = 52.0 + 1 + tableViewHeight + k_Height_safeAreaInsetsBottom()
        return totalHeight
    }
}

extension YHLongtapPictureSheetView {
    
    func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    @objc func dismiss() {
        DispatchQueue.main.async {
            self.removeFromSuperview()
        }
    }
}

private extension YHLongtapPictureSheetView {
    @objc func share() {
        self.dismiss()
        guard let url = URL(string: myUrl) else {
            return
        }
        let task = URLSession.shared.dataTask(with: url) { data, _, error in
            DispatchQueue.main.async {
                guard let data = data, error == nil else { return }
                let image = UIImage(data: data)
                if let image = image {
                    YHShareManager.shared.sendImageContent(image)
                }
            }
            
        }
        task.resume()
    }
    
    @objc func save() {
        saveLocalPictureSyn(myUrl)
        self.dismiss()
        
    }
    
    func saveLocalPictureSyn(_ picUrl: String) {
        guard let url = URL(string: picUrl) else {
            YHHUD.flash(message: "保存失败")
            return
        }
        KingfisherManager.shared.retrieveImage(with: url) { result in
            switch result {
            case .success(let imageLoadingResult):
                self.saveImage(imageLoadingResult.image)
            case .failure:
                YHHUD.flash(message: "保存失败")
            }
        }
//        let imageView = UIImageView()
//        imageView.kf.setImage(with: URL(string: picUrl)) { result in
//            switch result {
//            case .success(let value):
//                self.saveImage(value.image)
//            case .failure:
//                YHHUD.flash(message: "保存失败")
//            }
//        }
    }
    
    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: "保存失败，请检查系统权限")
                }
            }
        }
    }
}
