//
//  YHDynamicViewModel.swift
//  galaxy
//
//  Created by Dufet on 2025/9/30.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHDynamicViewModel: YHBaseViewModel {
    
    var curPageIndex: Int = 1
    var pageSize = 10
    var totalCount: Int = 0
    var dynamicArr: [YHDynamicItem] = []
    var hasMore: Bool = true
    var preloadItemIndex: Int = 25

    func getList(_ firstFlag: Bool, sourceType: Int, other_user_id: String = "", callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        var params: [String: Any] = ["page": curPageIndex]
        if firstFlag {
            curPageIndex = 1
            params = ["page": curPageIndex]

        } else {
            params = ["page": curPageIndex + 1]
        }
        
        if !other_user_id.isEmpty {
            params["other_user_id"] = other_user_id
        }
        
        //  source_type 0---全部用户评论列表 1-个人评论列表 2-他人评论列表
        let other_params = ["page_size": pageSize,
                            "source_type": sourceType]
        
        params = params.merging(other_params) { (_, new) in new }
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Dynamic.list
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHDynamicListModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }

                if firstFlag {
                    self.totalCount = result.total
                    self.dynamicArr.removeAll()
                    self.dynamicArr = result.list

                } else {
                    self.dynamicArr.append(contentsOf: result.list)
                    curPageIndex += 1
                }

                if self.dynamicArr.count >= self.totalCount {
                    self.hasMore = false
                } else {
                    self.hasMore = true
                }

                callBackBlock(true, nil)

            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
}

// MARK: - 点赞功能扩展
extension YHDynamicViewModel {
    
    /// 点赞/取消点赞动态
    /// - Parameters:
    ///   - id: 动态ID
    ///   - type: 操作类型 1收藏2点赞
    ///   - operation: 操作类型 1增加 2取消
    ///   - callBackBlock: 回调
    func getLike(_ id: String, _ operation: Int, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["id": id, "operation": operation, "type": 2]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Dynamic.like
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            if json.code == 200 {
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
}

// MARK: - 发布动态
extension YHDynamicViewModel {
    
    /// 发布动态
    /// - Parameters:
    ///   - title: 标题
    ///   - content: 内容
    ///   - resources：图片/视频数组
    ///   - callBackBlock: 回调
    func publishCircle(_ id: String?, _ title: String, _ content: String, resources: [YHResourceURLs], callBackBlock: @escaping (_ success: String?, _ error: YHErrorModel?) -> Void) {
        var params: [String: Any] = ["title": title, "content": content]
        params["id"] = id
        params["resource_urls"] = resources.map { resource in
            [
                "name": resource.name,
                "url": resource.url,
                "type": resource.type,
                "width": resource.width,
                "height": resource.height
            ] as [String: Any]
        }
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Dynamic.publishCircle
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            if json.code == 200 {
                callBackBlock(json.data?.peel as? String, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(nil, error)
            }
        } failBlock: { err in
            callBackBlock(nil, err)
        }
    }
}
