//
//  YHSearchInfomationVC.swift
//  galaxy
//
//  Created by edy on 2024/4/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AVFoundation
import AVKit

//  搜索文字集合本地存储key
let searchInfoHistoryKey = "searchInfoHistoryKey"
//  最近一条有效搜索本地存储key
let kLatestValidSearchKey = "kLatestValidSearchKey"

// 本地是否有搜索记录
func isHaveLocalSearchRecords() -> Bool {
    if let arr = UserDefaults.standard.array(forKey: searchInfoHistoryKey) as? [String], arr.count > 0 {
        return true
    }
    return false
}

// 获取最新有效搜索记录
func getLatestValidSearchWord() -> String {
    if let text = UserDefaults.standard.string(forKey: kLatestValidSearchKey), !text.isEmpty {
        return text
    }
    return ""
}

class YHSearchInfomationVC: YHBaseViewController {

    static let searchHistoryMaxCount = 10
    private var searchStr = ""
    var searchPlaceHolder = ""
    var items: [YHHomeListModel] = []
    
    lazy var viewModel: YHHomePageViewModel = {
        let viewModel = YHHomePageViewModel()
        return viewModel
    }()
    
    lazy var homeViewModel: YHHomeWebViewModel = {
        let viewModel = YHHomeWebViewModel()
        return viewModel
    }()
    
    lazy var navBar: UIView = {
        let bar = UIView()
        let backBtn = UIButton()
        backBtn.setImage(UIImage(named: "back_icon"), for: .normal)
        backBtn.addTarget(self, action: #selector(didBackBtnClicked), for: .touchUpInside)
        backBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        bar.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.width.height.equalTo(21)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(16)
        }
        return bar
    }()
    
    lazy var searchBar: YHSearchInfoBar = {
        let bar = YHSearchInfoBar(frame: CGRect(x: 20, y: k_Height_NavigationtBarAndStatuBar+8.0, width: KScreenWidth-40, height: 36.0))
        bar.placeHolder = self.searchPlaceHolder
        bar.searchBlock = {
            [weak self] _ in
            guard let self = self else { return }
            searchStr = self.searchBar.textField.text ?? ""
            searchStr = searchStr.trimmingCharacters(in: .whitespaces)

            if isEmptyString(searchStr) {
                searchStr = searchPlaceHolder
                self.searchBar.textField.text = searchPlaceHolder
            }
            searchText()
            if searchStr.count > 0 {
                self.saveSearchHistory(searchStr)
            }
        }
        bar.textChange = {
            [weak self] text in
            guard let self = self else { return }
            if isEmptyString(text) {
                searchHistoryView.isHidden = false
                searchHistoryView.updateDataSource(self.getSearchHistoryList())
                items.removeAll()
                self.tableView.reloadData()
            }
        }
        return bar
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.estimatedSectionHeaderHeight = 0.1
        tableView.estimatedSectionFooterHeight = 20.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .white
        tableView.backgroundView = emptyDataTipsView
        tableView.register(YHSearchInfoCell.self, forCellReuseIdentifier: YHSearchInfoCell.cellReuseIdentifier)
        tableView.es.addYHPullToRefresh {
            self.loadFirstData()
        }
        tableView.es.addInfiniteScrolling {
            self.loadMoreData()
        }
        return tableView
    }()
    
    lazy var searchHistoryView: YHSearchInfoHistoryView = {
        let view = YHSearchInfoHistoryView(frame: CGRect(x: 0, y: searchBar.frame.maxY+8, width: KScreenWidth, height: KScreenHeight-searchBar.frame.maxY-8))
        view.updateDataSource(self.getSearchHistoryList())
        view.selectBlock = {
            [weak self] text in
            guard let self = self else { return }
            self.searchHistoryView.isHidden = true
            self.searchBar.textField.text = text
            self.searchStr = text
            searchText()
            self.saveSearchHistory(text)
        }
        view.deleteBlock = {
            [weak self] in
            guard let self = self else { return }
            self.view.endEditing(true)
            let arr = self.getSearchHistoryList()
            if arr.count <= 0 {
                YHHUD.flash(message: "暂无搜索记录~")
                return
            }
            self.showDeleteHistoryAlertView()
        }
        return view
    }()
    
    lazy var emptyDataTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("无搜索结果", kEmptySearchBgName)
        view.topMargin = 204
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
    }
    
    func setupUI() {
        
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        
        view.addSubview(navBar)
        view.addSubview(searchBar)
        view.addSubview(tableView)
        view.addSubview(searchHistoryView)
        
        navBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_StatusBar)
            make.height.equalTo(k_Height_NavContentBar)
        }
        searchBar.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar+8.0)
            make.height.equalTo(36.0)
        }
        
        searchHistoryView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(searchBar.snp.bottom).offset(20)
            make.bottom.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(searchBar.snp.bottom).offset(8+20)
            make.bottom.equalToSuperview()
        }
    }
    
    func showDeleteHistoryAlertView() {
        YHCommonAlertView.show("", "确认删除全部历史搜索记录？", "取消", "确认") {
            
        } callBack: {
            self.deleteAllSearchHistory()
            self.searchHistoryView.updateDataSource([])
        }
    }
    
    func searchText() {
        self.tableView.scrollToTop()
        YHHUD.show(.progress(message: "搜索中..."))
        viewModel.searchArticleList(self.searchStr, isFirstPage: true) {
            [weak self] _, _ in
            YHHUD.hide()
            guard let self = self else { return }
            
            items.removeAll()
            if let arr = self.viewModel.arrHomeNewsData {
                items.append(contentsOf: arr)
            }
            
            if items.count > 0, !self.searchStr.isEmpty {
                self.saveLatestValidSearchKewWord(self.searchStr)
            }
            
            emptyDataTipsView.isHidden = (items.count > 0)
            searchHistoryView.isHidden = true
            self.tableView.reloadData()
            tableView.es.stopPullToRefresh()
            // 只有一页的时候不展示没有更多数据了
            if self.viewModel.totalCount < self.viewModel.searchPageSize { // 不足一页
                tableView.footer?.isHidden = true
            } else {
                tableView.footer?.isHidden = false
                if self.viewModel.hasMoreForHomeNews == false {
                    tableView.es.noticeNoMoreData()
                }
            }
        }
    }
    
    func loadMoreData() {
        viewModel.searchArticleList(self.searchStr, isFirstPage: false) {
            [weak self] _, _ in
            guard let self = self else { return }
            
            items.removeAll()
            if let arr = self.viewModel.arrHomeNewsData {
                items.append(contentsOf: arr)
            }
            emptyDataTipsView.isHidden = (items.count > 0)
            searchHistoryView.isHidden = true
            self.tableView.reloadData()
            tableView.es.stopLoadingMore()
            // 只有一页的时候不展示没有更多数据了
            if self.viewModel.totalCount < self.viewModel.searchPageSize { // 不足一页
                tableView.footer?.isHidden = true
            } else {
                tableView.footer?.isHidden = false
                if self.viewModel.hasMoreForHomeNews == false {
                    tableView.es.noticeNoMoreData()
                }
            }
        }
    }
    
    func loadFirstData() {
        
        viewModel.searchArticleList(self.searchStr, isFirstPage: true) {
            [weak self] _, _ in
            guard let self = self else { return }
            
            items.removeAll()
            if let arr = self.viewModel.arrHomeNewsData {
                items.append(contentsOf: arr)
            }
            emptyDataTipsView.isHidden = (items.count > 0)
            searchHistoryView.isHidden = true
            self.tableView.reloadData()
//            DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute: {
            self.tableView.es.stopPullToRefresh()
//            })
            // 只有一页的时候不展示没有更多数据了
            if self.viewModel.totalCount < self.viewModel.searchPageSize { // 不足一页
                tableView.footer?.isHidden = true
            } else {
                tableView.footer?.isHidden = false
                if self.viewModel.hasMoreForHomeNews == false {
                    tableView.es.noticeNoMoreData()
                }
            }
        }
    }
    
    func getSearchHistoryList() -> [String] {
        if let arr = UserDefaults.standard.array(forKey: searchInfoHistoryKey) as? [String] {
            return arr
        }
        return []
    }
    
    func deleteAllSearchHistory() {
        UserDefaults.standard.set([], forKey: searchInfoHistoryKey)
        UserDefaults.standard.set("", forKey: kLatestValidSearchKey)
        UserDefaults.standard.synchronize()
        
    }
    
    func saveSearchHistory(_ text: String) {
        
        if isEmptyString(text) { return }
        
        var arr = getSearchHistoryList()
        // 去除两端的空格
        let targetText = text.trimmingCharacters(in: .whitespaces)
        
        // 查找历史记录中是否有相同记录
        var targetIndex = -1
        for (index, history) in arr.enumerated() {
            if history == targetText {
                targetIndex = index
                break
            }
        }
        // 去除相同记录
        if 0 <= targetIndex && targetIndex < arr.count {
            arr.remove(at: targetIndex)
        }
        
        // 将最近记录放在第一位
        if arr.count < Self.searchHistoryMaxCount {
            arr.insert(targetText, at: 0)
        } else {
            arr.insert(targetText, at: 0)
            arr.removeLast()
        }
        UserDefaults.standard.set(arr, forKey: searchInfoHistoryKey)
        UserDefaults.standard.synchronize()
    }
    
    @objc func didBackBtnClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if items.count == 0 {
            searchBar.textField.becomeFirstResponder()
        }
    }
    
    func saveLatestValidSearchKewWord(_ keyWord: String) {
        UserDefaults.standard.set(keyWord, forKey: kLatestValidSearchKey)
        UserDefaults.standard.synchronize()
    }
}

extension YHSearchInfomationVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHSearchInfoCell.cellReuseIdentifier, for: indexPath) as? YHSearchInfoCell else { return UITableViewCell() }
        
        if 0 <= indexPath.section && indexPath.section < items.count {
            let item = items[indexPath.section]
            cell.updateModel(item)
            cell.renderHighLightText(searchStr)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        if 0 <= indexPath.section && indexPath.section < items.count {
            let model = items[indexPath.section]
            if model.type == 1 { // 视频
                if !model.media_url.isEmpty, let url = URL(string: model.media_url) {
                    let vc = YHVideoPlayerVC()
                    if !model.media_transcode_url.isEmpty {
                        vc.url = model.media_transcode_url
                    } else {
                        vc.url = model.media_url
                    }
                    vc.id = model.id
                    self.navigationController?.pushViewController(vc)
                }
                return
            }
            
            // 非视频类型
            let vc = YHHomeWebViewController()
            vc.url = YHBaseUrlManager.shared.curH5URL() + "articleDetail.html" + "?id=\(model.id)"
            vc.id = model.id
            print("URL: \(vc.url)")
            self.navigationController?.pushViewController(vc)
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 20.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return UIView()
    }
}
