//
//  YHGCWorkExperienceViewModel.swift
//  galaxy
//
//  Created by EDY on 2024/12/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHGCWorkExperienceViewModel: YHBaseViewModel {
    var position: YHGCWorkExperienceModel = YHGCWorkExperienceModel()
    
    override init() {
        super.init()
    }
    
    func getBaseDataSource(_ isShowPrompt: Bool) -> [YHSectionWorkExperienceModel] {
        let item = YHWorkExperienceModel(id: .id1, isNeed: true, title: "用人单位", isUserKeyBoard: false, prompts: "请输入", message: position.company_name, type: .unit, isShowPrompts: isShowPrompt, alertMessage: "请输入")
        let item1 = YHWorkExperienceModel(id: .id2, isNeed: true, title: "工作国家/地区", isUserKeyBoard: false, prompts: "请选择", message: position.location.country, type: .country, isShowPrompts: isShowPrompt, alertMessage: "请选择工作国家/地区")
        var string = ""
        let array = position.location.area
        for item in array {
            if string.count != 0 {
                string = string + "/" + item
            } else {
                string += item
            }
        }
        let item2 = YHWorkExperienceModel(id: .id3, isNeed: true, title: "工作城市", isUserKeyBoard: false, prompts: "请选择", message: string, type: .address, isShowPrompts: isShowPrompt, alertMessage: "请选择工作国家/地区")
        let item22 = YHWorkExperienceModel(id: .id4, isNeed: true, title: "工作城市", isUserKeyBoard: true, prompts: "请输入", message: position.location.foreign, isShowPrompts: isShowPrompt, alertMessage: "请输入工作国家/地区")
        let item3 = YHWorkExperienceModel(id: .id5, isNeed: true, title: "职责", isUserKeyBoard: true, prompts: "请输入", message: position.position, isShowPrompts: isShowPrompt, alertMessage: "请输入")
        let item4 = YHWorkExperienceModel(id: .id23, isNeed: true, title: "开始就职年月", isUserKeyBoard: false, prompts: "请选择", message: position.entry_time, type: .time)
        let item5 = YHWorkExperienceModel(id: .id24, isNeed: true, title: "结束就职年月", isUserKeyBoard: false, prompts: "请选择", message: position.departure_time, type: .time)
        var has_work_certificate = 2
        if position.has_work_certificate == 1 {
            has_work_certificate = 1
        } else if position.has_work_certificate == 2 {
            has_work_certificate = 0
        }
        let item6 = YHWorkExperienceModel(id: .id6, isNeed: true, title: "工作证明是否可以提供", isUserKeyBoard: false, prompts: "", message: "\(has_work_certificate)", leftButtonString: "是", rightButtonString: "否")
        let item7 = YHWorkExperienceModel(id: .id7, isNeed: true, title: "职业界别", isUserKeyBoard: false, prompts: "请选择", message: position.company_type, type: .position, isShowPrompts: isShowPrompt, alertMessage: "请选择")
        let item77 = YHWorkExperienceModel(id: .id8, isNeed: true, title: "具体经验领域", isUserKeyBoard: true, prompts: "请输入", message: position.company_type_other, isShowPrompts: isShowPrompt, alertMessage: "请输入")
       
        let addressCountry = position.location.country
        let company_type = position.company_type
        var section = YHSectionWorkExperienceModel()
        if addressCountry.contains("中国") {
            if company_type.contains("其他") {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item4, item5, item6, item7, item77])
            } else {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item4, item5, item6, item7])
            }
        } else {
            if company_type.contains("其他") {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item22, item3, item4, item5, item6, item7, item77])
            } else {
                section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item22, item3, item4, item5, item6, item7])
            }
        }

        return [section]
    }
    
    func updateCompanyModel(_ value: String) {
        position.company_name = value
    }
    
    func updateModel(_ item: YHWorkExperienceModel) {
        guard let type = item.id else { return }
        switch type {
        case .id1: // 用人单位
            position.company_name = item.message ?? ""
        case .id2: // 用人单位性质
            position.location.country = 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 .id3:
            position.location.area = item.value ?? []
        case .id4:
            position.location.foreign = item.message ?? ""
        case .id5:
            position.position = item.message ?? ""
        case .id6:
            let value = item.value?.first?.int ?? 0
            if value == 0 {
                position.has_work_certificate = 2
            } else if value == 1 {
                position.has_work_certificate = 1
            }
        case .id7:
            position.company_type = item.message ?? ""
        case .id8:
            position.company_type_other = item.message ?? ""
        default: break
        }
    }
    
    func isCanNext() -> Bool {
        let company_name = position.company_name
        let country = position.location.country
        let entry_time = position.entry_time
        let departure_time = position.departure_time
        let area = position.location.area
        let foreign = position.location.foreign
        let has_work_certificate = position.has_work_certificate
        let company_type = position.company_type
        let company_type_other = position.company_type_other
        
        guard company_name.count > 0 else { return false }
        guard country.count > 0 else { return false }
        guard entry_time.count > 0 else { return false }
        guard departure_time.count > 0 else { return false }
        guard has_work_certificate > 0 else { return false }
        guard country.count > 0 else { return false }
        if company_type == "其他" {
            guard company_type_other.count > 0 else { return false }
        }
        if country.contains("中国") {
            guard area.count > 0 else { return false }
        } else {
            guard foreign.count > 0 else { return false }
        }
        return true
    }
    
    func requestWorkPositionDetail(_ workId: Int, _ orderID: Int, callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let param: [String: Any] = ["id": workId, "order_id": orderID]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.gcworkDetail
        _ = 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 = YHGCWorkExperienceModel.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) {
        let address = ["area": position.location.area,
                       "country": position.location.country,
                       "details": position.location.details,
                       "foreign": position.location.foreign] as [String: Any]
        let country = position.location.country
        var location_aboard = 0
        if country.contains("中国") {
            location_aboard = 0
        } else {
            location_aboard = 1
        }
        let params: [String: Any] = ["id": position.id,
                                      "order_id": position.order_id,
                                      "company_name": position.company_name,
                                      "entry_time": position.entry_time,
                                      "departure_time": position.departure_time,
                                      "position": position.position,
                                      "has_work_certificate": position.has_work_certificate,
                                      "company_type": position.company_type,
                                      "company_type_other": position.company_type_other,
                                      "location": address,
                                      "location_aboard": location_aboard]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.gcWorkSave
        _ = 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
                }
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
}
