//
//  YHCerAppointViewModel.swift
//  galaxy
//
//  Created by edy on 2024/8/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHCerAppointViewModel: YHBaseViewModel {
    
    var serviceArr: [YHServiceItem] = []
    var hkUsers: [YHHKMemberModel] = []
    var placeList: [YHMakeCertificatePlaceModel] = []
    var appointResult: YHAppointHKResultModel = YHAppointHKResultModel()
    
    // 香港节假日
    var dataModelForHkHolidays: YHHKLegaldaysModel?
    var isHKHolidaysOKFlag: Bool = false
    var isRequestFlag: Bool = false
    
    // 保存香港额外服务
    func saveHkExpectService(params: [String: Any], callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.saveExpectServiceApi
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            [weak self] json, _ in
            guard let self = self else {
                callback?(false, nil)
                return
            }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true, nil)
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { _ in
            callback?(false, nil)
        }
    }
    
    // 获取香港节假日
    func getHKHolidays(callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        if isHKHolidaysOKFlag {
            return
        }
        
        if isRequestFlag {
            return
        }
        
        isRequestFlag = true
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.hkholidaysApi
        
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            self?.isRequestFlag = false
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as?  [String: Any], let resultModel = YHHKLegaldaysModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                self.isHKHolidaysOKFlag = true
                self.dataModelForHkHolidays = resultModel
                callback?(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                self.hkUsers = []
                callback?(false, err)
            }
            
        } failBlock: { err in
            self.isRequestFlag = false
            self.hkUsers = []
            callback?(false, err)
        }
    }
    
    // 获取香港服务列表
    func getServicelist(_ callBack: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.MakeCertificate.servicelist
        _ = YHNetRequest.getRequest(url: strUrl) {
            [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog(json)
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [Any], let list = [YHServiceItem].deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    self.serviceArr = []
                    callBack(false, err)
                    return
                }
                self.serviceArr.removeAll()
                for item in list {
//                    if let item = item {
                        self.serviceArr.append(item)
//                    }
                }
                callBack(true, nil)
                
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                self.serviceArr = []
                callBack(false, error)
            }
            
        } failBlock: { err in
            self.serviceArr = []
            callBack(false, err)
        }
    }
    
    //  所有赴港人员列表
    func getGoHKFamilyMembers(orderId: Int, callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.hkMembers
        _ = YHNetRequest.getRequest(url: strUrl, params: ["order_id": orderId]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [Any], let arr = [YHHKMemberModel].deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    self.hkUsers = []
                    callback?(false, err)
                    return
                }
                self.hkUsers.removeAll()
                for user in arr {
//                    if let user = user {
                        self.hkUsers.append(user)
//                    }
                }
                callback?(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                self.hkUsers = []
                callback?(false, err)
            }
            
        } failBlock: { err in
            self.hkUsers = []
            callback?(false, err)
        }
    }
    
    // 获取港府预约结果
    func getAppointResult(orderId: Int, callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.appointResult
        _ = YHNetRequest.getRequest(url: strUrl, params: ["order_id": orderId]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHAppointHKResultModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                self.appointResult = resultModel
                callback?(true, nil)

            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    // 提交赴港时间预约
    
    func submitAppoint(params: [String: Any], callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.appointResult
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
             json, _ in
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    // 是否需要赴港
    func getIsNeedGoToHK(orderId: Int, callback: ((_ needGoHK: Int, _ reservationToHK: Int) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.isNeedGoHK
        
        _ = YHNetRequest.getRequest(url: strUrl, params: ["order_id": orderId]) { json, _ in
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                // is_need_to_hk 1需要赴港 0不需要 2没有选择
                // reservation_to_hk 0没有预约 1已经预約
                var isNeedGoHK = 2
                var reserveToHK = 0
                if let dic = json.data?.peel as? [String: Any] {
                    if let needGoHK = dic["is_need_to_hk"] as? Int {
                        isNeedGoHK = needGoHK
                    }
                       
                    if let reservationToHK = dic["reservation_to_hk"] as? Int {
                        reserveToHK = reservationToHK
                    }
                    callback?(isNeedGoHK, reserveToHK)
                    
                } else {
                    callback?(2, 0)
                }
                
            } else {
//                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(2, 0)
            }
            
        } failBlock: { _ in
            callback?(2, 0)
        }
    }
    
    // 保存是否需要赴港
    func saveNeedGoHK(orderId: Int, need: Bool, callback: ((_ success: Bool) -> Void)?) {
        // is_need_to_hk 是否需要赴港 1需要 0不需要
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.saveNeedGoHK
        
        _ = YHNetRequest.postRequest(url: strUrl, params: ["order_id": orderId,
                                                              "is_need_to_hk": (need ? 1 : 0)]) {
            
            [weak self] json, _ in
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false)
            }
            
        } failBlock: { _ in
            callback?(false)
        }
    }
    
    //
    func cancelAppoint(orderId: Int, reservationId: Int, callback: ((_ success: Bool) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.cancelAppoint
        
        _ = YHNetRequest.postRequest(url: strUrl, params: ["order_id": orderId,
                                                              "reservation_id": reservationId]) {
            
            [weak self] json, _ in
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false)
            }
            
        } failBlock: { _ in
            callback?(false)
        }
    }
    
    func getMakeCerPlaceList(callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.cerPlaceList
        
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [Any], let arr = [YHMakeCertificatePlaceModel].deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    self.placeList = []
                    callback?(false, err)
                    return
                }
                self.placeList.removeAll()
                for user in arr {
//                    if let user = user {
                        self.placeList.append(user)
//                    }
                }
                callback?(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                self.placeList = []
                callback?(false, err)
            }
            
        } failBlock: { err in
            self.placeList = []
            callback?(false, err)
        }
    }
}
    
