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

import UIKit

class YHMyNotifySettingVC: YHBaseViewController {

    var items:[YHPermissionItem] = [YHPermissionItem(title: "接收推送消息通知".local, type:.notify, 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)
        checkNotifyPermission()
    }
    
    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(checkNotifyPermission), name: YhConstant.YhNotification.didReqeustNotifyPermissionNotification, object: nil)
    }
    
    @objc func checkNotifyPermission() {
        checkNotificationAuthorizationStatus {
            [weak self] granted in
            guard let self = self else { return }
            for item in items {
                if item.type == .notify {
                    item.enableStatus = granted
                }
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
    
    func checkNotificationAuthorizationStatus(_ callBack:((Bool)->())?) {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            var enableStatus = false
            switch settings.authorizationStatus {
            case .authorized:
                print("通知已授权")
                enableStatus = true
            case .denied:
                print("通知被拒绝")
                enableStatus = false
            case .notDetermined:
                print("通知权限尚未确定")
                enableStatus = false
            case .provisional:
                print("通知以临时方式授权")
                enableStatus = false
            case .ephemeral:
                enableStatus = false
            @unknown default:
                break
            }
            callBack?(enableStatus)
        }
    }
}

extension YHMyNotifySettingVC: 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) {
       
        let url = URL(string: UIApplication.openSettingsURLString)
        if let url = url, UIApplication .shared.canOpenURL(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 = "允许银河APP向您发送通知，可以及时了解到服务进度提醒、政策解读等系统通知".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
    }
    
}


