//
//  MenuVC.swift
//  SwiftProject
//
//  Created by aaa on 2024/4/12.
//

import Foundation
import UIKit
import Firebase
import FirebaseRemoteConfig
import Kingfisher
class MenuVC: BaseController,UITableViewDelegate,UITableViewDataSource {
    
    static let kMenuVCCell_identifier = "kMenuVCCell_identifier"
    var dataSource:[[[String:Any]]]{
        get {
            let tempDic = getDatasourceThreeSection()
            if tempDic.count > 0 {
                return [getDatasourceOneSection(), getDatasourceTwoSection(), getDatasourceThreeSection()]
            }
            else {
                return [getDatasourceOneSection(), getDatasourceTwoSection()]
            }
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configureUI()
//        let remoteConfig = FirebaseRemoteConfig.RemoteConfig.remoteConfig()
//        print("..\(remoteConfig).")
//        self.configureData()
//        {
//            "default":[{"icon":"xxxxxx","title":"wecht","url":""},
//                       {"icon":"xxxxxx","title":"wecht","url":""}
//            ],
//            "zh":[],
//            "en":[]
//            
//        }
//        UIApplication.openURL("tel://")
//        "image:d"
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        if UserInfo.sharedInstance.isMemberShip {//统计
//            
//            Analytics.logEvent("iap_isvip_pv", parameters: nil)
//        }
//        else {
//            Analytics.logEvent("iap_unvip_pv", parameters: nil)
//        }
    }
    
    func configureUI() {
        self.navLine?.isHidden = true
        self.setLeftOneBtnImg(imgStr: "menuvc_backbtn")
//        self.leftBtn1?.addTarget(self, action: #selector(dismissVC(sender: )), for: .touchUpInside)
        self.view.backgroundColor = UIColor(r: 6, g: 5, b: 7, a: 1)
        let topView = topView()
        self.view.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(113)
            make.left.right.equalToSuperview()
            make.height.equalTo(162)
        }
        //创建一个底部View（内置一个tableView）
        let bottomView = buttomView()
        self.view.addSubview(bottomView)
        //覆盖主视图下半部分
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
            make.top.equalTo(topView.snp.bottom).offset(0)
        }
    }
    
    func topView() -> UIView {
        let bgView = UIView()
        let imageView = UIImageView()
        bgView.addSubview(imageView)
        imageView.image = UIImage(named: "AppIcon")
        imageView.layer.cornerRadius = 10
        imageView.layer.masksToBounds = true
        imageView.snp.makeConstraints { make in
            make.width.height.equalTo(86)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(0)
        }
        
        let titleLabel = UILabel()
        bgView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(imageView.snp.bottom).offset(8)
        }
        titleLabel.text = "VPCamera"
        titleLabel.textColor = .white
        titleLabel.font = UIFont(name: "PingFangSC-Medium", size: 16)
        
        let verLabel = UILabel()
        bgView.addSubview(verLabel)
        verLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
        }
        verLabel.textColor = UIColor(red: 0.78, green: 0.78, blue: 0.8, alpha: 1)
        verLabel.font = UIFont(name: "PingFangSC-Medium", size: 14)
        verLabel.text = ZZHHelper.getVersion()
        return bgView
    }
    
    func buttomView() -> UIView {
        let bgView = UIView()
        //创建tableView
        let tableView = UITableView(frame: .zero, style: .insetGrouped)
        //注册cell
        tableView.register(MenuVCCell.classForCoder(), forCellReuseIdentifier: MenuVC.kMenuVCCell_identifier)
        //将tableView添加入bgView
        bgView.addSubview(tableView)
        //tableView全覆盖
        tableView.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(0)
            make.right.equalToSuperview().offset(0)
        }
        //实现tableView数据源和代理
        tableView.dataSource = self
        tableView.delegate = self
        //颜色为透明
        tableView.backgroundColor = .clear
        return bgView
    }
    
    @objc func dismissVC(sender:UIButton) {
        self.dismiss(animated: true)
    }
    //数据源第一组（Share VPCamera And Feedback）,key值为image、title
    private func getDatasourceOneSection () -> [[String:Any]] {
        return [
            ["image":UIImage(named: "menuvc_sharevpcamera")!, "title":NSLocalizedString("v1.5_share vpcamera", comment: "")],
            ["image":UIImage(named: "menuvc_feedback")!, "title":NSLocalizedString("v1.5_feedback", comment: "")]
        ]
    }
    //数据源第二组（Privacy Policy And Terms of Service）,key值为image、title
    private func getDatasourceTwoSection () -> [[String:Any]] {
        return [
            ["image":UIImage(named: "menuvc_privacy")!, "title":NSLocalizedString("v1.5_privacy policy", comment: "")],
            ["image":UIImage(named: "menuvc_terms")!, "title":NSLocalizedString("v1.5_terms of service", comment: "")]
        ]
    }
    //数据源第三组，网络获取，key值为 image、title、url
    private func getDatasourceThreeSection () -> [[String:Any]] {
        let config = FirebaseRemoteConfig.RemoteConfig.remoteConfig()
        let menuParams = config.configValue(forKey: "menuParams")
        guard let dicInfo = menuParams.jsonValue as? [String:Any] else {
            return []
        }
        guard let contactConfig = dicInfo["contactConfig"] as? [String:Any] else {
            return []
        }
        
        
        var localConfig = contactConfig[NSLocalizedString("v1.5_menu_lang", comment: "")]  as? [[String:Any]]
        if localConfig == nil {
            localConfig = contactConfig["default"] as? [[String:Any]]
        }
        var dataDictionary:[[String:Any]] = []
        localConfig?.forEach({ item in
            
            let iconUrl = item["icon"] as! String
            let title = item["title"] as! String
            let jumpUrl = item["url"] as! String
            let image:UIImageView = UIImageView()
            let url = URL(string: iconUrl)
            dataDictionary.append(["image":url!, "title":item["title"] as! String, "url":item["url"] as! String])
        })
        
        return dataDictionary
    }
    
    //MARK: - TableViewDelegate and DataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MenuVC.kMenuVCCell_identifier, for: indexPath) as! MenuVCCell
        cell.data = dataSource[indexPath.section][indexPath.row]
        if dataSource[indexPath.section].count == 1 {
            //这一组只有一行
            cell.radiusType = .all
        }else {
            switch indexPath.row {
            case 0:
                cell.radiusType = .top
            case dataSource[indexPath.section].count - 1:
                cell.radiusType = .bottom
            default:
                cell.radiusType = ._none
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 52
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionView:UIView = .init(frame: .init(x: 0, y: 0, width: tableView.bounds.width, height: 54))
        sectionView.backgroundColor = .clear
        //添加一个Label
        let titleLabel = UILabel()
        titleLabel.textColor = .init(r: 255, g: 255, b: 255, a: 0.5)
        titleLabel.text = section == 2 ? NSLocalizedString("v1.5_contact us", comment: ""):""
        titleLabel.font = .systemFont(ofSize: 15, weight: .medium)
        sectionView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-10)
            make.left.equalToSuperview()
        }
        titleLabel.isHidden = !(section == 2)
        return sectionView
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 0
        case dataSource[section].count - 1:
            return 54
        default:
            return 18
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.section {
        case 0://第一组
            switch indexPath.row {
            case 0://Share VPCamera,执行分享
                //设置分享文本
                let text = "VPCamera"
                //分享图片icon
                let image = UIImage(named: "AppIcon")
                //设置分享路径
                let url = URL(string: "https://apps.apple.com/app/id6479474994")
                let activityItems = [text,image as Any,url as Any]
                //弹出分享框
                let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities:nil)
                present(activityViewController, animated: true, completion: nil)
                //分享结束后的回调
                activityViewController.completionWithItemsHandler = { [weak self] ( activityType, isCompleted, returnedItems, error) -> Void in
                    print(isCompleted ? "Share Success":"Share Failure")
                }
            default://反馈
                let feedVC = FeedBackVC()
                navigationController?.pushViewController(feedVC, animated: true)
            }
        case 1://第二组
            switch indexPath.row {
            case 0://Privacy Policy，执行隐私政策
                let vc:CCWebController = CCWebController()
                vc.titleValue =  NSLocalizedString("隐私政策", comment: "")
                let sizeUrl = NSLocalizedString("siteUrl", comment: "隐私政策url")
                vc.urlString = sizeUrl
                self.navigationController?.pushViewController(vc, animated: true)
                break
            default://Terms of Service， 用户协议
                let vc:CCWebController = CCWebController()
                vc.titleValue =  NSLocalizedString("用户协议", comment: "")
                let sizeUrl = NSLocalizedString("userSiteUrl", comment: "用户协议url")
                vc.urlString = sizeUrl
                self.navigationController?.pushViewController(vc, animated: true)
                break
            }
        default://跳转组
            guard let url = URL(string: dataSource[indexPath.section][indexPath.row]["url"] as! String) else {
                return
            }
            UIApplication.shared.open(url)
        }
    }
}
