//
//  OrderBookVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/4.
//

import Foundation

class OrderBookVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    var callBack:((Bool)->Void)?
    
    var mobile = ""
    var userName = ""
    var wishBookDate = ""
    var orderId = ""        //当前工单ID;(必传)
    var bookType = 2        //预约状态：1预约失败;2预约成功(必传)
    var bookDate = ""        //预约日期,预约状态=2时必有值;
    var bookDatePeriod = ""        //预约时段,预约状态=2时必有值(不要传1,2,3这种下标值);
    var remark = ""        //预约备注,预约状态=1时必有值

    
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(type: .clear)
        do{
            let rowCell = TCFormCellModel<OrderOperationSwitchCell>.init(data: ("预约用户状态".languageString(), "预约失败".languageString(), "预约成功".languageString(), "", bookType), config: (true, (8, .allCorners)), frameh: UITableView.automaticDimension) { [weak self] back in
                guard let weakSelf = self else { return }
                if let tag = back as? Int {
                    weakSelf.bookType = tag
                    weakSelf.makeForms()
                }
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(type: .clear)
        
        newForms += makeTitleCellForm(titleStr: "用户信息".languageString(), corner: (8, [.topLeft, .topRight]))
        do{
            let rowCell = TCFormCellModel<OrderBookUserInfoCell>.init(data: ("", userName, mobile, wishBookDate), frameh: UITableView.automaticDimension) {[weak self] _ in
                guard let weakSelf = self else { return }
//                if let callUrl = URL(string :"tel://"+"\(weakSelf.mobile)") , UIApplication.shared.canOpenURL(callUrl) {
//                    if #available(iOS 10.0, *) {
//                        UIApplication.shared.open(callUrl)
//                    }else{
//                        UIApplication.shared.openURL(callUrl)
//                    }
//                }else{
//                    hud_error("联系电话错误！")
//                }
                CD.visibleVC?.callUserPhone(weakSelf.mobile, orderId: weakSelf.orderId)
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(type: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        newForms += makeLineCellForm(type: .clear)
        
        newForms += makeTitleCellForm(titleStr: "预约信息".languageString(), corner: (8, [.topLeft, .topRight]))
        if bookType == 2 {
            newForms += makeSelectCellForm(titleStr: "预约日期".languageString(), infoStr: bookDate)
            newForms += makeSelectCellForm(titleStr: "预约时间".languageString(), infoStr: bookDatePeriod)
        }
        newForms += makeSelectCellForm(titleStr: "预约备注".languageString(), infoStr: "nil", isHideLine: true, isHideArrow: true)
        do{
            let rowCell = TCFormCellModel<OrderOperationTextViewCell>.init(data: (remark), frameh: 104) {[weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    weakSelf.remark = txt
                    weakSelf.makeForms()
                }
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(type: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        newForms += makeLineCellForm(type: .clear)
        
        forms = newForms
        reloadData?()
    }
}

extension OrderBookVm {
    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]
    }
    
    func makeTitleCellForm(titleStr:String = "", statusStr:String = "", corner:(CGFloat, UIRectCorner) = (0,[]), hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailTitleCell>.init(data: (titleStr, statusStr), config: corner, frameh: hh ?? UITableView.automaticDimension )
        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]
    }
}

extension OrderBookVm {
    func didSelect(_ titleStr:String) {
        switch titleStr {
        case "预约日期".languageString():
            TSDatePickerVC.showDatePicker(titleStr: "请选择预约日期".languageString(), maxDate: nil, minDate: Date()) { [weak self] (selDate) in
                guard let weakSelf = self else { return }
                let format = DateFormatter()
                format.dateFormat = "yyyy-MM-dd"
                weakSelf.bookDate = format.string(from: selDate)
                weakSelf.makeForms()
            }.show(CD.visibleVC!)
        case "预约时间".languageString():
            guard !bookDate.isEmpty else {
                hud_info("请选择预约日期".languageString())
                return
            }
            var minDate:Date? = nil
            if Date().string("yyyy-MM-dd") == bookDate {
                minDate = Date()
            }
            TSDatePickerVC.showDatePicker(titleStr: "请选择预约时间".languageString(), maxDate: nil, minDate: minDate, mode: .time) { [weak self] (selDate) in
                guard let weakSelf = self else { return }
                let format = DateFormatter()
                format.dateFormat = "HH:mm:00"
                weakSelf.bookDatePeriod = format.string(from: selDate)
                weakSelf.makeForms()
            }.show(CD.visibleVC!)
            
//            var bookDatePeriodArr:[String] = []
//            if Date().string("yyyy-MM-dd") == bookDate {
//                let time = Date().string("HH.mm.ss").floatValue()
//                if time < 10 {
//                    bookDatePeriodArr.append("08:00-10:00")
//                }
//                if time < 12 {
//                    bookDatePeriodArr.append("10:00-12:00")
//                }
//                if time < 14 {
//                    bookDatePeriodArr.append("12:00-14:00")
//                }
//                if time < 16 {
//                    bookDatePeriodArr.append("14:00-16:00")
//                }
//                bookDatePeriodArr.append("16:00以后")
//            }else{
//                bookDatePeriodArr = ["08:00-10:00","10:00-12:00","12:00-14:00","14:00-16:00","16:00以后"]
//            }
//            let dataArr = bookDatePeriodArr.compactMap { ($0,"") }
//            TWSheetPicker.showActionSheet(titleStr: "预约时间段", singleType: true, dataArr: dataArr) {[weak self] arr in
//                guard let weakSelf = self else {return}
//                guard !arr.isEmpty else {return}
//                weakSelf.bookDatePeriod = bookDatePeriodArr[arr.first!]
//                weakSelf.makeForms()
//            }.show(CD.visibleVC!)
        default:
            break
        }
    }
}

extension OrderBookVm {
    
    func submit() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["bookType"] = bookType
        if bookType == 2 {
            par["bookDate"] = bookDate
            par["bookDatePeriod"] = bookDatePeriod
        }
        par["remark"] = remark
        
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/book",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()
    }

}

