//
//  EmailContentView.swift
//  PhoneManager
//
//  Created by edy on 2025/5/9.
//

import UIKit
import MJRefresh

class EmailContentView: UIView {
    
    var parent:UIViewController?
    var callblock:((Bool)->Void) = { show in}
    
    private func setup() -> Void {
        topItem.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.snp.top).offset(0)
            make.height.equalTo(60)
        }
        topLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(15)
            make.top.equalTo(topItem.snp.bottom)
        }
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(botAction.snp.top)
            make.top.equalTo(topLabel.snp.bottom).offset(15)
        }
        botAction.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(52 + (cWindow?.safeAreaInsets.bottom ?? 0) + 24 )
        }
    }
    
    func beginLoading() -> Void {
        self.tableView.mj_header?.beginRefreshing()
    }
    
    func endLoading() -> Void {
        self.tableView.mj_header?.endRefreshing()
    }
    
    convenience init( _ parent:UIViewController) {
        self.init(frame: CGRect())
        self.parent = parent
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    private lazy var topLabel: UILabel = {
        let headerT = UILabel()
        headerT.text = "Cleans the mails in the categories you choose,according to the filters you applied."
        headerT.numberOfLines = 0
        headerT.font = UIFont.systemFont(ofSize: 14)
        headerT.textColor = UIColor(hex: "#333333")
        addSubview(headerT)
        return headerT
    }()
    
    private lazy var topItem: EmailCleanTopView = {
        let item = EmailCleanTopView()
        addSubview(item)
        item.callblock = { [weak self] in
            guard let self = self else { return }
            let vc = EmailFilterController()
            UIViewController.topMostViewController()?.navigationController?.pushViewController(vc, animated: true)
        }
        return item
    }()
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRectZero, style: .plain)
        tab.delegate = self;
        tab.dataSource = self
        tab.separatorStyle = .none
        tab.separatorInset = UIEdgeInsets()
        tab.rowHeight = 74 + 12
        tab.sectionHeaderHeight = 40 + 12
        tab.mj_header = mj_header
        tab.register(UINib(nibName: EmailContentTabCell.id, bundle: nil), forCellReuseIdentifier: EmailContentTabCell.id)
        if #available(iOS 15.0, *) {
            tab.sectionHeaderTopPadding = 0
        }
        addSubview(tab)
        return tab
    }()
    
    @objc func refresh() -> Void {
        self.tableView.reloadData()
        EmailFilterManager.share.SelectEmailSet = (0..<5).map { _ in NSMutableSet() }
        PMEmailManager.shareManager.fetchEmails { [weak self] in
            self?.endLoading()
            self?.datasource = PMEmailManager.shareManager.allMessage
        }
    }
    
    private lazy var botAction: EmailContentBottonAction = {
        let bot = EmailContentBottonAction(state: .EmailGroup)
        bot.clipsToBounds = false
        addSubview(bot)
        bot.numberMails = 0
        bot.callblock = { [weak self] in
            guard let self = self else { return }
            self.callblock(true)
            let alert = EmailContentDelAlert(state: .group)
            alert.callblock = { idx in
                if idx == 1 {
                    self.deleteEmail()
                }
                self.callblock(false)
            }
            alert.show()
        }
        return bot
    }()
    
    var datasource:[EmailDetailModel] = PMEmailManager.shareManager.allMessage {
        didSet {
            DispatchQueue.main.async {
                self.tableView.reloadData()
                self.Total()
            }
        }
    }
    
    private lazy var mj_header: MJRefreshNormalHeader = {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refresh))
        return header
    }()
    
}


extension EmailContentView :UITableViewDelegate,UITableViewDataSource{
    
    private func deleteEmail() -> Void {
        var num = 0
        for set in EmailFilterManager.share.SelectEmailSet {
            num += set.count
        }
        let callblock = {[weak self] in
            PMLoadingHUD.share.show()
            PMEmailManager.shareManager.deleteEmail { success in
                guard let self = self else { return }
                PMLoadingHUD.share.disMiss()
                if success {
                    self.datasource = PMEmailManager.shareManager.allMessage
                    self.showDeleteSuccess(fileCount: num, fileSize: 0)
                    self.Total()
                }
            }
        }
        if IAPManager.share.isSubscribed == false {
            // 弹出内购页面
            HomePayViewController.show {
                callblock()
            }
        }else {
            callblock()
        }
    }
    
    // 删除成功页面
    func showDeleteSuccess(fileCount:Int,fileSize:Int64){
        DispatchQueue.main.async {
            let vc = DelSuccessViewController()
            vc.type = .email
            vc.delType = fileCount > 1 ? "photos" : "photo"
            vc.fileSzie = fileSize
            vc.fileCount = fileCount
            vc.modalPresentationStyle = .fullScreen
            UIViewController.topMostViewController()?.present(vc, animated: true)
        }
    }
    
    // 广告
    func popAdverTisement(){
      //  AdvManager.shared.showInterstitialAd(vc: UIViewController.topMostViewController() ?? UIViewController())
    }
    
    private func Total() -> Void {
        var num = 0
        for set in EmailFilterManager.share.SelectEmailSet {
            num += set.count
        }
        self.botAction.numberMails = num
    }
    
    private func selectAll(_ indexPath:IndexPath) -> Void {
        let set = EmailFilterManager.share.SelectEmailSet[indexPath.row]
        let data = datasource[indexPath.row]
        if set.count == data.child.count {
            set.removeAllObjects()
        }else{
            for i in 0..<data.child.count {
                set.add(i)
            }
        }
        EmailFilterManager.share.SelectEmailSet[indexPath.row] = set
        Total()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datasource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datasource[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: EmailContentTabCell.id, for: indexPath) as! EmailContentTabCell
        cell.selectionStyle = .none
        let set = EmailFilterManager.share.SelectEmailSet[indexPath.row]
        cell.selectBtn.isSelected = (set.count == data.child.count && set.count > 0)
        cell.groupName.text = data.label
        if self.mj_header.isRefreshing {
            cell.groupNumbers.text = "Scanning..."
            cell.loaingView.isHidden = false
            cell.loaingView.startAnimating()
            cell.info.isHidden = true
        }else{
            cell.groupNumbers.text = "\(data.child.count) Emails" + (set.count > 0 ? " · \(set.count) Selected" : "")
            cell.loaingView.isHidden = true
            cell.info.isHidden = false
        }
        cell.callblock = {[weak self] in
            guard let self = self else { return }
            self.vibrate()
            self.selectAll(indexPath)
            tableView.reloadData()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = datasource[indexPath.row].child
        if data.count > 0 {
            let vc = EmailCleanListController()
            vc.titleLabel.text = datasource[indexPath.row].label
            vc.datasoure = data
            vc.indexPath = indexPath
            parent?.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}
