//
//  ServiceKnowledgeListVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/10/12.
//

import Foundation

class ServiceKnowledgeListVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var searchKey = ""      //查询关键字(搜索时传入的关键字)
    var pageNumber = 1      //当前页
    var pageSize = 20        //每页大小
    var pageCount = 0
    
    var models:[M_Knowledge] = []
    
    var knowledgeTypeId = ""       //分类ID
    var typeName = ""       //分类名称
    
    var orderId = ""
}

extension ServiceKnowledgeListVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        for (idx, item) in models.enumerated(){
            do{
                let rowCell = TCFormCellModel<ServiceKnowledgeListCell>.init(data: (item.title, item.content, item.createTime), frameh: UITableView.automaticDimension, didSelect:  {[weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.didSelect(idx)
                })
                newForms.append(rowCell)
            }
            newForms += makeLineCellForm(height: 8)
        }
        
        forms = newForms
        reloadData?()
    }
    
    func makeLineCellForm(leftW:CGFloat = 0, rightW:CGFloat = 0, bgColor:UIColor = .clear, backGroundColor:UIColor = .clear, corners:(CGFloat, CACornerMask) = (0, []), height:CGFloat = 8, idx:Int = -99) -> [TCCellBaseProtocol] {
        let uiConfigModel = TCFormCellConfigModel.defaultModel()
            .bgColor(backGroundColor)
            .cornerMask(corners.1)
            .cornerRadius(corners.0)
        let rowCell = TCFormCellModel<TCLineCell>.init(data: (leftW, rightW, bgColor), config: uiConfigModel, frameh: height, didSelect:  {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.didSelect(idx)
        })
        return [rowCell]
    }
    
    func didSelect(_ idx:Int) {
        guard idx >= 0 else {
            return
        }
        let m = models[idx]
        let urlStr = "\(TWOCNetwork.shareNetManager().baseURL)/h5/knowledgeDetail.html?id=\(m.id)&userName=\(MyInfo.shareInstance().userName.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!)&token=\(MyInfo.shareInstance().token)"
        R_Web.push(.http(urlStr), title: "知识详情".languageString())
    }
}

extension ServiceKnowledgeListVm {
    func requestData() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["knowledgeTypeId"] = knowledgeTypeId
        par["searchKey"] = searchKey
        par["pageNumber"] = pageNumber
        par["pageSize"] = pageSize

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/support/getKnowledgeList",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                let knowledgeList = data.arrayValue(forKey: "knowledgeList").compactMap({M_Knowledge($0)})
                if weakSelf.pageNumber == 1 {
                    if knowledgeList.isEmpty {
                        hud_info("没有知识库数据".languageString())
                    }
                    weakSelf.models = knowledgeList
                }else{
                    weakSelf.models += knowledgeList
                }
                weakSelf.makeForms()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
}

class M_Knowledge: NSObject {
    var id = ""       //知识库ID
    var title = ""       //标题
    var createTime = ""       //创建时间
    var content = ""       //内容

    init(_ data:[String:Any] = [:]) {
        id = data.stringValue(forKey: "id")
        title = data.stringValue(forKey: "title")
        createTime = data.stringValue(forKey: "createTime")
        content = data.stringValue(forKey: "content")
    }
}
