//
//  OrderApplyCloseVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/1.
//

import Foundation

class OrderApplyCloseVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    var orderId = ""
    var callBack:((Bool)->Void)?
    
    var closeReasonList:[M_SelectType] = []
    var closeReason = M_SelectType()
    var remark = ""
    
    var closeType = 1    //关闭类型：1用户验证码;2总部审核(必传)
    var mobile = ""    //用户手机,类型=1时有值;
//    var verificationCode = ""    //验证码,类型=1时有值;
    var codeM = M_VerifyCode() //验证码,类型=1时有值;
    
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(type: .clear)
        do{
            let rowCell = TCFormCellModel<OrderOperationSwitchCell>.init(data: ("销售类型".languageString(), "用户验证码".languageString(), "总部审核".languageString(), "", closeType), config: (false, (8, [.topLeft, .topRight])), frameh: UITableView.automaticDimension) { [weak self] back in
                guard let weakSelf = self else { return }
                if let tag = back as? Int {
                    weakSelf.closeType = tag
                    weakSelf.makeForms()
                }
            }
            newForms.append(rowCell)
        }
        if closeType == 1 {
            do{
                let rowCell = TCFormCellModel<OrderOperationTextFieldCell>.init(data: ("用户手机".languageString(), mobile, UIKeyboardType.phonePad), config: (false, false, ([], 0), false), frameh: UITableView.automaticDimension) { [weak self] t in
                    guard let weakSelf = self else { return }
                    if let t = t as? Int, t == -60 {
                        weakSelf.sendCode()
//                        CD_Timer.make(CD_Timer.Style.notification(M_VerifyCode.verifyCodeSendId, 60, 1))
                    }
                }
                newForms.append(rowCell)
            }
            do{
                codeM.isCodeEnabled = true
                let rowCell = TCFormCellModel<OrderOperationTextFieldCell>.init(data: ("验证码".languageString(), codeM, UIKeyboardType.numberPad), config: (true, false, ([], 0), true), frameh: UITableView.automaticDimension) { [weak self] back in
                    guard let weakSelf = self else { return }
                    if let txt = back as? String {
                        weakSelf.codeM.verifyCode = txt
                        weakSelf.makeForms()
                    }
                }
                newForms.append(rowCell)
            }
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("关闭原因".languageString(), closeReason.name), config: (false, false, (8, [.topLeft, .topRight])), frameh: UITableView.automaticDimension, didSelect:  {
                self.getReturnTypeList()
            })
            newForms.append(rowCell)
        }
        
        do{
            let rowCell = TCFormCellModel<OrderOperationRemarkVCell>.init(data: ("关闭描述".languageString(), remark), config: ((8, [.bottomLeft, .bottomRight]), true), frameh: 96) {[weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    weakSelf.remark = txt
                    weakSelf.makeForms()
                }
            }
            newForms.append(rowCell)
        }
        
        
        
        forms = newForms
        reloadData?()
    }
}

extension OrderApplyCloseVm {
    enum LineCellType {
        case line
        case clear
        case white
    }
    func makeLineCellForm(type:LineCellType, corners:(CGFloat, CACornerMask)? = nil, hideLine:Bool? = nil, hideView:Bool? = nil, height:CGFloat? = nil) -> [TCCellBaseProtocol] {
        var corner:(CGFloat, CACornerMask) = (0,[])
        var isLineHidden = true
        var isViewHidden = false
        var hh:CGFloat = 12
        switch type {
        case .line:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? false
            isViewHidden = hideView ?? false
            hh = height ?? 13
        case .clear:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? true
            isViewHidden = hideView ?? true
            hh = height ?? 8
        case .white:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? true
            isViewHidden = hideView ?? false
            hh = height ?? 8
        }
        let rowCell = TCFormCellModel<WorkbenchTitleCell>.init(data: "", config: (corner, isLineHidden, isViewHidden), frameh: hh)
        return [rowCell]
    }
}

extension OrderApplyCloseVm {
    func selectCloseReason() {
        let dataArr = closeReasonList.compactMap { ($0.name,"") }
        TWSheetPicker.showActionSheet(titleStr: "请选择关闭原因".languageString(), singleType: true, dataArr: dataArr) {[weak self] arr in
            guard let weakSelf = self else {return}
            guard !arr.isEmpty else {return}
            weakSelf.closeReason = weakSelf.closeReasonList[arr.first!]
            weakSelf.makeForms()
        }.show(CD.visibleVC!)
    }
}

extension OrderApplyCloseVm {
    func getReturnTypeList() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["type"] = 2
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/getReturnTypeList",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["list"] as? [[String:Any]] {
                    weakSelf.closeReasonList = list.compactMap({M_SelectType($0)})
                    weakSelf.selectCloseReason()
                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()

    }
    
    func sendCode() {
        var par:[String:Any] = [:]
        par["mobile"] = mobile
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/AppUtil/getVerificationCode",andParam: par)
        cNet.successCall = {(result) in
            hud_hidden()
            CD_Timer.make(CD_Timer.Style.notification(M_VerifyCode.verifyCodeSendId, 60, 1))
            hud_succeed("已发送".languageString())
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func submit() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["returnTypeId"] = closeReason.id
        par["remark"] = remark
        par["closeType"] = closeType
        if closeType == 1 {
            par["mobile"] = mobile
            par["verificationCode"] = codeM.verifyCode
        }
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/close",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_succeed("操作成功~".languageString())
            weakSelf.callBack?(true)
            CD.pop()
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
}

