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

import UIKit

class EmailCleanListView: UIView {
    
    var callblock:((Bool)->Void) = { select in }
    var callBlur:((Bool)->Void) = { show in }
    var indexPath:IndexPath?
    
    private func setup() -> Void {
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(botAction.snp.top)
        }
        botAction.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(52 + (cWindow?.safeAreaInsets.bottom ?? 0) + 24 )
        }
    }
    
    var datasource:[EmailMessageModel] = [] {
        didSet {
            botAction.numberMails = EmailFilterManager.share.SelectEmailSet[indexPath?.row ?? 0].count
            self.tableView.reloadData()
        }
    }
    
    func changeSelectAll(_ select:Bool) -> Void {
        let set = EmailFilterManager.share.SelectEmailSet[indexPath?.row ?? 0]
        if select {
            for i in 0..<datasource.count {
                set.add(i)
            }
        }else{
            set.removeAllObjects()
        }
        EmailFilterManager.share.SelectEmailSet[indexPath?.row ?? 0] = set
        botAction.numberMails = set.count
        tableView.reloadData()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    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 = 101
        tab.sectionHeaderHeight = 10
        tab.register(UINib(nibName: EmailCleanListViewCell.id, bundle: nil), forCellReuseIdentifier: EmailCleanListViewCell.id)
        if #available(iOS 15.0, *) {
            tab.sectionHeaderTopPadding = 0
        } else {
        }
        addSubview(tab)
        return tab
    }()
    
    private lazy var botAction: EmailContentBottonAction = {
        let bot = EmailContentBottonAction(state: .EmailList)
        bot.clipsToBounds = false
        addSubview(bot)
        bot.numberMails = EmailFilterManager.share.SelectEmailSet[indexPath?.row ?? 0].count
        bot.callblock = { [weak self] in
            guard let self = self else { return }
            self.callBlur(true)
            let alert = EmailContentDelAlert(state: .list)
            alert.callblock = { idx in
                if idx == 1 {
                    self.deleteEmail()
                }
                self.callBlur(false)
            }
            alert.show()
        }
        return bot
    }()
}

extension EmailCleanListView : UITableViewDataSource,UITableViewDelegate {
    
    private func deleteEmail() -> Void {
        
        let num = EmailFilterManager.share.SelectEmailSet[indexPath?.row ?? 0].count
        let callblock = {[weak self] in
            PMLoadingHUD.share.show()
            PMEmailManager.shareManager.deleteEmail(self?.indexPath?.row ?? 0) { sucess in
                guard let self = self else { return }
                PMLoadingHUD.share.disMiss()
                if sucess {
                    self.datasource = PMEmailManager.shareManager.allMessage[self.indexPath?.row ?? 0].child
                    self.botAction.numberMails = EmailFilterManager.share.SelectEmailSet[self.indexPath?.row ?? 0].count
                    self.tableView.reloadData()
                    self.showDeleteSuccess(fileCount: num, fileSize: 0)
                }
            }
        }
        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(),from: "email")
    }
    
    private func selectSet(_ indexPath:IndexPath) -> Void {
        let set = EmailFilterManager.share.SelectEmailSet[self.indexPath?.row ?? 0]
        if set.contains(indexPath.row) {
            set.remove(indexPath.row)
        }else{
            set.add(indexPath.row)
        }
        self.botAction.numberMails = set.count
        callblock(set.count == self.datasource.count)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datasource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: EmailCleanListViewCell.id, for: indexPath) as! EmailCleanListViewCell
        cell.selectionStyle = .none
        let data = datasource[indexPath.row]
        let send = data.payload?.headers?.from ?? " "
        cell.ListFirstL.text = (send.count > 0 ? send.substring(to:send.index(send.startIndex, offsetBy: 1)) : "")
        cell.groupName.text = send as String
        cell.EmailTimeL.text = data.payload?.headers?.date?.GetddMM()
        cell.descpText.text = data.payload?.headers?.subject
        cell.descpText1.text = data.payload?.body.plainText?.removeEscapeCharacters()
        let set = EmailFilterManager.share.SelectEmailSet[self.indexPath?.row ?? 0]
        cell.selectBtn.isSelected = set.contains(indexPath.row)
        
        Print("startttt = \(data.labelids)")
        if EmailFilterManager.share.FilterSet.start {
            cell.startInfo.isHidden = !((data.labelids?.contains("STARRED")) ?? false)
        }else{
            cell.startInfo.isHidden = true
        }
        
        cell.ListDot.isHidden = !((data.labelids?.contains("UNREAD")) ?? false)
        cell.callblock = {[weak self] in
            guard let self = self else { return }
            self.selectSet(indexPath)
            self.vibrate()
            tableView.reloadData()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detail = EmailListDetailController()
        detail.detail = datasource[indexPath.row]
        UIViewController.topMostViewController()?.navigationController?.pushViewController(detail, animated: true)
    }
    
}
