//
//  YHServiceCenterMainViewModel.swift
//  galaxy
//
//  Created by davidhuangA on 2024/1/23.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SmartCodable
class YHServiceCenterMainViewModel: YHBaseViewModel {
    
    var application_type : Int = 0  // 高才 才使用该数据 1-高A 2-高B 3-高C
    
    //合同列表 数据
    var arrContactList : [YHContactItemModel] = []
    
    //合同对应的状态
    var arrContactStausItmes: [YHContactMainItemStatusModel] = []
    var contactDetailData: YHContactMainItemStatusModel2?
    
    //信息完善列表
    var arrInfoFillStep : [YHInformationPerfectModel] = []
    var myInfoFillStep : Int = 0
    var myTargetIndex : Int = -1
    var informationFillStepModel : YHPersonInfoFillStepModel?
    
    //我的评分
    var myScoreResultData : YHScoreResultModel?//网络请求的结果数据
    var localScoreData : YHScoreDataModel? //本地缓存的数据
    var allInfoScoreModel: YHContactInfoScoreModel? //提交信息获取 得分
    
    //服务中心进度模型
    var arrDataForSeviceCenterProgress  : [YHServiceCenterProgressModel] = []
    var personInfoModel: YHPersonInfoModel = YHPersonInfoModel()
}

//请求接口
extension YHServiceCenterMainViewModel {
    //服务中心进度列表
    func getServiceCenterProgressList(_ orderId: Int, _ type: Int,callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        
        /*
         orderId integer 订单id 可选
         status integer 可选   0全部 1待开始 2进行中 3 已完成
         let arr = ["orderId":id,"status"]
         */
        let params: [String : Any] = ["orderId": orderId,
                                      "status": type]

        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.serviceCenterProgressApi
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code 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 result = [YHServiceCenterProgressModel].deserialize(from: dic) else {
                    callBackBlock(false,nil)
                    return
                }
                self.arrDataForSeviceCenterProgress = result 
                callBackBlock(true, nil)
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false,err)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    //服务中心进度列表
    func getNewServiceCenterProgressList(_ orderId: Int, _ type: Int, orderType: Int, callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        
        /*
         orderId integer 订单id 可选
         status integer 可选   0全部 1待开始 2进行中 3 已完成
         let arr = ["orderId":id,"status"]
         */
        let params: [String : Any] = ["orderId": orderId,
                                      "status": type]

        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.process
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code 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 result = [YHServiceProgressModel].deserialize(from: dic) else {
                    callBackBlock(false,nil)
                    return
                }
                
                var resultItem = YHServiceProgressModel()
                for item in result {
                    if item.type == orderType {
                        resultItem = item
                    } else {
                        if orderType == 2 && (item.type == 2 || item.type == 3) {
                            resultItem = item
                        }
                    }
                }
                self.arrDataForSeviceCenterProgress = resultItem.list
//                self.arrDataForSeviceCenterProgress = result as! [YHServiceCenterProgressModel]
                callBackBlock(true, nil)
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false,err)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    //获取我的评分结果
    func getMyScoreDetail( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        
        loadLocalScoreData()
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.scoreDetailApi
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code 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 = YHScoreResultModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    
                    callBackBlock(false,err)
                    return
                }
                self.myScoreResultData = resultModel
                
                if let localScoreData = self.localScoreData  {
                    localScoreData.age_score!.resultData = resultModel.age_score
                    localScoreData.language_score!.resultData = resultModel.language_score
                    localScoreData.background_score!.resultData = resultModel.background_score
                    localScoreData.work_experience_score!.resultData = resultModel.work_experience_score
                    localScoreData.education_score!.resultData = resultModel.education_score
                    localScoreData.talent_list_score!.resultData = resultModel.talent_list_score
                    
                    callBackBlock(true,nil)
                } else {
                    
                    
                    let err = YHErrorModel(errorCode: YHErrorCode.unknowError.rawValue, errorMsg: YHErrorCode.unknowError.description())
                    callBackBlock(false,err)
                }
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false,err)
                
            }
            
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    //请求合同项
    func getContactList(callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.contractListApi
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            arrContactList.removeAll()
            
            if json.code == 200 {
                DispatchQueue.global().async {
                    guard let dic = json.data?.peel as? [String : Any],let resultModel = YHContactItemHoldModel.deserialize(from: dic) else {
                        
                        DispatchQueue.main.async {
                            self.arrContactList = []
                            callBackBlock(false,nil)
                        }
                        return
                    }
                    
                    DispatchQueue.main.async {
                        self.arrContactList = resultModel.orders
                        callBackBlock(true,nil)
                    }
                }
                
            } else {
                arrContactList = []
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code),errorMsg: json.msg.count > 0 ? json.msg : "数据错误")
                callBackBlock(false,error)
            }
        } failBlock: { err in
            self.arrContactList = []
            callBackBlock(false,err)
        }
    }
    
    
    //请求合同的状态
    func getContactStatus( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.contractStatusApi
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            arrContactStausItmes = []
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String : Any], let resultModel = YHContactMainItemStatusModel2.deserialize(from: dic) else {
                    self.arrContactStausItmes = []
                    callBackBlock(false,nil)
                    return
                }

                self.contactDetailData = resultModel
                if resultModel.fill_info_step > 6 {
                    //resultModel.fill_info_step == 7的时候表示 我的信息填写完成
                    let model = YHContactMainItemStatusModel()
                    model.type = 1
                    model.isFinished = true
                    arrContactStausItmes.append(model)
                    
                    //我的证件
                    if resultModel.supplement_not_submit_num > 0 {
                        let model2 = YHContactMainItemStatusModel()
                        model2.type = 2
                        model2.isFinished = false
                        arrContactStausItmes.append(model2)
                    } else {
                        let model2 = YHContactMainItemStatusModel()
                        model2.type = 2
                        model2.isFinished = true
                        arrContactStausItmes.append(model2)
                    }
                    
                    if resultModel.my_document {
                        //我的文书
                        let model4 = YHContactMainItemStatusModel()
                        model4.type = 4
                        model4.isFinished = true
                        arrContactStausItmes.append(model4)
                    }
                   
                    if resultModel.my_signature {
                        //我的签字
                        let model5 = YHContactMainItemStatusModel()
                        model5.type = 5
                        model5.isFinished = true
                        arrContactStausItmes.append(model5)
                    }
                    
                    
                    //我的评分
                    let model3 = YHContactMainItemStatusModel()
                    model3.type = 3
                    model3.isFinished = true
                    arrContactStausItmes.append(model3)
                    
                    if resultModel.scheme_position_switch == 1 {
                        //我的方案
                        let model6 = YHContactMainItemStatusModel()
                        model6.type = 6
                        model6.isFinished = true
                        arrContactStausItmes.append(model6)
                        
                    }
                } else {
                    
                    let model = YHContactMainItemStatusModel()
                    model.type = 1
                    model.isFinished = false
                    arrContactStausItmes.append(model)
                }
                callBackBlock(true,nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code),errorMsg: json.msg.count > 0 ? json.msg : "数据错误")
                callBackBlock(false,error)
            }
            
        } failBlock: { err in
            self.arrContactStausItmes = []
            callBackBlock(false,err)
        }
    }
    
    
    
    //请求 信息表的填写状态
    func getPersonInfoFillStep( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.informationStepApi
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            guard let dic = json.data?.peel as? [String : Any],let resultModel = YHPersonInfoFillStepModel.deserialize(from: dic) else {
                self.arrInfoFillStep = []
                informationFillStepModel = nil
                callBackBlock(false,nil)
                return
            }
            
            if json.code == 200 {
                arrInfoFillStep.removeAll()
                informationFillStepModel = resultModel
                myInfoFillStep = resultModel.step   //当前正在进行的步骤
                application_type = resultModel.application_type //高才类型
                
                
                var arr : [Int] = []
                if application_type == 0 {
                    //优才
                    arr = [0,1,2,3,4,5,8]
                } else if application_type == 1 {
                    //高A
                    arr = [0,1,2,3,5]
                } else if application_type == 2 || application_type == 3 {
                    //高B、C
                    arr = [0,1,2,3,4,5]
                } else {
                    //未知
                    printLog("未处理的 订单类型 \(application_type)")
                }
                    
                let target = myInfoFillStep
                var targetIndex : Int = -1
                for (index , item) in arr.enumerated() {
                    if item == target {
                        targetIndex = index
                    }
                }
                
                self.myTargetIndex = targetIndex
                
                for (index,item) in arr.enumerated() {
                    let model = YHInformationPerfectModel()
                    model.productType = application_type
                    model.helpModel = resultModel
                    model.type = item
                    arrInfoFillStep.append(model)
                    
                    
                    if targetIndex == -1 {
                        //已完成6  或者 已提交7
                        model.isDoing = false
                        model.isFinished = true
                    } else {
                        if index < targetIndex {
                            model.isFinished = true
                        } else {
                            model.isFinished = false
                        }
                        
                        if index == targetIndex  {
                            model.isDoing = true
                        }
                    }
                }
                callBackBlock(true,nil)
            } else {
                let err : YHErrorModel = YHErrorModel(errorCode:Int32(json.code),errorMsg: json.msg)
                self.arrInfoFillStep = []
                informationFillStepModel = nil
                callBackBlock(false,err)
            }
           
        } failBlock: { err in
            self.arrInfoFillStep = []
            self.informationFillStepModel = nil
            callBackBlock(false,err)
        }
    }
    
    //提交订单信息
    func submitAllInfoOp( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.submitAllInfoApi
        let _ = YHNetRequest.postRequest(url: strUrl,params: params) {[weak self] json, code in
            //1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            guard let self = self else {
                callBackBlock(false,nil)
                return
            }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String : Any], let resultModel = YHContactInfoScoreModel.deserialize(from: dic) else {
                    callBackBlock(false,nil)
                    return
                }
                self.allInfoScoreModel = resultModel
                callBackBlock(true,nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code),errorMsg: json.msg.count > 0 ? json.msg : "数据错误")
                callBackBlock(false,error)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    
    //提交 温馨提示弹窗
    func submitSweetNotifyOp( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Users.submitSweetNotifyApi
        let _ = YHNetRequest.postRequest(url: strUrl,params: params) {[weak self] json, code in
            //1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            guard let self = self else {
                callBackBlock(false,nil)
                return
            }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String : Any], let resultModel = YHContactInfoScoreModel.deserialize(from: dic) else {
                    callBackBlock(false,nil)
                    return
                }
                self.allInfoScoreModel = resultModel
                callBackBlock(true,nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code),errorMsg: json.msg.count > 0 ? json.msg : "数据错误")
                callBackBlock(false,error)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    func getStageInformation(params:[String : Any], callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Order.stage
        let _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            guard let dic = json.data?.peel as? [String : Any],let resultModel = YHPersonInfoModel.deserialize(from: dic) else {
                callBackBlock(false,nil)
                return
            }
            if json.code == 200 {
                self.personInfoModel = resultModel
                callBackBlock(true,nil)
                
            } else {
                let err : YHErrorModel = YHErrorModel(errorCode:Int32(json.code),errorMsg: json.msg)
                callBackBlock(false,err)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
}

//其他方法
extension YHServiceCenterMainViewModel {
    //加载本地 plist数据
    private func loadLocalScoreData() {
        if let path = Bundle.main.path(forResource: "scoreOptionData", ofType: "plist") {
            if let plistData = FileManager.default.contents(atPath: path) {
                do {
                    let listDictionary = try PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as! [String: Any]
                    guard let model = YHScoreDataModel.deserialize(from: listDictionary) else {
                        localScoreData = nil
                        return
                    }
                    localScoreData = model
                } catch {
                    localScoreData = nil
                }
            } else {
                localScoreData = nil
            }
        } else {
            localScoreData = nil
        }
    }
}

//合同数据结构
struct YHContactItemHoldModel : SmartCodable {
    var orders : [YHContactItemModel] = []
}

struct YHPersonInfoModel: SmartCodable {
    var order_id : Int = 0
    var user_name : String = ""
    var stage_name : String = "身份申请"
    var sex : Int = 0
    var type : Int = 0  // 1.身份申请 2.申请结果
}
