//
//  YHWorkExperiencePositionViewModel.swift
//  galaxy
//
//  Created by EDY on 2024/11/15.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHWorkExperiencePositionViewModel: YHBaseViewModel {
    var position: YHWorkExperiencePositionModel = YHWorkExperiencePositionModel()
    
    override init() {
        super.init()
    }
    
    func getBaseDataSource(_ isShowPrompt: Bool) -> [YHSectionWorkExperienceModel] {
        let item = YHWorkExperienceModel(id: .id1, isNeed: true, title: "职位名称", isUserKeyBoard: true, prompts: "请输入", message: position.position_name, isShowPrompts: isShowPrompt, alertMessage: "请输入")
        let item1 = YHWorkExperienceModel(id: .id2, isNeed: true, title: "职责性质", isUserKeyBoard: true, prompts: "请输入", message: position.wduty, isShowPrompts: isShowPrompt, alertMessage: "请输入")
        let item2 = YHWorkExperienceModel(id: .id23, isNeed: true, title: "开始就职年月", isUserKeyBoard: false, prompts: "请选择", message: position.entry_time, type: .time)
        let item3 = YHWorkExperienceModel(id: .id24, isNeed: true, title: "结束就职年月", isUserKeyBoard: false, prompts: "请选择", message: position.departure_time, type: .time)
        let item6 = YHWorkExperienceModel(id: .id5, isNeed: true, title: "经验领域", isUserKeyBoard: false, prompts: "请选择", message: position.experience_scope, type: .field, isShowPrompts: isShowPrompt, alertMessage: "请选择")
        let item66 = YHWorkExperienceModel(id: .id6, isNeed: true, title: "具体经验领域", isUserKeyBoard: true, prompts: "请输入", message: position.experience_sub_scope, type: .country, isShowPrompts: isShowPrompt, alertMessage: "请输入")
        let item11 = YHWorkExperienceModel(id: .id7, isNeed: true, title: "相关工作经验是否属于国际工作经验", isUserKeyBoard: false, prompts: "", message: "\(position.is_international_work_experience)", leftButtonString: "是", rightButtonString: "否")
        let item4 = YHWorkExperienceModel(id: .id8, isNeed: true, title: "工作国家/地区", isUserKeyBoard: false, prompts: "请选择", message: position.work_country, type: .country, isShowPrompts: isShowPrompt, alertMessage: "请选择工作国家/地区")
        let item5 = YHWorkExperienceModel(id: .id9, isNeed: true, title: "工作城市", isUserKeyBoard: false, prompts: "请选择", message: position.work_city, type: .address, isShowPrompts: isShowPrompt, alertMessage: "请选择工作国家/地区")
        let item55 = YHWorkExperienceModel(id: .id11, isNeed: true, title: "工作城市", isUserKeyBoard: true, prompts: "请输入", message: position.work_city, isShowPrompts: isShowPrompt, alertMessage: "请输入工作国家/地区")
        
        let addressCountry = position.work_country
        let experience_scope = position.experience_scope
        
        var section = YHSectionWorkExperienceModel()
        if experience_scope.contains("其他") {
            if addressCountry.contains("中国") {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item6, item66, item11, item4, item5])
            } else {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item6, item66, item11, item4, item55])
            }
            
        } else {
            if addressCountry.contains("中国") {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item6, item11, item4, item5])
            } else {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item6, item11, item4, item55])
            }
            
        }
        return [section]
    }
    
    func updateModel(_ item: YHWorkExperienceModel) {
        guard let type = item.id else { return }
        switch type {
        case .id1: // 用人单位
            position.position_name = item.message ?? ""
        case .id2: // 用人单位性质
            position.wduty = item.message ?? ""
        case .id23: // 入职年月
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM"
            if let selectDate = format.date(from: item.message ?? "") {
                let selectTimeInterval = selectDate.timeIntervalSince1970
                let currentTimeInterval = Date().timeIntervalSince1970
                if selectTimeInterval > currentTimeInterval {
                    YHHUD.flash(message: "开始就职年月不能晚于当前日期")
                } else {
                    guard let endDate = format.date(from: position.departure_time) else {
                        position.entry_time = item.message ?? ""
                        return
                    }
                    let endTimeInterval = endDate.timeIntervalSince1970
                    if selectTimeInterval > endTimeInterval {
                        YHHUD.flash(message: "开始就职年月不能晚于结束就职年月")
                    } else {
                        position.entry_time = item.message ?? ""
                    }
                }
            }
        case .id24: // 离职年月
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM"
            if let selectDate = format.date(from: item.message ?? ""), let startDate = format.date(from: position.entry_time) {
                let selectTimeInterval = selectDate.timeIntervalSince1970
                let startTimeInterval = startDate.timeIntervalSince1970
                if selectTimeInterval < startTimeInterval {
                    YHHUD.flash(message: "结束就职年月不能早于开始就职年月")
                } else {
                    position.departure_time = item.message ?? ""
                }
            } else {
                position.departure_time = item.message ?? ""
            }
            
        case .id5:
            position.experience_scope = item.message ?? ""
        case .id6:
            position.experience_sub_scope = item.message ?? ""
        case .id7:
            position.is_international_work_experience = Int(item.value?.first ?? "0") ?? 0
        case .id8:
            position.work_country = item.message ?? ""
        case .id9:
            position.work_city = item.message ?? ""
        case .id11:
            position.work_city = item.message ?? ""
        default: break
        }
    }
    
    func isCanNext() -> Bool {
        let position_name = position.position_name
        let wduty = position.wduty
        let entry_time = position.entry_time
        let departure_time = position.departure_time
        let experience_scope = position.experience_scope
        let experience_sub_scope = position.experience_sub_scope
        let is_international_work_experience = position.is_international_work_experience
        let work_country = position.work_country
        let work_city = position.work_city
        let provide_certificate_type = position.provide_certificate_type
        
        guard position_name.count > 0 else { return false }
        guard wduty.count > 0 else { return false }
        guard entry_time.count > 0 else { return false }
        guard departure_time.count > 0 else { return false }
        guard experience_scope.count > 0 else { return false }
        guard work_country.count > 0 else { return false }
        guard work_city.count > 0 else { return false }
        guard provide_certificate_type != 5 else { return false }
        if experience_scope == "其他" {
            guard experience_sub_scope.count > 0 else { return false }
        }
        return true
    }
    
    func requestWorkPositionDetail(_ workId: Int, _ positionId: Int, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let param: [String: Any] = ["work_id": workId, "position_id": positionId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.workPositionDetail
        _ = 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 = YHWorkExperiencePositionModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.position = 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 saveWorkPosition(callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        var is_location_aboard: Int = 0
        let addressCountry = position.work_country
        if addressCountry.contains("中国") {
            is_location_aboard = 1
        } else {
            is_location_aboard = 2
        }
        let params: [String: Any] = ["position_id": position.position_id,
                                      "order_id": position.order_id,
                                      "work_id": position.work_id,
                                      "position_name": position.position_name,
                                      "wduty": position.wduty,
                                      "entry_time": position.entry_time,
                                      "departure_time": position.departure_time,
                                      "experience_scope": position.experience_scope,
                                      "is_international_work_experience": position.is_international_work_experience,
                                      "work_country": position.work_country,
                                      "work_city": position.work_city,
                                      "provide_certificate_type": position.provide_certificate_type,
                                      "experience_sub_scope": position.experience_sub_scope,
                                      "is_location_aboard": is_location_aboard]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.saveWorkPosition
        _ = 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 = YHWorkExperiencePositionModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.position.position_id = result.position_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)
        }
    }
}
