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

import UIKit

class YHCerAppointViewModel: NSObject {
    
    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 getHKHolidays(callback:((_ success: Bool, _ error: YHErrorModel?)->())?) {

        
        if isHKHolidaysOKFlag {
            return
        }
        
        
        if isRequestFlag {
            return
        }
        
        isRequestFlag = true
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.hkholidaysApi
        
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            self?.isRequestFlag = false
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                let dic = json.data
                guard let resultModel = YHHKLegaldaysModel.deserialize(dict: dic as? [AnyHashable : Any]) 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?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.MakeCertificate.servicelist
        let _ = YHNetRequest.getRequest(url: strUrl) {
            [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog(json)
            
            if json.code == 200 {
                let dic = json.data
                guard let list = [YHServiceItem].deserialize(array: dic as? [Any]) 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?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.hkMembers
        let _ = YHNetRequest.getRequest(url: strUrl,params: ["order_id" : orderId]) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                let dic = json.data
                guard let arr = [YHHKMemberModel].deserialize(array: dic as? [Any]) 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?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.appointResult
        let _ = YHNetRequest.getRequest(url: strUrl,params: ["order_id" : orderId]) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                let dic = json.data
                guard let resultModel = YHAppointHKResultModel.deserialize(dict: dic as? [AnyHashable : Any]) 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 getIsNeedGoToHK(orderId: Int, callback:((_ needGoHK: Int, _ reservationToHK: Int)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.isNeedGoHK
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: ["order_id" : orderId]) {
            
            [weak self] json, code in
            guard let self = self else { return }
            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 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: { err in
            callback?(2, 0)
        }
    }
    
    // 保存是否需要赴港
    func saveNeedGoHK(orderId: Int, need: Bool, callback:((_ success: Bool)->())?) {
        // is_need_to_hk 是否需要赴港 1需要 0不需要
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.saveNeedGoHK
        
        let _ = YHNetRequest.postRequest(url: strUrl,params: ["order_id" : orderId,
                                                              "is_need_to_hk" : (need ? 1 : 0)]) {
            
            [weak self] json, code 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: { err in
            callback?(false)
        }
    }
    
    //
    func cancelAppoint(orderId:Int, reservationId:Int, callback:((_ success: Bool)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.cancelAppoint
        
        let _ = YHNetRequest.postRequest(url: strUrl,params: ["order_id" : orderId,
                                                              "reservation_id" : reservationId]) {
            
            [weak self] json, code 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: { err in
            callback?(false)
        }
    }
    
    func getMakeCerPlaceList(callback:((_ success: Bool, _ error: YHErrorModel?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.AppointHK.cerPlaceList
        
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                let dic = json.data
                guard let arr = [YHMakeCertificatePlaceModel].deserialize(array: dic as? [Any]) 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)
        }
    }
}
    
    
    
