//
//  OrderPartsApplyInfoVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/15.
//

import UIKit

class OrderPartsApplyInfoVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var orderId = ""
    var itemId = ""
    var data:[String:Any] = [:] {
        didSet {
            model = M_OrderPartsInfo(data)
        }
    }
    var model = M_OrderPartsInfo()
    var siteComplainStat = 0
    
    var areaStr = ""
    
    var callBack:((Int)->Void)?
    
    var picArr:[TCFormImageModel] = []
    
    lazy var picker:TWImagePicker = {
        let pp = TWImagePicker()
        pp.maxPhotoCount = 3
        pp.isSheet = true
        return pp
    }()
    
    lazy var upload:TWImagePickerUpload = {
        return TWImagePickerUpload()
    }()
}

extension OrderPartsApplyInfoVm {
    func makeForms() {
        switch model.applyPartsMode {
        case "1":
            makeForms1()
        case "2":
            makeForms2()
        default:
            makeForms1()
            break
        }
    }
    
    func makeForms1() {
        var newForms:[TCCellBaseProtocol] = []
        //MARK: ------申领信息
        newForms += makeLineCellForm(height: 8)
        newForms += makeTitleCellForm(titleStr: "申领信息".languageString(), corner: (8, [.topLeft, .topRight]))
        newForms += makeSelectCellForm(titleStr: "申请单号".languageString(), infoStr: model.applyNo, isHideArrow: true)
        newForms += makeSelectCellForm(titleStr: "状态".languageString(), infoStr: model.statName, isHideArrow: true)
        areaStr = model.deliverProvince + model.deliverCity + model.deliverCounty + model.delieverTown
        newForms += makeSelectCellForm(titleStr: "收货地区".languageString(), infoStr: areaStr, isHideArrow: false)
        newForms += makeTextFieldCellForm(titleStr: "详细地址".languageString(), valueStr: model.deliverAddress)
        newForms += makeTextFieldCellForm(titleStr: "收货人".languageString(), valueStr: model.deliverMan)
        newForms += makeTextFieldCellForm(titleStr: "联系电话".languageString(), valueStr: model.deliverMobile, keyboard: .phonePad)
        var txt = ""
        switch model.outType {
        case "1":
            txt = "总部".languageString()
        case "2":
            txt = "区域".languageString()
        default:
            break
        }
        newForms += makeSelectCellForm(titleStr: "发出类型".languageString(), infoStr: txt, isHideArrow: true)
        newForms += makeSelectCellForm(titleStr: "发出仓库".languageString(), infoStr: model.outWarehouseName, isHideArrow: true)
        newForms += makeSelectCellForm(titleStr: "配送方式".languageString(), infoStr: model.deliverTypeName, isHideArrow: true)
        newForms += makeSelectCellForm(titleStr: "数量/金额".languageString(), infoStr: model.qtyAndAmount, isHideArrow: true)
        newForms += makeSelectCellForm(titleStr: "申请人".languageString(), infoStr: model.createByAndDate, isHideArrow: true)
        newForms += makeTextFieldCellForm(titleStr: "备注".languageString(), valueStr: model.remark)
        newForms += makeSelectCellForm(titleStr: "凭证".languageString(), infoStr: "nil", isHideLine: true, isHideArrow: true)
        do{
            let rowCell = TCFormCellModel<OrderOperationAddImagesCell>.init(data: picArr, config: (false, true, 3), frameh: 76) {[weak self] back in
                guard let weakSelf = self else { return }
                if let data = back as? (Int, Int) {
                    switch data.0 {
                    case 1:
                        weakSelf.picArr.remove(at: data.1)
                        weakSelf.picker.remove(data.1)
                        weakSelf.makeForms()
                    case 2:
                        weakSelf.showImages(data.1)
                    case 3:
                        weakSelf.picker.maxPhotoCount = 3 - weakSelf.picArr.filter({$0.image == nil}).count
                        weakSelf.picker.showPhoto(weakSelf.picker.list.count) {[weak self] in
                            guard let strongSelf = self else { return }
                            strongSelf.requstUploadImages()
                            strongSelf.makeForms()
                        }
                    default:
                        break
                    }
                }
            }
            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]))
        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(), statusStr: "新增".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,hh: 12)
            newForms += makeOperationLineCellForm(hh: 1)
            newForms += makeDeleteCellForm(idx: i, hh:36)
        }
        newForms += makeLineCellForm(leftW: 12, rightW: 12,bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        newForms += makeLineCellForm(height: 8)
        
        forms = newForms
        reloadData?()
    }
    
    func makeForms2() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 8)
        for (i,item) in model.waitApplyPartsList.enumerated() {
            do{
                let rowCell = TCFormCellModel<OrderWaitApplyPartsCell>.init(data: item, config: (false, true), frameh: UITableView.automaticDimension) { [weak self] back in
                    guard let weakSelf = self else { return }
                    if let tag = back as? Int, tag == -99 {
                        weakSelf.model.waitApplyPartsList.remove(at: i)
                        weakSelf.makeForms()
                    }
                    if let qty = back as? String {
                        weakSelf.model.waitApplyPartsList[i].qty = qty
                        weakSelf.makeForms()
                    }
                }
                newForms.append(rowCell)
            }
            newForms += makeLineCellForm(height: 8)
        }
        forms = newForms
        reloadData?()
    }
    
    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) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.didSelect(titleStr)
        }
        return [rowCell]
    }
    
    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 makeSelectCellForm(titleStr:String = "", infoStr:String = "", isHideLine:Bool = false, isHideArrow:Bool = false, corner:(CGFloat, UIRectCorner) = (0,[]), hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: (titleStr,(isHideArrow && infoStr.isEmpty) ? "nil" : infoStr), config: (isHideLine, isHideArrow, corner), frameh: hh ?? UITableView.automaticDimension, didSelect:  {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.didSelect(titleStr)
        })
        return [rowCell]
    }
    
    func makeTextFieldCellForm(titleStr:String, valueStr:String = "", keyboard:UIKeyboardType = .default, isHideBtn:Bool = true, isHideline:Bool = false, corner:(CACornerMask,CGFloat) = ([], 0), isUse:Bool = true) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderOperationTextFieldCell>.init(data: (titleStr, valueStr, keyboard), config: (isHideBtn, isHideline, corner, isUse), frameh: UITableView.automaticDimension) { [weak self] t in
            guard let weakSelf = self else { return }
            weakSelf.valueBack(titleStr, value: t)
        }
        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_OrderPartsInfo.Parts, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderPartsApplyListItemAmountCell>.init(data: (data),  frameh: hh == nil ? UITableView.automaticDimension : hh!)
        return [rowCell]
    }
    
    func makeDeleteCellForm(idx:Int, hh:CGFloat = 36) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderPartsApplyListDeleteCell>.init(frameh: hh) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.deleteParts(idx)
        }
        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]
    }
    
    func showImages(_ idx:Int = 0) {
        let imgArr:[(String,UIImage?)] = picArr.compactMap { ($0.imageUrl, $0.image) }
        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 OrderPartsApplyInfoVm {
    func didSelect(_ titleStr:String) {
        switch titleStr {
        case "收货地区".languageString():
            let vc = UIStoryboard(name: "CreatOrder", bundle: nil).instantiateViewController(withIdentifier: "VC_SelectArea") as! VC_SelectArea
            vc.modalTransitionStyle = .crossDissolve
            vc.modalPresentationStyle = .custom
            vc.style = .省市区街道
            vc.isAllDataBack = true
            vc.pickerAllDataBack = {[weak self] (areaId,areaArr) in
                guard let weakSelf = self else { return }
                weakSelf.model.areaId = areaId
                for (i, item) in areaArr.enumerated() {
                    switch i {
                    case 0:
                        weakSelf.model.deliverProvince = item.stringValue(forKey: "areaName")
                    case 1:
                        weakSelf.model.deliverCity = item.stringValue(forKey: "areaName")
                    case 2:
                        weakSelf.model.deliverCounty = item.stringValue(forKey: "areaName")
                    case 3:
                        weakSelf.model.delieverTown = item.stringValue(forKey: "areaName")
                    default:
                        break
                    }
                }
                weakSelf.makeForms()
            }
            CD.visibleVC?.present(vc, animated: true, completion: nil)
        case "配件明细".languageString():
            R_OrderSelectPart.router(orderId, itemId: itemId, outwarehouseId: model.outWarehouseId, applyPartsMode: model.applyPartsMode) { [weak self] (selItes) in
                guard let weakSelf = self else { return }
                let partsIdArr = weakSelf.model.partsList.compactMap({$0.partsId})
                for item in selItes {
                    if !partsIdArr.contains(item.partsId) {
                        weakSelf.model.partsList.append(item)
                    }else{
                        for (j, it) in weakSelf.model.partsList.enumerated(){
                            if it.partsId == item.partsId {
                                weakSelf.model.partsList[j].applyQty = "\(weakSelf.model.partsList[j].applyQty.intValue() + item.applyQty.intValue())"
                            }
                        }
                    }
                }
                weakSelf.makeForms()
            }
        default:
            break
        }
        makeForms()
    }
    
    func valueBack(_ titleStr:String, value:Any?) {
        if let txt = value as? String {
            switch titleStr {
            case "详细地址".languageString():
                model.deliverAddress = txt
            case "收货人".languageString():
                model.deliverMan = txt
            case "联系电话".languageString():
                model.deliverMobile = txt
            case "备注".languageString():
                model.remark = txt
            default:
                break
            }
        }
        makeForms()
    }
    
    func deleteParts(_ idx:Int) {
        model.partsList.remove(at: idx)
        makeForms()
    }
}
extension OrderPartsApplyInfoVm {
    func saveData() {
        for (i, item) in picArr.enumerated() {
            switch i {
            case 0:
                model.pic1 = kGetPicUrl(item.imageUrl)
            case 1:
                model.pic2 = kGetPicUrl(item.imageUrl)
            case 2:
                model.pic3 = kGetPicUrl(item.imageUrl)
            default:
                break
            }
        }
        guard !areaStr.isEmpty else {
            hud_info("请选择收货地区！".languageString())
            return
        }
        guard !model.deliverAddress.isEmpty else {
            hud_info("请填写详细地址！".languageString())
            return
        }
        guard !model.deliverMan.isEmpty else {
            hud_info("请填写收货人姓名！".languageString())
            return
        }
        guard !model.deliverMobile.isEmpty else {
            hud_info("请填写联系电话！".languageString())
            return
        }
        guard !model.outType.isEmpty else {
            hud_info("发出类型不能为空！".languageString())
            return
        }
        guard !model.outWarehouseName.isEmpty else {
            hud_info("发出仓库不能为空！".languageString())
            return
        }
        guard !model.partsList.isEmpty else {
            hud_info("配件明细不能为空！".languageString())
            return
        }
        requestUpdatePartsApply()
    }
    
    func requestUpdatePartsApply() {
        var par:[String:Any] = model.jsonValue()
        par["orderId"] = orderId

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/updatePartsApply",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
            hud_succeed("操作成功~".languageString())
            CD.pop()
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
    
    func requstUploadImages(){
        let images:[TWImagePicker.Model] = picker.list
    
        if images.isEmpty { return }
        for (i,item) in images.enumerated() {
            let cNet = TWOCNetwork(url: "/admin/sys-file/upload",andParam: [:])
            cNet.successCall = { [weak self] (result) in
                guard let weakSelf = self else { return }
                if let data = result["data"] as? [String:Any] {
                    let iconUrl = kGetServerPicUrl(data.stringValue(forKey: "url"))
                    weakSelf.picker.list[i].uploadurl = iconUrl
                    weakSelf.picker.list[i].isupload = true
                    weakSelf.picArr = weakSelf.picArr.filter({$0.image == nil})
                    weakSelf.picArr += weakSelf.picker.list.compactMap({TCFormImageModel(imageUrl: $0.uploadurl, image: $0.image)})
                    weakSelf.makeForms()
                }else{
                    hud_error("请求出错了，请稍后再试~".languageString())
                }
            }
            cNet.failCall = {(errorTag,errorStr) in
                hud_error(errorStr)
            }
            cNet.upLoad(item.image!)
        }
    }
}

