//
//  PartsApplyDetailVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/22.
//

import Foundation

class PartsApplyDetailVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var applyId = ""
    
    var model = M_PartsApplyDetail()
}

extension PartsApplyDetailVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 16)
        do{
            let rowCell = TCFormCellModel<PartsApplyDetailStatusCell>.init(data: ("icon_daizhifu", model.statName, model.applyTypeName,""), frameh: UITableView.automaticDimension)
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(height: 24)
        do{
            let rowCell = TCFormCellModel<PartsApplyDetailNumCell>.init(data: (model.applyNo), frameh: 44)
            newForms.append(rowCell)
        }
        //MARK: ----申请信息
        newForms += makeTitleCellForm(titleStr: "申请信息".languageString())
        newForms += makeInfoCellForm(titleStr: "申请单位".languageString(), detailStr: model.siteName)
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        newForms += makeInfoCellForm(titleStr: "申请时间".languageString(), detailStr: model.applyDate)
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        newForms += makeInfoCellForm(titleStr: "收 货 人".languageString(), detailStr: "\(model.deliverMan)/\(model.deliverMobile)")
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        newForms += makeInfoCellForm(titleStr: "收货地址".languageString(), detailStr: "\(model.deliverProvince)\(model.deliverCity)\(model.deliverCounty)\(model.delieverTown)\(model.deliverAddress)")
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        newForms += makeInfoCellForm(titleStr: "数      量".languageString(), detailStr: model.applyQtyAll)
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        newForms += makeInfoCellForm(titleStr: "备      注".languageString(), detailStr: model.remark)
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        do{
            let rowCell = TCFormCellModel<PartsApplyDetailImagesCell>.init(data: ("凭      证".languageString(), model.picArr), frameh: UITableView.automaticDimension) { [weak self] back in
                guard let weakSelf = self else { return }
                if let tag = back as? Int {
                    weakSelf.showImages(tag)
                }
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]),height: 12)
        
        
        //MARK: ----发货信息
        newForms += makeLineCellForm(height: 8)
        newForms += makeTitleCellForm(titleStr: "发货信息".languageString(), corner: (8, [.topLeft, .topRight]))
        var outTypeName = ""
        switch model.outType {
        case "1":
            outTypeName = "总部".languageString()
        case "2":
            outTypeName = "区域".languageString()
        default:
            break
        }
        newForms += makeInfoCellForm(titleStr: "发出类型".languageString(), detailStr: outTypeName)
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        newForms += makeInfoCellForm(titleStr: "发出仓库".languageString(), detailStr: model.outWarehouseName)
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
//        newForms += makeInfoCellForm(titleStr: "物流类型", detailStr: "")
//        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
        newForms += makeInfoCellForm(titleStr: "配送方式".languageString(), detailStr: model.deliverTypeName)
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]),height: 12)
        
        
        //MARK: ----物流信息
        newForms += makeLineCellForm(height: 8)
        newForms += makeTitleCellForm(titleStr: "物流信息".languageString(), corner: (8, [.topLeft, .topRight]))
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 12)
        do{
            let rowCell = TCFormCellModel<OrderPartsApplyLogisticsInfoCell>.init(data: (model.deliverCompanyName, model.deliverNo), frameh: UITableView.automaticDimension)
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(leftW: 12, rightW: 12,bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 16)
        
        
        
        //MARK: ------配件明细
        newForms += makeLineCellForm(height: 8)
        newForms += makeTitleCellForm(titleStr: "配件明细".languageString(), corner: (8, [.topLeft, .topRight]))
        for (i,item) in model.partsList.enumerated() {
            if i > 0 {
                newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white,height: 8)
            }
            newForms += makeOperationLineCellForm(lineColor: .clear,corner: (8, [.topLeft, .topRight], 2))
            newForms += makeItemCellForm(imgStr: item.pic, name: item.partsName, code: item.partsCode)
            newForms += makeOperationLineCellForm(lineColor: .clear,hh: 6)
            newForms += makeAmountCellForm(data: item, hh: 136)
            newForms += makeOperationLineCellForm(lineColor: .clear, corner: (8, [.bottomLeft, .bottomRight], 2),hh: 12)
        }
        newForms += makeLineCellForm(leftW: 12, rightW: 12,bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        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 = 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), frameh: hh ?? UITableView.automaticDimension)
        return [rowCell]
    }
    
    func makeInfoCellForm(titleStr:String, detailStr:String) -> [TCCellBaseProtocol] {
        let ww = titleStr.getLabelWidth(h: 20, f: Config.font.fontRegular(14))
        let rowCell = TCFormCellModel<PartsManagementListInfoCell>.init(data: (titleStr, detailStr), config: ww + 8, frameh: UITableView.automaticDimension)
        return [rowCell]
    }
    
    
    func makeItemCellForm(imgStr:String, name:String, code:String) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderPartsApplyListItemCell>.init(data: (imgStr, name, code),  frameh: UITableView.automaticDimension)
        return [rowCell]
    }
    
    func makeAmountCellForm(data:M_PartsApplyDetail.Parts, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let m = M_OrderPartsInfo.Parts(data.jsonValue())
        let rowCell = TCFormCellModel<OrderPartsApplyListItemAmountCell>.init(data: (m),  frameh: hh == nil ? UITableView.automaticDimension : hh!)
        return [rowCell]
    }
    
    func makeOperationLineCellForm(cellColor:UIColor = .clear, bgColor:UIColor = .white, contentColor:UIColor = Config.color.hex("f8"), lineColor:UIColor = Config.color.hex("e6"), left1:CGFloat = 12, left2:CGFloat = 12, left3:CGFloat = 12, corner:(CGFloat, UIRectCorner, Int) = (0,[],3), hh:CGFloat = 12) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderOperationLineCell>.init(data: (cellColor, bgColor, contentColor, lineColor ), config: (left1, left2, left3, corner),frameh: hh)
        return [rowCell]
    }
}

extension PartsApplyDetailVm {
    func showImages(_ idx:Int = 0) {
        let imgArr:[(String,UIImage?)] = model.picArr.compactMap { ($0, nil) }
        var photos:[GKPhoto] = []
        for item in imgArr {
            let  photo = GKPhoto()
            if !item.0.isEmpty {
                photo.url = URL(string: item.0)!
            }
            if item.1 != nil {
                photo.image = item.1
            }
            photos.append(photo)
        }
        let browser = GKPhotoBrowser(photos: photos, currentIndex: idx)
        browser.showStyle = .none
        browser.modalPresentationStyle = .overFullScreen
        browser.show(fromVC: CD.visibleVC!)
    }
}

extension PartsApplyDetailVm {
    
    func requestDatas() {
        var par:[String:Any] = [:]
        par["applyId"] = applyId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/parts/getApplyDetail",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_hidden()
            if let data = result["data"] as? [String:Any] {
                weakSelf.model = M_PartsApplyDetail(data)
                weakSelf.makeForms()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
}

