//
//  OrderTransferVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/9.
//

import Foundation

class OrderTransferVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var orderId = ""
    var searchKey = ""      //查询关键字(搜索时传入的关键字)
    var pageNumber = 1      //当前页
    var pageSize = 10        //每页大小
    var pageCount = 0
    
    var models:[M_OrderTransfer] = []
    var selModel = M_OrderTransfer()
    
    var callBack:((Bool)->Void)?
}

extension OrderTransferVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        
        for (i,item) in models.enumerated(){
            newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
            do{
                let rowCell = TCFormCellModel<OrderHelperCell>.init(data: item,frameh: UITableView.automaticDimension, didSelect:  {[weak self] in
                    guard let weakSelf = self else { return }
                    for j in 0..<weakSelf.models.count {
                        if i == j {
                            weakSelf.models[j].isSelect = true
                            weakSelf.selModel = weakSelf.models[j]
                        }else{
                            weakSelf.models[j].isSelect = false
                        }
                    }
                    weakSelf.makeForms()
                })
                newForms.append(rowCell)
            }
        }
        newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 16)
        
        forms = newForms
        reloadData?()
    }
    
    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]
    }
}
extension OrderTransferVm {
    func requestData() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["searchKey"] = searchKey
        par["pageNumber"] = pageNumber
        par["pageSize"] = pageSize

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/getHelperSites",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
//            if let data = result["data"] as? [String:Any] {
//                if let list = data["helperlist"] as? [[String:Any]] {
//                    weakSelf.pageCount = list.count
//                    if weakSelf.pageNumber == 1 {
//                        weakSelf.models = list.compactMap({M_OrderTransfer($0)})
//                    }else{
//                        weakSelf.models += list.compactMap({M_OrderTransfer($0)})
//                    }
//                    weakSelf.makeForms()
//                }
//            }
            if let list = result["data"] as? [[String:Any]] {
                weakSelf.pageCount = list.count
                if weakSelf.pageNumber == 1 {
                    weakSelf.models = list.compactMap({M_OrderTransfer($0)})
                }else{
                    weakSelf.models += list.compactMap({M_OrderTransfer($0)})
                }
                weakSelf.makeForms()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
    
    func transferOrder() {
        guard !selModel.id.isEmpty else {
            CD.visibleVC?.promptInformation("请选择一个转派用户".languageString())
            return
        }
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["assignedSiteId"] = selModel.id
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/helpReSsign",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
            hud_succeed("操作成功~".languageString())
            weakSelf.callBack?(true)
            CD.pop()
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
}

class M_OrderTransfer: NSObject {
    var id = ""         //协助人ID
    var pic = ""         //头像,如果为null时前端使用默认图片
    var name = ""         //名称
    var mobile = ""         //手机号码
    var unFinishOrderQty = ""         //工单容量
    var orgName = ""         //所在服务中心
    var isSelect = false
    var usable = ""
    init(_ data:[String:Any] = [:], selArr:[String] = []) {
        id = data.stringValue(forKey: "id")
        pic = kGetServerPicUrl(data.stringValue(forKey: "pic"))
        name = data.stringValue(forKey: "name")
        mobile = data.stringValue(forKey: "mobile")
        unFinishOrderQty = data.stringValue(forKey: "unFinishOrderQty")
        orgName = data.stringValue(forKey: "orgName")
        usable = data.stringValue(forKey: "usable")
        if selArr.contains(id) {
            isSelect = true
        }
    }
    
    func jsonValue() -> [String:Any] {
        var dic:[String:Any] = [:]
        dic["id"] = id
        dic["pic"] = pic
        dic["name"] = name
        dic["mobile"] = mobile
        dic["unFinishOrderQty"] = unFinishOrderQty
        dic["orgName"] = orgName
        dic["usable"] = usable
        return dic
    }
}
