//
//  YHWorkExperienceViewModel.swift
//  galaxy
//
//  Created by EDY on 2024/2/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Alamofire

class YHWorkExperienceViewModel: YHBaseViewModel {
    var mainModel: YHWorkExperienceDetailModel = YHWorkExperienceDetailModel()
    var exampleModels: [YHWorkExampleModel]?
    var projectModels: [YHWorkExperienceProjectListModel] = []
    var fileList: [YHWorkExperienceFileModel] = []
    var positionList: [YHWorkExperiencePositionModel] = []
    var stepModel: YHWorkExperienceStepModel = YHWorkExperienceStepModel()
    var dutyModel: YHWorkExperienceDetailModel = YHWorkExperienceDetailModel()
    var helightModel: YHWorkExperienceDetailModel = YHWorkExperienceDetailModel()
    override init() {
        super.init()
    }
    
    func getBaseDataSource(_ isShowPrompt: Bool) -> [YHSectionWorkExperienceModel] {
        let item = YHWorkExperienceModel(id: .id1, isNeed: true, title: "用人单位", isUserKeyBoard: true, prompts: "请输入", message: mainModel.company_name, isShowPrompts: isShowPrompt, alertMessage: "请输入")
        let item1 = YHWorkExperienceModel(id: .id2, isNeed: true, title: "公司基本情况", isUserKeyBoard: false, prompts: "请选择", message: "\(mainModel.has_finish_basic_question)", type: .company, isShowPrompts: isShowPrompt, alertMessage: "请选择")
        let item2 = YHWorkExperienceModel(id: .id3, isNeed: true, title: "职位水平类别", isUserKeyBoard: false, prompts: "请选择", message: "\(mainModel.professional_level)", type: .level, isShowPrompts: isShowPrompt, alertMessage: "请选择")
        var section = YHSectionWorkExperienceModel()
        section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2])
        return [section]
    }
    
    func updateModel(_ item: YHWorkExperienceModel) {
        guard let type = item.id else { return }
        switch type {
            
        case .id1: // 用人单位
            mainModel.company_name = item.message ?? ""
        case .id2: // 用人单位性质
            mainModel.has_finish_basic_question = 1
        case .id3: // 职位水平类型
            mainModel.professional_level = Int(item.value?.first ?? "0") ?? 0
        default: break
        }
    }
    
    func updateWduty(_ value: String) {
        dutyModel.work_duty = value
    }
    
    func updateHighlights(_ value: String) {
        helightModel.work_highlights = value
    }
    
    func requestWorkExample(callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.example
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [Any], let result = [YHWorkExampleModel].deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.exampleModels = result as? [YHWorkExampleModel]
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func requestWorkDetail(_ orderId: String, _ workId: String, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
//        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.detail + "?id=\(workId)"
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.detail
        let param: [String: Any] = ["work_id": workId, "order_id": orderId]
        
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceDetailModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.mainModel = result
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func requestWorkStep(_ orderId: String, _ workId: String, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
//        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.detail + "?id=\(workId)"
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.workStep
        let param: [String: Any] = ["work_id": workId, "order_id": orderId]
        
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceStepModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.stepModel = result
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    // 0保存 1下一步
    func saveWorkDetail(workId: Int, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        var file: [[String: Any]] = []
        for item in mainModel.file {
            let fileDic = ["fileName": item.fileName,
                           "fileUrl": item.fileUrl,
                           "uploadedAt": item.uploadedAt]
            file.append(fileDic)
        }
        let params: [String: Any] = ["next_step": 0,
                                      "work_id": workId,
                                      "file_list": file
                                     ]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.save
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceDetailModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
//                self.mainModel.id = result.id
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func requestWorkInfoProject(_ workId: String, callBackBlock: @escaping (_ success: [YHWorkExperienceProjectModel]?, _ error: YHErrorModel?) -> Void) {
//        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.projectList + "?work_id=\(workId)"
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.projectList
        let param: [String: Any] = ["work_id": workId]
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceProjectModel.deserialize(from: dic) else {
                    callBackBlock([], nil)
                    return
                }
                self.mainModel.file = result.list
                callBackBlock([], nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock([], error)
            }
        } failBlock: { err in
            callBackBlock([], err)
        }
    }
    
    func requestDeleteWorkPosition(_ model: YHWorkExperiencePositionModel, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["position_id": model.position_id, "work_id": model.work_id]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.deleteWorkPosition
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func requestFileMessage(_ url: String, callBackBlock: @escaping (_ success: Bool, _ model: YHFileContent?, _ error: YHErrorModel?) -> Void) {
//        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.ocrFileContent + "?file_url=\(url)"
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OCR.normal
        let params: [String: Any] = ["url": url]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHFileContent.deserialize(from: dic) else {
                    callBackBlock(false, nil, nil)
                    return
                }
                callBackBlock(true, result, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, nil, error)
            }
        } failBlock: { err in
            callBackBlock(false, nil, err)
        }
    }
    
    func requestFileList(_ orderId: Int, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.fileList
        let params: [String: Any] = ["order_id": orderId]
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [Any], let result = [YHWorkExperienceFileModel].deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                let last = result.compactMap { $0 }
                self.fileList = last
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func isCanNext(_ step: Int) -> Bool {
        if step == 0 {
            let companyName = mainModel.company_name // 公司名称
            let professional_level = mainModel.professional_level
            let work_certificate = mainModel.work_certificate
            guard companyName.count > 0 else { return false }
            guard professional_level > 0 else { return false }
            guard work_certificate.count > 0 else { return false }
            return true
        } else if step == 1 {
            let message = dutyModel.work_duty
            guard message.count > 0 else { return false }
            return true
        } else if step == 2 {
            let message = helightModel.work_highlights
            guard message.count > 0 else { return false }
            return true
        } else {
            return true
        }
    }
    
    func requestWorkPositionList(_ orderId: String, _ workId: String, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let param: [String: Any] = ["work_id": workId, "order_id": orderId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.workPositionList
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [Any], let result = [YHWorkExperiencePositionModel].deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.positionList = result
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func saveWorkData(_ orderId: Int, workId: Int, _ step: Int = 1, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["order_id": orderId,
                                      "work_id": workId,
                                      "company_name": mainModel.company_name,
                                      "professional_level": mainModel.professional_level,
                                      "work_certificate": mainModel.work_certificate,
                                      "next_step": step
                                     ]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.saveWorkData
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceDetailModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.mainModel.work_id = result.work_id
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func requestworkDutyDetail(_ workId: String, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
//        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.detail + "?id=\(workId)"
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.workDutyDetail
        let param: [String: Any] = ["work_id": workId]
        
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceDetailModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.dutyModel = result
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func saveWorkDuty(workId: Int, _ step: Int = 2, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["work_id": workId,
                                      "work_duty": dutyModel.work_duty,
                                      "next_step": step
                                     ]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.saveWorkDuty
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceDetailModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.mainModel.work_id = result.work_id
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func requestWorkHighlightsDetail(_ workId: String, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
//        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.detail + "?id=\(workId)"
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.workHighlightsDetail
        let param: [String: Any] = ["work_id": workId]
        
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceDetailModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.helightModel = result
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func saveWorkHighlights(workId: Int, _ step: Int = 4, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["work_id": workId,
                                      "work_highlights": helightModel.work_highlights,
                                      "next_step": 4
                                     ]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.saveWorkHighlights
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHWorkExperienceDetailModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.mainModel.work_id = result.work_id
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
}
