//
//  OrderGetActivationCodeVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/10/23.
//

import Foundation

class OrderGetActivationCodeVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var orderId = ""
    var callBack:((Bool)->Void)?
    
    var model = M_UserInfo()
    
}

extension OrderGetActivationCodeVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        
        newForms += makeLineCellForm(height: 8)
        newForms += makeSelectCellForm(titleStr: "用户名称".languageString(), infoStr: str(model.userName), isHideArrow: true, corner: (8, [.topLeft, .topRight]))
        newForms += makeSelectCellForm(titleStr: "用户手机".languageString(), infoStr: str(model.userMobile), isHideArrow: true)
        let areaStr = model.proviceName + model.cityName + model.countyName
        newForms += makeSelectCellForm(titleStr: "用户地区".languageString(), infoStr: str(areaStr), isHideArrow: true)
        newForms += makeSelectCellForm(titleStr: "面积类型".languageString(), infoStr: model.areaTypeName)
        newForms += makeTextFieldCellForm(titleStr: "机器条码".languageString(), valueStr: model.barcode, keyboard: .asciiCapable, isScan: true)
        newForms += makeTextFieldCellForm(titleStr: "机身随机码".languageString(), valueStr: model.randomCode, keyboard: .asciiCapable, corner: ([.layerMinXMaxYCorner, .layerMaxXMaxYCorner],8))
        newForms += makeLineCellForm(height: 8)
        
        forms = newForms
        reloadData?()
    }
    
    func str(_ str:String) -> String {
        if str.isEmpty {
            return "nil"
        }
        return str
    }
    
    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, 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, isScan:Bool = false, corner:(CACornerMask,CGFloat) = ([], 0), isUse:Bool = true) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderOperationTextFieldCell>.init(data: (titleStr, valueStr, keyboard, isScan), 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]
    }
}

extension OrderGetActivationCodeVm {
    func didSelect(_ titleStr:String) {
        switch titleStr {
        case "面积类型".languageString():
            var areaTypeArr:[(String, String)] = []
            if isEnglish() {
                areaTypeArr = [("0", "Less than 100m²"),("1", "100-150m²"),("2", "150-200m²"),("3", "200-300m²"),("4", "More than 300m²")]
            }else{
                areaTypeArr = [("0", "100平米以下"),("1", "100-150平米"),("2", "150-200平米"),("3", "200-300平米"),("4", "300平米以上")]
            }
            let pickerDataArr = areaTypeArr.compactMap {
                ($0.1,"")
            }
            TWSheetPicker.showActionSheet(titleStr: "请选择面积类型".languageString(), singleType: true, dataArr: pickerDataArr) {  [weak self] (indexArr) in
                guard let weakSelf = self else { return }
                guard let index = indexArr.first else { return }
                let item = areaTypeArr[index]
                weakSelf.model.areaType = item.0
                weakSelf.model.areaTypeName = item.1
                weakSelf.makeForms()
            }.show(CD.visibleVC!)
        default:
            break
        }
    }
    
    func valueBack(_ titleStr:String, value:Any?) {
        if let tag = value as? Int, tag == -999 {
            let qrVC = QRViewController()
            qrVC.configResultCall {[weak self] code, errorStr in
                guard let weakSelf = self else { return }
                if errorStr != nil && errorStr != "" {
                    CD.visibleVC?.promptInformation(errorStr ?? "扫码出错了~".languageString())
                    return
                }
                weakSelf.model.barcode = code ?? ""
                weakSelf.makeForms()
            }
            let qrNavigationC = TWNavigationVc(rootViewController: qrVC)
            qrNavigationC.modalPresentationStyle = .overFullScreen
            qrNavigationC.modalTransitionStyle = .crossDissolve
            CD.visibleVC?.present(qrNavigationC, animated: true, completion: nil)
        }
        
        if let txt = value as? String {
            switch titleStr {
            case "机身条码".languageString():
                model.barcode = txt
            case "机身随机码".languageString():
                model.randomCode = txt
            default:
                break
            }
            makeForms()
        }
    }
}
extension OrderGetActivationCodeVm {
    func requestData() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/getActivationCodeDetail",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                weakSelf.model = M_UserInfo(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()
    }
    
    func checkData() {
        guard !model.areaType.isEmpty else {
            hud_info("请选择面积类型".languageString())
            return
        }
        guard !model.barcode.isEmpty else {
            hud_info("机器条码不能为空".languageString())
            return
        }
        guard !model.randomCode.isEmpty else {
            hud_info("机身随机码不能为空".languageString())
            return
        }
        submitData()
    }
    
    func submitData() {
        var par:[String:Any] = model.jsonValue()
        par["orderId"] = orderId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/getActivationCode",andParam: par)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_succeed("操作成功~".languageString())
            weakSelf.callBack?(true)
            CD.pop()
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
}

extension OrderGetActivationCodeVm {
    struct M_UserInfo {
        var userName = ""               //用户名称
        var userMobile = ""               //用户手机号码
        var proviceName = ""               //用户所在省名称
        var proviceCode = ""               //用户所在省编码
        var cityName = ""               //用户所在市名称
        var cityCode = ""               //用户所在市编码
        var countyName = ""               //用户所在区/县名称
        var countyCode = ""               //用户所在区/县编码

        var areaType = ""             //面积类型0:100平米以下;1:100-150平米;2:150-200平米;3:200-300平米;4:300以上平米
        var areaTypeName = ""
        var barcode = ""              //机器条码
        var randomCode = ""            //机身随机码
        init(_ data:[String:Any] = [:]) {
            userName = data.stringValue(forKey: "userName")
            userMobile = data.stringValue(forKey: "userMobile")
            proviceName = data.stringValue(forKey: "proviceName")
            proviceCode = data.stringValue(forKey: "proviceCode")
            cityName = data.stringValue(forKey: "cityName")
            cityCode = data.stringValue(forKey: "cityCode")
            countyName = data.stringValue(forKey: "countyName")
            countyCode = data.stringValue(forKey: "countyCode")
        }
        
        func jsonValue() -> [String:Any] {
            var par:[String:Any] = [:]
            par["userName"] = userName
            par["userMobile"] = userMobile
            par["proviceName"] = proviceName
            par["proviceCode"] = proviceCode
            par["cityName"] = cityName
            par["cityCode"] = cityCode
            par["countyName"] = countyName
            par["countyCode"] = countyCode
            
            par["areaType"] = areaType
            par["barcode"] = barcode
            par["randomCode"] = randomCode
            return par
        }
    }
}
