//
//  PMEmailSupportController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/19.
//

import UIKit
import MessageUI

class PMEmailSupportController: BaseViewController {

    @IBOutlet weak var emailTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        titleView.model.title = "Email support"
        setup()
    }
    
    func setup() -> Void {
        emailTableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview().inset(marginLR)
            make.top.equalTo(titleView.snp.bottom).offset(10)
        }
        emailTableView.sectionHeaderHeight = 40
        if #available(iOS 15.0, *) {
            emailTableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        emailTableView.register(UINib(nibName: PMEmailSupportCell.id, bundle: nil), forCellReuseIdentifier: PMEmailSupportCell.id)
        emailTableView.showsVerticalScrollIndicator = false
        let file = Bundle.main.bundleURL.appendingPathComponent("PMEmailSupportData.json")
        do{
            let dictData = try Data(contentsOf: file)
            dataSource = try JSONDecoder().decode([FAQDataModel].self, from: dictData)
        }catch{ }
    }
    
    var dataSource:[FAQDataModel] = [] {
        didSet {
            self.emailTableView.reloadData()
        }
    }

}

extension PMEmailSupportController : UITableViewDelegate,UITableViewDataSource,MFMailComposeViewControllerDelegate {
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PMEmailSupportCell.id, for: indexPath) as! PMEmailSupportCell
        cell.selectionStyle = .none
        cell.data = dataSource[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UILabel()
        header.text = "Please select a request from the following list."
        header.textColor = UIColor.colorWithHex(hexStr: "#999999")
        header.font = UIFont.systemFont(ofSize: 12)
        header.backgroundColor = .white
        return header
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = dataSource[indexPath.row]
        if data.problem != "Other" {
            let support = PMEmailSupportDetailController()
            support.data = data
            self.navigationController?.pushViewController(support, animated: true)
        }else{
            if MFMailComposeViewController.canSendMail() {
                let mail = MFMailComposeViewController()
                mail.mailComposeDelegate = self
                mail.setSubject("My PhoneManager Experience")
                mail.setToRecipients(["ligaili1217@163.com"]) // 收件人地址
                let body = String(format: "\n\n%@. iOS %@.%@\n%@", UIDevice.current.detailedModel,UIDevice.current.systemVersion,UIDevice.current.version(),UIDevice.current.identifierForVendor?.uuidString ?? "")
                mail.setMessageBody(body, isHTML: false)
                self.present(mail, animated: true, completion: nil)
            } else {
                print("无法发送邮件")
                PMAlert(title: nil, messsage: "Unable to send email", action: ["Ok"])
            }
        }
    }
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: (any Error)?) {
        controller.dismiss(animated: true)
    }
    
}

extension UIDevice {
    var detailedModel: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        return machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
    }
    
    func version() -> String {
        let infoDictionary = Bundle.main.infoDictionary
        let appVersion = infoDictionary?["CFBundleShortVersionString"] as? String ?? ""  // 版本号
        let buildNumber = infoDictionary?["CFBundleVersion"] as? String ?? "" // 构建号
        return String(format: "App version:%@(%@)",appVersion ,buildNumber)
    }
    
}
