//
//  SessionController+Adapter.swift
//  LegendTeam
//
//  Created by 梁博 on 20/12/21.
//

import Foundation
import UIKit

extension SessionController {
    func setupTableView() {
        tableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(tableView)
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.keyboardDismissMode = .onDrag
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        tableView.contentInset = UIEdgeInsets(top: 40, left: 0, bottom: 20, right: 0)// UIWindow.navBarTotalHeight
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.register(SessionAIHeadView.self, forCellReuseIdentifier: "SessionAIHeadView")
        tableView.setContentCompressionResistancePriority(UILayoutPriority(743), for: .vertical)
        
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cancelEditing))
        gestureRecognizer.numberOfTapsRequired = 1
        gestureRecognizer.cancelsTouchesInView = false
        tableView.addGestureRecognizer(gestureRecognizer)
        
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapPageBg(_:)))
        doubleTap.numberOfTapsRequired = 2   // 双击
        doubleTap.numberOfTouchesRequired = 1 // 单指
        tableView.addGestureRecognizer(doubleTap)
        
        tableView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(self.view)
            // Case 1:
            make.top.equalTo(sessionNavigationView.snp.bottom) // navigationView
            // Case 2:
//            make.height.equalTo(UIScreen.height * 0.4)
            make.bottom.equalTo(bottomViewsStackV.snp.top).offset(0)
        }
        
        let header = RefreshHeaderAnimator.init(refreshingBlock: {[weak self] in
            self?.loadMessages { _, _ in
                
            }
        })
        header.ignoredScrollViewContentInsetTop = tableView.contentInset.top
        tableView.mj_header = header
    
        tableView.alpha = 0
    }
    
    private func cellIn(tableView: UITableView, cellModel: SessionBaseModel) -> SessionCell {
        var cellID = cellModel.cellType.rawValue
        if String.realEmpty(str: cellID) {
            cellID = SessionCellType.text.rawValue
        }
        
        var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
        if cell != nil {
            return cell as! SessionCell
        } else {
            tableView.register(SessionCell.self, forCellReuseIdentifier: cellID)
            cell = tableView.dequeueReusableCell(withIdentifier: cellID)
            return cell as! SessionCell
        }
    }
    
    func updateTableViewContentLayout() {
        // 动态调整contentInset，使内容底部对齐
        adjustTableViewContentInset()
        
        DispatchQueue.main.async {[weak self] in
            self?.scrollToBottom(self?.tableView)
        }
    }
    
    func scrollToBottom(_ tableView: UITableView?, delay: CGFloat? = 0,  animated: Bool = false) {
        guard let table = tableView else{
            return
        }
        
        let delaySeconds = delay ?? 0
//        let y = max(table.contentSize.height - table.bounds.size.height, 0)
//        table.setContentOffset(CGPoint(x: 0, y: y), animated: animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + delaySeconds) {[weak self] in
            let count = self?.util.cellModels.count ?? 0
            if count > 0 {
                table.scrollToRow(at: IndexPath(row: count - 1, section: 1), at: .bottom, animated: animated)
                // Initial state
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                    if table.alpha == 0{
                        UIView.animate(withDuration: 0.35) {
                            table.alpha = 1
                        }
                    }
                }
            }
        }
        
    }
}

// MARK: - Reload

extension SessionController {
    /// 更新某些cell
    func update(indexs: [Int]?) {
        guard indexs != nil else {
            return
        }
        let indexPaths = self.indexPathsWith(indexs: indexs!)
        
        // 没有就不刷新
        if Array.realEmpty(array: indexPaths) {
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.tableView.reloadRows(at: indexPaths, with: .none)
        }
    }

    /// 插入某些cell
    func insert(indexs: [Int], animation: Bool, isOut: Bool, first:Bool = false) {
        guard indexs.count > 0 else {
            return
        }
        // 别人发的消息，且上滑了一定的距离才显示newMessage，需要早点计算
        let offset = self.tableView.contentSize.height - self.tableView.bounds.size.height - 80
        // 获取需要插入的indexPaths
        let indexPaths = self.indexPathsWith(indexs: indexs)
        let needReload = SessionUtilOC.shouldReload(whenInsert: indexPaths, tableView: self.tableView)
        if needReload || !animation {
            self.tableView.reloadData()
        } else {
            UIView.performWithoutAnimation {
                self.tableView.beginUpdates()
                self.tableView.insertRows(at: indexPaths, with: .none)
                self.tableView.endUpdates()
            }
        }
        // 插入第一条消息，不处理下面这个
        if first {
            return
        }
        if isOut {
            // 自己发的消息
            DispatchQueue.main.async {
                self.updateTableViewContentLayout()
            }
        } else {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                if offset > self.tableView.contentOffset.y {
//                    self.showNewMessages(show: true)
                } else {
                    DispatchQueue.main.async {
                        self.updateTableViewContentLayout()
                    }
                }
            }
        }
    }

    func loadMoreCell(indexs: [Int]?) {
        if Array.realEmpty(array: indexs) {
            return
        }
        
        var index = 0
        
        if (self.tableView.visibleCells.count > 0) {
            // 第一个一定是显示时间cell。所以要取第二个
            guard let cell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? SessionCell else {
                self.tableView.reloadData()
                return
            }
            if let model = cell.model {
                index = self.util.modelIndexWith(model: model) ?? 0
            }
        } else {
            self.tableView.reloadData()
            return;
        }
        if (index < 0) {
            index = 0;
        }
        
        self.tableView.reloadData()
        
        let count = self.tableView.numberOfRows(inSection: 0)
        if (index >= count && count > 0) {
            index = count - 1;
        }
        
        self.tableView.scrollToRow(at: IndexPath(row: index, section: 0), at: .top, animated: false)
    }
    
    /// 通过index获取indexPath
    func indexPathsWith(indexs: [Int]) -> [IndexPath] {
        var indexPaths = [IndexPath]()
        
        for index in indexs {
            let indexPath = IndexPath(row: index, section: 0)
            indexPaths.append(indexPath)
        }
        return indexPaths
    }
}

// MARK: - UITableViewDataSource

extension SessionController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            guard aiInfo != nil else{
                return 0
            }
            return 1
        }
        return self.util.cellModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "SessionAIHeadView", for: indexPath) as! SessionAIHeadView
            cell.refresh(self.aiInfo)
            return cell
        }
        let model = self.util.cellModels[indexPath.row]
        let cell = self.cellIn(tableView: tableView, cellModel: model)
        cell.delegate = self
        cell.bindCell(model: model)
        return cell
    }
}

// MARK: - UITableViewDelegate

extension SessionController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0{
            return UITableView.automaticDimension
        }
        
        let model = self.util.cellModels[indexPath.row]
        let cellHeight = model.cellHeight()
        return cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //...
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
        let height = scrollView.frame.size.height

        if offsetY > contentHeight - height + 40 {
            //print("松手时，滑到底部之外了")
            if isPullingToAIHomePage == false{
                CLTool.feedbackGenerator()
                AppRouter.goAIRoleHome(aiId: aiId)
                
                isPullingToAIHomePage = true
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {[weak self] in
                self?.isPullingToAIHomePage = false
            }
        } else if offsetY < 0 {
            //print("松手时，滑到顶部之外了")
        }
    }
    
    /// 动态调整tableView的contentInset，使内容底部对齐
    func adjustTableViewContentInset() {
        guard let tableView = self.tableView else { return }
        
        // 计算内容高度
        let contentHeight = tableView.contentSize.height
        let tableViewHeight = tableView.bounds.height
        
        // 如果内容高度小于tableView高度，调整top inset使内容底部对齐
        if contentHeight < tableViewHeight {
            let topInset = tableViewHeight - contentHeight
            tableView.contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: 20, right: 0)
        } else {
            // 内容高度超过tableView时，恢复原始top inset
            tableView.contentInset = UIEdgeInsets(top: 40, left: 0, bottom: 20, right: 0)
        }
        
        // 更新下拉刷新组件的ignoredScrollViewContentInsetTop
        if let header = tableView.mj_header as? RefreshHeaderAnimator {
            header.ignoredScrollViewContentInsetTop = tableView.contentInset.top
        }
    }
}



