//
//  YHConsultantQRCodeView.swift
//  galaxy
//
//  Created by edy on 2024/7/4.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Photos

class YHConsultantQRCodeView: UIView {

    var codeUrl:String = "" {
        didSet {
            if !codeUrl.isEmpty {
                self.qrCodeImgView.kf.setImage(with: URL(string: codeUrl), placeholder: UIImage(named: "global_default_image"))
            }
        }
    }
    
    var downloadUrl: String = "" {
        didSet {
            if !downloadUrl.isEmpty {
                self.downloadCodeImgView.kf.setImage(with: URL(string: downloadUrl)) { result in
                    switch result {
                    case .success(let value):
                        self.downloadCodeImage = value.image
                        self.saveBtn.alpha = 1.0
                        self.saveBtn.isUserInteractionEnabled = true
                        
                    case .failure(let value):
                        self.saveBtn.alpha = 0.3
                        self.saveBtn.isUserInteractionEnabled = false
                    }
                }
            }
        }
    }
    
    var downloadCodeImage:UIImage? = nil
    // 底层蒙版
    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.68)
        return view
    }()
    
    lazy var bgImgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "home_web_consult_bg"))
        view.isUserInteractionEnabled = true
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "专属顾问".local
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_B(ofSize: 22)
        return label
    }()
    
    lazy var detailLabel: UILabel = {
        let label = UILabel()
        label.text = "微信扫码添加专属顾问".local
        label.textColor = UIColor.mainTextColor70
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize: 15)
        return label
    }()
    
    lazy var qrCodeImgView:UIImageView = {
        let view = UIImageView(image: UIImage(named: "global_default_image"))
        return view
    }()
    
    lazy var downloadCodeImgView:UIImageView = {
        let view = UIImageView()
        return view
    }()
    
    lazy var saveBtn: UIButton = {
        let button = UIButton()
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        button.setTitle("保存到相册", for: .normal)
        button.setTitleColor( UIColor.white, for: .normal)
        button.backgroundColor = UIColor.brandMainColor
        button.addTarget(self, action: #selector(didSaveQRCodeBtnClicked), for: .touchUpInside)
        button.layer.cornerRadius = 3
        button.alpha = 0.3
        button.isUserInteractionEnabled = false
        return button
    }()
    
    lazy var closeBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "update_close"), for: .normal)
        btn.addTarget(self, action: #selector(didCloseBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    static func codeView(_ url: String, downloadUrl: String) -> YHConsultantQRCodeView {
        let alertView = YHConsultantQRCodeView(frame:UIScreen.main.bounds)
        alertView.codeUrl = url
        alertView.downloadUrl = downloadUrl
        return alertView
    }
    
    @objc func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    func createUI() {
        self.addSubview(blackMaskView)
        self.addSubview(bgImgView)
        bgImgView.addSubview(titleLabel)
        bgImgView.addSubview(detailLabel)
        bgImgView.addSubview(qrCodeImgView)
        bgImgView.addSubview(saveBtn)
        self.addSubview(closeBtn)

        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        bgImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-(20.0+24.0)/2.0)
            make.width.equalTo(299.0)
            make.height.equalTo(491.0)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(129.0)
            make.height.equalTo(30.0)
            make.centerX.equalToSuperview()
        }
        
        detailLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(2.0)
            make.height.equalTo(20.0)
            make.centerX.equalToSuperview()
        }
        
        qrCodeImgView.snp.makeConstraints { make in
            make.top.equalTo(detailLabel.snp.bottom).offset(20.0)
            make.width.height.equalTo(192.0)
            make.centerX.equalToSuperview()
        }
        
        saveBtn.snp.makeConstraints { make in
            make.left.equalTo(24.0)
            make.right.equalTo(-24.0)
            make.top.equalTo(qrCodeImgView.snp.bottom).offset(28.0)
            make.height.equalTo(45.0)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.top.equalTo(bgImgView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
        }
    }
    
    @objc func didSaveQRCodeBtnClicked() {
        if let img = self.downloadCodeImage {
            self.saveImage(img)
        }
    }
    
    @objc func didCloseBtnClicked() {
        self.dismiss()
    }
   
    func saveImage(_ image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                DispatchQueue.main.sync {
                    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            } else {
                YHHUD.flash(message: "没有访问图库权限")
            }
        }
    }
    
    @objc func image(image: UIImage,didFinishSavingWithError: NSError?,contextInfo: AnyObject) {
        if didFinishSavingWithError != nil {
            YHHUD.flash(message: "保存失败")
            return
        }
        YHHUD.flash(message: "保存成功")
    }
}
