//
//  ServiceHomeVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/10/9.
//

import Foundation

class ServiceHomeVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var callback:(()->())?
    var didSelCallback:((M_OrderPartsInfo.Parts)->())?
    var model = M_ServiceHome()
    
    func makeForms(){
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 18)
        do {
            let rowCell = TCFormCellModel<ServiceHomeTopCell>.init(frameh: 96) {[weak self] _ in
                guard let weakSelf = self else { return }
                if weakSelf.model.onLineUrl.isEmpty {
                    hud_info("在线客服功能暂未开放".languageString())
                }else{
                    R_Web.push(.http(weakSelf.model.onLineUrl+"&token=\(MyInfo.shareInstance().token)"))
                }
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(height: 12)
        do {
            let rowCell = TCFormCellModel<ServiceHomeLibraryCell>.init(frameh: 88) { [weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    switch txt {
                    case "知识库":
                        R_ServiceKnowledgeList.router()
                        break
                    case "故障库":
                        R_ServiceFaultList.router()
                    default:
                        break
                    }
                }
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(height: 16)
        
        if !model.bulletinList.isEmpty {
            let total = isEnglish() ? " \(model.total) " : model.total
            newForms += makeTitleCellForm(titleStr: "通知公告".languageString(), statusStr: "\("查看全部".languageString())\(total)\("条".languageString())", corner: (8, [.topLeft, .topRight]), isShowArrow: true)
            for (i, item) in model.bulletinList.enumerated() {
                do {
                    let rowCell = TCFormCellModel<ServiceHomeNoticeCell>.init(data: (item.title, item.content, item.createTime, item.record != "0"), frameh: UITableView.automaticDimension, didSelect:  {[weak self] in
                        guard let weakSelf = self else { return }
                        if item.record == "0" {
                            weakSelf.readNotice(item.id)
                        }
//                        R_Web.push(.html(item.content), title: "详情")
                        let html5String = "<html>" +
                                "<head>" +
                                "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0,viewport-fit=cover\"/>" +
                                "<style>" +
                                "img {width: 100%;height: auto;}" +
                                "video {width: 100%;height: auto;}" +
                                "</style>" +
                                "</head>" +
                                "<body>" +
                        item.content +
                                "</body>" +
                                "</html>"
                        let web = Vc_Web()
                        web.title = "详情".languageString()
                        web.webType = .html(html5String)
    
                        CD.push(web)
                    })
                    newForms.append(rowCell)
                }
                if i < model.bulletinList.count - 1 {
                    newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, height: 8)
                }else{
                    newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]), height: 12)
                }
            }
        }
        
        forms = newForms
        callback?()
    }
    
    func makeLineCellForm(leftW:CGFloat = 0, rightW:CGFloat = 0, bgColor:UIColor = .clear, backGroundColor:UIColor = .clear, corners:(CGFloat, CACornerMask) = (0, []), height:CGFloat = 12) -> [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)
        return [rowCell]
    }
    
    func makeTitleCellForm(titleStr:String, statusStr:String = "", corner:(CGFloat, UIRectCorner) = (0,[]), isShowArrow:Bool = false, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailTitleCell>.init(data: (titleStr, statusStr), config: (corner, isShowArrow, false, Config.color.hex("9")), frameh: hh ?? UITableView.automaticDimension) { _ in
            R_ServiceNoticeList.router()
        }
        return [rowCell]
    }
}
extension ServiceHomeVm {
    func requestData() {
        var par:[String:Any] = [:]

        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/support/index",andParam: par)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                weakSelf.model = M_ServiceHome(data)
                weakSelf.makeForms()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
    
    func readNotice(_ id:String) {
        var par:[String:Any] = [:]
        par["bulletinId"] = id
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/support/bulletinRecord",andParam: par)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.requestData()
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
}






class M_ServiceHome: NSObject {
    var onLineUrl = ""            //在线客服跳转页面地址
    var bulletinList:[Bulletin] = []            //通知公告列表
    var total = ""        //公告总数

    init(_ data:[String:Any] = [:]) {
        onLineUrl = data.stringValue(forKey: "onLineUrl")
        bulletinList = data.arrayValue(forKey: "bulletinList").compactMap({Bulletin($0)})
        total = data.stringValue(forKey: "total")
    }
    
    struct Bulletin {
        var id = ""            //ID
        var title = ""            //标题
        var content = ""            //内容//富文本
        var createTime = ""            //创建时间
        var record = "0"           //是否已读,为0时为未读，为1时为已读
        init(_ data:[String:Any] = [:]) {
            id = data.stringValue(forKey: "id")
            title = data.stringValue(forKey: "title")
            content = data.stringValue(forKey: "content")
            createTime = data.stringValue(forKey: "createTime")
            record = data.stringValue(forKey: "record")
        }
    }
}
