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

import UIKit
import Photos

enum YHPermissionType: Int {
    case none = 0
    case network = 1
    case photo = 2
    case camera = 3
    case location = 4
    case file = 5
    case notify = 6
}

class YHPermissionItem {
    var type: YHPermissionType = .none
    var title:String = ""
    var enableStatus:Bool = false
    init(title: String, type:YHPermissionType, enableStatus: Bool) {
        self.title = title
        self.type = type
        self.enableStatus = enableStatus
    }
}

class YHMyPermissionSettingVC: YHBaseViewController {

    let items:[YHPermissionItem] = [YHPermissionItem(title: "网络".local, type:.network, enableStatus: YHNetworkStatusManager.shared.isNetWorkOK),
                                    YHPermissionItem(title: "照片".local, type:.photo, enableStatus: false),
                                    YHPermissionItem(title: "相机".local, type:.camera, enableStatus: false)]
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame:.zero, style:.grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .white
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHMyPermissionCell.self, forCellReuseIdentifier: YHMyPermissionCell.cellReuseIdentifier)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestPermission()
    }
    
    func setupUI() {
        gk_navTitle = "权限设置".local
        view.backgroundColor = .white
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview().offset(-k_Height_TabBar)
        }
        NotificationCenter.default.addObserver(self, selector: #selector(updateNetWorkStatus), name: .reachabilityChanged, object: nil)
            
    }
    
    @objc func updateNetWorkStatus() {
        for item in items {
            if item.type == .network {
                DispatchQueue.main.async {
                    item.enableStatus = YHNetworkStatusManager.shared.isNetWorkOK
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func requestPermission() {
        
        // 1）获取网络状态并更新
        updateNetWorkStatus()
        
        // 2）获取相册权限
        requestAndUpdatePhotoPermission()
        
        // 3）获取相机权限
        requestAndUpdateCameraPermission()
    }
    
    func requestAndUpdatePhotoPermission() {
        requestPhotoLibraryPermission {
            [weak self] grant in
            guard let self = self else { return }
            for item in items {
                if item.type == .photo {
                    DispatchQueue.main.async {
                        item.enableStatus = grant
                        self.tableView.reloadData()
                    }
                }
            }
        }
    }
    
    func requestAndUpdateCameraPermission() {
        requestCameraPermission {
            [weak self] grant in
            guard let self = self else { return }
            for item in items {
                if item.type == .camera {
                    DispatchQueue.main.async {
                        item.enableStatus = grant
                        self.tableView.reloadData()
                    }
                }
            }
        }
    }
    
    func requestPhotoLibraryPermission(completion: @escaping (Bool) -> Void) {
        let status = PHPhotoLibrary.authorizationStatus()
        
        switch status {
        case .authorized:
            // 已经授权
            completion(true)
            
        case .denied, .restricted, .limited:
            // 拒绝或受限制，需要提示用户去设置中授权
            completion(false)
            
        case .notDetermined:
            // 尚未确定，请求授权
            completion(false)
            
        @unknown default:
            completion(false)
        }
    }
    
    func requestCameraPermission(completion: @escaping (Bool) -> Void) {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        
        switch status {
        case .authorized:
            // 已经授权
            completion(true)
            
        case .denied, .restricted:
            // 拒绝或受限制，需要提示用户去设置中授权
            completion(false)
            
        case .notDetermined:
            // 尚未确定，请求授权
            completion(false)
            
        @unknown default:
            completion(false)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension YHMyPermissionSettingVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHMyPermissionCell.cellReuseIdentifier, for: indexPath) as! YHMyPermissionCell
        if 0 <= indexPath.row && indexPath.row < items.count {
            let item = items[indexPath.row]
            cell.updateModel(item)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 53.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if 0 <= indexPath.row && indexPath.row < items.count {
            let item = items[indexPath.row]
            if item.type == .photo {
                let status = PHPhotoLibrary.authorizationStatus()
                if status == .notDetermined {
                    PHPhotoLibrary.requestAuthorization {
                        authorizationStatus in
                        self.requestPhotoLibraryPermission {
                            [weak self] granted in
                            guard let self = self else { return }
                            requestAndUpdatePhotoPermission()
                        }
                    }
                    return
                }
            }
            if item.type == .camera {
                let status = AVCaptureDevice.authorizationStatus(for: .video)
                if status == .notDetermined {
                    AVCaptureDevice.requestAccess(for: .video) {
                        [weak self] granted in
                        guard let self = self else { return }
                        requestAndUpdateCameraPermission()
                    }
                    return
                }
            }
            let url = URL(string: UIApplication.openSettingsURLString)
            if let url = url, UIApplication .shared.canOpenURL(url) {
                printLog("settingUrl:\(url)")
                UIApplication .shared.open(url, options: [:], completionHandler: {
                    (success) in
                })
            }
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0xF8FAFB)
        
        let label = UILabel()
        label.textColor = UIColor.mainTextColor50
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize:12)
        label.numberOfLines = 0
        label.text = "为了更好的使用体验，银河在特定场景会向您申请手机系统权限。您可以随时在手机系统设置中修改".local
        view.addSubview(label)

        label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(12)
            make.bottom.equalToSuperview().offset(-12)
        }
        return view
    }
    
}

