//
//  FinishFeesCategoryVm.swift
//  VattiCSS
//
//  Created by WZR on 2024/1/4.
//

import Foundation

class FinishFeesCategoryVm {
    
    var orderId = ""
    var feeType = 1
    var guaranteeType = ""
    var itemCategoryId = ""
    var serviceTypeId = ""
    var itemId = ""
    
    var searchKey = ""
    
    var list:[M_FinishFeesCategory] = [] {
        didSet{
            defaultSelectFirst()
            makeForm()
        }
    }
    var selectId:String = ""
    var selectItem = M_FinishFeesCategory()
    var selectIndex:Int = 0
    var selFeesList:[M_FinishFeesCategory.FeeItem] = []
    
    lazy var forms:[[CD_CellProtocol]] = {
        return list.map({ (m) -> [CD_CellProtocol] in
            return []
        })
    }()
    lazy var formsHeader: [CD_CellProtocol] = {
        return []
    }()
    
    var reloadData: (() -> Void)?
    var reloadFeesData: (() -> Void)?
    init() {
        //makeList()
    }
    
    var cellForms:[TCCellBaseProtocol] = []
}

extension FinishFeesCategoryVm {
    func defaultSelectFirst() {
        let arr = self.list.map{$0}
        guard !arr.isEmpty else {
            return
        }
        arr[0].select = true
        self.selectItem = arr[0]
        self.selectId = arr[0].bigTypeId
        self.reloadData?()
    }
    
    func makeForm() {
        var newForms:[CD_CellProtocol] = []
        do{
            let lineModel = Cell_Line.Model(color: UIColor.cd_hex("f8"), colorbg: UIColor.cd_hex("f8"))
            let lineCell = CD_RowCell<Cell_Line>.init(config: lineModel, frame: CGRect(h:8), bundleFrom: Cell_Line.bundle)
            newForms.append(lineCell)
        }
        for (i, m) in list.enumerated() {
            let corner:(UIRectCorner, CGFloat) = i == selectIndex + 1 ? ([.topRight], 8) : (i == selectIndex - 1 ? ([.bottomRight], 8) : ([],0))
            let row = CD_RowCell<Cell_FinishFeesCategory>(data: (m), config: corner, frame: CGRect(h: UITableView.automaticDimension), didSelect: { [weak self] in
                self?.selectIndex = i
                guard let id = self?.selectId, id != m.bigTypeId else {
                    return
                }
                self?.selectItem = m
                self?.selectId = m.bigTypeId
                self?.didSelectCell(m.bigTypeId)
                self?.refreshFeeSubject()
            })
            newForms.append(row)
        }
        do{
            let corner:(UIRectCorner, CGFloat) = selectIndex == list.count - 1 ? ([.topRight], 8) : ([],0)
            let row = CD_RowCell<Cell_FinishFeesCategory>(data: (M_FinishFeesCategory()), config: corner, frame: CGRect(h: UITableView.automaticDimension))
            newForms.append(row)
        }
        forms = [newForms]
        makeFeesForm()
        reloadData?()
    }
    
    func didSelectHeader(_ id:String) {
        for item in list where item.bigTypeId == id {
            item.select = !item.select
        }
        makeForm()
        //self.reloadData?()
    }
    
    func didSelectCell(_ id:String)  {
        
        list.forEach { (item) in
            if (item.bigTypeId) == id {
                
               item.select = !item.select
            }else{
                item.select = false
            }
        }
        makeForm()
        //self.reloadData?()
    }
    
}

extension FinishFeesCategoryVm {
    func makeFeesForm()  {
        var newForms:[TCCellBaseProtocol] = []
        
        newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
        if !list.isEmpty {
            for (i, item) in list[selectIndex].smallTypeList.enumerated() {
                newForms += makeSmallCategoryCellForm(titleStr: item.smallTypeName, isShow: item.isShow, corner: i == 0 ? ([.topLeft], 8) : ([],0), idx: i)
                if item.isShow && !item.feesList.isEmpty {
                    for (j, fee) in item.feesList.enumerated() {
                        newForms += makeLineCellForm(bgColor: Config.color.hex("f"), height: 8)
                        newForms += makeFeesItemCellForm(titleStr: fee.subjectName, detailStr: fee.spec, price: "¥\(fee.price)元/\(fee.unit)", qty: fee.qty, sIdx: i, idx: j)
                    }
                    newForms += makeLineCellForm(bgColor: Config.color.hex("f"), height: 8)
                }
            }
        }
        cellForms = newForms
        reloadFeesData?()
    }
    
    func makeLineCellForm(leftW:CGFloat = 0, rightW:CGFloat = 0, bgColor:UIColor = .clear, backGroundColor:UIColor = .clear, corners:(CGFloat, CACornerMask) = (0, []), height:CGFloat = 12, 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)
        return [rowCell]
    }
    
    func makeSmallCategoryCellForm(titleStr:String, isShow:Bool, corner:(UIRectCorner, CGFloat) = ([],0), idx:Int) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<Cell_FinishFeesSmallCategory>.init(data: (titleStr, isShow), config: corner, frameh: 44, didSelect:  {[weak self] in
            guard let weakSelf = self else { return }
            if !isShow {
//                if weakSelf.list[weakSelf.selectIndex].smallTypeList[idx].feesList.isEmpty {
//                    weakSelf.getFeeSubject(idx)
//                }else{
//                    weakSelf.list[weakSelf.selectIndex].smallTypeList[idx].isShow = true
//                }
                weakSelf.getFeeSubject(idx)
            }else{
                weakSelf.list[weakSelf.selectIndex].smallTypeList[idx].isShow = false
            }
            weakSelf.makeFeesForm()
        })
        return [rowCell]
    }
    
    func makeFeesItemCellForm(titleStr:String, detailStr:String, price:String, qty:Int, sIdx:Int, idx:Int) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<Cell_FinishFeesItem>.init(data: (titleStr, detailStr, price, qty), frameh: UITableView.automaticDimension, callBack: {[weak self] back in
            guard let weakSelf = self else { return }
            if let qty = back as? Int {
                weakSelf.addSubFees(sIdx: sIdx, idx: idx, qty: qty)
            }
        })
        return [rowCell]
    }
}

extension FinishFeesCategoryVm {
    func addSubFees(sIdx: Int, idx:Int, qty:Int) {
        list[selectIndex].smallTypeList[sIdx].feesList[idx].qty = qty

        selFeesList = []
        for x in list {
            for y in x.smallTypeList {
                for z in y.feesList {
                    if z.qty > 0 {
                        selFeesList.append(z)
                    }
                }
            }
        }
        makeFeesForm()
    }
    
    func refreshFeeSubject() {
        guard list.count > selectIndex else {
            return
        }
        for (i,item) in list[selectIndex].smallTypeList.enumerated() {
            if item.isShow {
                getFeeSubject(i)
            }
        }
    }
    
    func reloadFeesList() {
        let ids = selFeesList.compactMap({$0.subjectId})
        for (i,x) in list.enumerated() {
            for (j,y) in x.smallTypeList.enumerated() {
                for (k,z) in y.feesList.enumerated() {
                    if ids.contains(z.subjectId) {
                        for item in selFeesList {
                            if item.subjectId == z.subjectId {
                                list[i].smallTypeList[j].feesList[k].qty = item.qty
                            }
                        }
                    }else{
                        list[i].smallTypeList[j].feesList[k].qty = 0
                    }
                }
            }
        }
        makeForm()
    }
}

extension FinishFeesCategoryVm {
    
    func requestList() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["feeType"] = feeType
        par["guaranteeType"] = guaranteeType
        par["itemCategoryId"] = itemCategoryId
        par["serviceTypeId"] = serviceTypeId
        par["itemId"] = itemId

        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/orderFinishDo/getFeeSubjectType",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.list = data.arrayValue(forKey: "bigTypeList").compactMap({M_FinishFeesCategory($0)})
                weakSelf.makeForm()
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            hud_error(errorStr)
            weakSelf.makeForm()
        }
        cNet.postRequest()
    }
    
    func getFeeSubject(_ idx:Int) {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["smallTypeId"] = list[selectIndex].smallTypeList[idx].smallTypeId
        par["searchKey"] = searchKey
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/orderFinishDo/getFeeSubject",andParam: par)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                let dataList = data.arrayValue(forKey: "dataList").compactMap({M_FinishFeesCategory.FeeItem(json: $0)})
                weakSelf.list[weakSelf.selectIndex].smallTypeList[idx].feesList = dataList
                weakSelf.list[weakSelf.selectIndex].smallTypeList[idx].isShow = true
                weakSelf.reloadFeesList()
                weakSelf.makeForm()
            }else{
                weakSelf.list[weakSelf.selectIndex].smallTypeList[idx].isShow = false
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            hud_error(errorStr)
            weakSelf.list[weakSelf.selectIndex].smallTypeList[idx].isShow = false
            weakSelf.makeForm()
        }
        cNet.postRequest()
    }
}

extension FinishFeesCategoryVm: CD_ViewModelTableViewProtocol {
    var _forms: [[CD_CellProtocol]] {
        return forms
    }
    
    var _formHeaders: [CD_CellProtocol] {
        return []
    }
    
    var _formFooters: [CD_CellProtocol] {
        return []
    }
    
    var _reloadData: (() -> Void)? {
        get {
            return reloadData
        }
        set(newValue) {
            reloadData = newValue
        }
    }
    
    var _reloadDataIndexPath: (([IndexPath], UITableView.RowAnimation) -> Void)? {
        get {
            return nil
        }
        set(newValue) {
            
        }
    }
    
    func requestData(_ refresh: Bool) {
        requestList()
    }
    
    var _mjRefreshType: [CD_MJRefreshModel.RefreshType] {
        return []
    }
    
    
}
