//
//  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: [YHWorkExperienceProjectModel]?
    var fileList: [YHWorkExperienceFileModel] = []
    override init() {
        super.init()
    }
    
    func getBaseDataSource(_ isShowPrompt: Bool) -> [YHSectionWorkExperienceModel] {
        let item = YHWorkExperienceModel(id: .id1, isNeed: true, title: "用人单位", isUserKeyBoard: false, prompts: "请输入", message: mainModel.company_name , type: .unit, isShowPrompts: isShowPrompt, alertMessage:"请输入用人单位")
        let item1 = YHWorkExperienceModel(id: .id2, isNeed: true, title: "用人单位性质", isUserKeyBoard: false, prompts: "请输入", message: mainModel.industry, type: .nature, isShowPrompts: isShowPrompt, alertMessage:"请选择用人单位性质")
        let item2 = YHWorkExperienceModel(id: .id3, isNeed: false, title: "用人单位介绍", isUserKeyBoard: true, prompts: "如方便提供，请填写", message: mainModel.company_introduce)
        let item3 = YHWorkExperienceModel(id: .id4, isNeed: false, title: "用人单位官网", isUserKeyBoard: true, prompts: "如有，请输入官网链接", message: mainModel.company_website)
        let item4 = YHWorkExperienceModel(id: .id5, isNeed: true, title: "工作国家/地区", isUserKeyBoard: false, prompts: "请选择", message: mainModel.location.country, type: .country, isShowPrompts: isShowPrompt, alertMessage:"请选择工作国家/地区")
        var string = ""
        let array = mainModel.location.area
        for item in array {
            if string.count != 0 {
                string = string + "/" + item
            } else {
                string = string + item
            }
        }
        let item5 = YHWorkExperienceModel(id: .id6, isNeed: true, title: "工作城市", isUserKeyBoard: false, prompts: "请选择", message: string, type: .address, isShowPrompts: isShowPrompt, alertMessage:"请选择工作国家/地区")
        let item55 = YHWorkExperienceModel(id: .id7, isNeed: true, title: "工作城市", isUserKeyBoard: true, prompts: "请输入", message: mainModel.location.foreign, isShowPrompts: isShowPrompt, alertMessage:"请输入工作国家/地区")
        let item6 = YHWorkExperienceModel(id: .id8, isNeed: true, title: "职位", isUserKeyBoard: true, prompts: "请输入", message: mainModel.position, isShowPrompts: isShowPrompt, alertMessage:"请输入职位")
        let item7 = YHWorkExperienceModel(id: .id9, isNeed: true, title: "入职年月", isUserKeyBoard: false, prompts: "请选择", message: mainModel.entry_time, type: .time, isShowPrompts: isShowPrompt, alertMessage:"请选择入职年月")
        let item8 = YHWorkExperienceModel(id: .id10, isNeed: true, title: "离职年月", isUserKeyBoard: false, prompts: "请选择", message: mainModel.departure_time, type: .time, isShowPrompts: isShowPrompt, alertMessage:"请选择离职年月")
        let item9 = YHWorkExperienceModel(id: .id11, isNeed: true, title: "工作证明文件", isUserKeyBoard: false, prompts: "请选择", message: mainModel.work_certificate, type: .certificate, isShowPrompts: isShowPrompt, alertMessage:"请选择工作证明文件")
        let item10 = YHWorkExperienceModel(id: .id12, isNeed: true, title: "职责性质", isUserKeyBoard: true, prompts: "请选择", message: mainModel.duty, isShowPrompts: isShowPrompt, alertMessage:"请输入职责性质")
        let item11 = YHWorkExperienceModel(id: .id13, isNeed: false, title: "相关工作经验是否属于国际工作经验", isUserKeyBoard: false, prompts: "", message: "\(mainModel.international_work_experience)", leftButtonString: "是", rightButtonString: "否")
        let addressCountry = mainModel.location.country
        var section = YHSectionWorkExperienceModel()
        if addressCountry.contains("中国") {
            section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11])
        } else {
            section = YHSectionWorkExperienceModel(title: "企业信息", models: [item, item1, item2, item3, item4, item55, item6, item7, item8, item9, item10, item11])
        }
        
        let item12 = YHWorkExperienceModel(id: .id14, isNeed: true, title: "企业人数规模", isUserKeyBoard: true, prompts: "请输入", message: "\(mainModel.company_member_total)", isShowPrompts: isShowPrompt, alertMessage:"请输入企业人数规模")
        let item13 = YHWorkExperienceModel(id: .id15, isNeed: false, title: "行政架构层级", isUserKeyBoard: false, prompts: "请输入", message: "\(mainModel.administrative_level)", type: .structure)
        let item14 = YHWorkExperienceModel(id: .id16, isNeed: true, title: "下属管理人数", isUserKeyBoard: true, prompts: "请输入", message: "\(mainModel.company_manage_total)", isShowPrompts: isShowPrompt, alertMessage:"请输入下属管理人数")
        let item15 = YHWorkExperienceModel(id: .id17, isNeed: false, title: "公司营业额/港元 (近一年)", isUserKeyBoard: true, prompts: "请输入具体数字", message: "\(mainModel.turnover)")
        let item16 = YHWorkExperienceModel(id: .id18, isNeed: false, title: "公司业务性质/范畴/所属行业", isUserKeyBoard: true, prompts: "请输入，100字内", message: mainModel.business_nature)
        let item17 = YHWorkExperienceModel(id: .id19, isNeed: true, title: "职位水平类别", isUserKeyBoard: false, prompts: "请选择", message: "\(mainModel.professional_level)", type: .level, isShowPrompts: isShowPrompt, alertMessage:"请选择职位水平类别")
        let item18 = YHWorkExperienceModel(id: .id20, isNeed: true, title: "高管证明文件", isUserKeyBoard: false, prompts: "请选择", message: mainModel.executives_certificate, type: .prove, isShowPrompts: isShowPrompt, alertMessage:"请选择高管证明文件")
        let item19 = YHWorkExperienceModel(id: .id21, isNeed: true, title: "高管在职开始时间", isUserKeyBoard: false, prompts: "请选择", message: mainModel.top_manager_start_at, type: .time, isShowPrompts: isShowPrompt, alertMessage:"请选择高管在职开始时间")
        let item20 = YHWorkExperienceModel(id: .id22, isNeed: true, title: "高管在职结束时间", isUserKeyBoard: false, prompts: "请选择", message: mainModel.top_manager_end_at, type: .time, isShowPrompts: isShowPrompt, alertMessage:"请选择高管在职结束时间")
        var section1 = YHSectionWorkExperienceModel()
        if mainModel.professional_level == 1 {
            section1 = YHSectionWorkExperienceModel(title: "企业规模", models: [item12, item13, item14, item15, item16, item17, item18, item19, item20])
        } else {
            section1 = YHSectionWorkExperienceModel(title: "企业规模", models: [item12, item13, item14, item15, item16, item17])
        }
        
        return [section, section1]
    }
    
    func updateModel(_ item: YHWorkExperienceModel) {
        guard let type = item.id else { return }
        switch type {
        
        case .id1: // 用人单位
            mainModel.company_name = item.message ?? ""
        case .id2: // 用人单位性质
            mainModel.industry = item.message ?? ""
        case .id3: // 用人单位介绍
            mainModel.company_introduce = item.message ?? ""
        case .id4: // 用人单位官网
            mainModel.company_website = item.message ?? ""
        case .id5: // 工作地区国家
            mainModel.location.country = item.message ?? ""
        case .id6: // 工作城市 国内
            mainModel.location.area = item.value ?? []
        case .id7: // 工作城市国外
            mainModel.location.foreign = item.message ?? ""
        case .id8: // 职位
            mainModel.position = item.message ?? ""
        case .id9: // 入职年月
            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: mainModel.departure_time) else {
                        mainModel.entry_time = item.message ?? ""
                        return
                    }
                    let endTimeInterval = endDate.timeIntervalSince1970
                    if selectTimeInterval > endTimeInterval {
                        YHHUD.flash(message: "入职日期不能晚于离职日期")
                    } else {
                        mainModel.entry_time = item.message ?? ""
                    }
                }
            }
        case .id10: // 离职年月
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM"
            if let selectDate = format.date(from:item.message ?? ""), let startDate = format.date(from:mainModel.entry_time) {
                let selectTimeInterval = selectDate.timeIntervalSince1970
                let startTimeInterval = startDate.timeIntervalSince1970
                if selectTimeInterval < startTimeInterval {
                    YHHUD.flash(message: "离职日期不能早于入职日期")
                } else {
                    mainModel.departure_time = item.message ?? ""
                }
            } else {
                mainModel.departure_time = item.message ?? ""
            }
        case .id11: // 工作证明文件
            mainModel.work_certificate = item.message ?? ""
        case .id12: // 职责性质
            mainModel.duty = item.message ?? ""
        case .id13: // 是否国际工作经验
            mainModel.international_work_experience = Int(item.value?.first ?? "0") ?? 0
        case .id14: // 企业人数规模
            mainModel.company_member_total = Int(item.message ?? "0") ?? 0
        case .id15: // 行政架构层级
            mainModel.administrative_level = Int(item.value?.first ?? "0") ?? 0
        case .id16: // 下属管理人数
            mainModel.company_manage_total = Int(item.message ?? "0") ?? 0
        case .id17: // 公司营业额/港元
            mainModel.turnover = Int(item.message ?? "0") ?? 0
        case .id18: // 公司性质/范畴/所属行业
            mainModel.business_nature = item.message ?? ""
        case .id19: // 职位水平类型
            mainModel.professional_level = Int(item.value?.first ?? "0") ?? 0
        case .id20: // 高管证明文件
            mainModel.executives_certificate = item.message ?? ""
        case .id21: // 高管在职开始时间
            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: mainModel.top_manager_end_at) else {
                        mainModel.top_manager_start_at = item.message ?? ""
                        return
                    }
                    let endTimeInterval = endDate.timeIntervalSince1970
                    if selectTimeInterval > endTimeInterval {
                        YHHUD.flash(message: "高管在职开始时间不能晚于离职日期")
                    } else {
                        mainModel.top_manager_start_at = item.message ?? ""
                    }
                }
            }
        case .id22: // 高管在职结束时间
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM"
            if let selectDate = format.date(from:item.message ?? ""), let startDate = format.date(from:mainModel.top_manager_start_at) {
                let selectTimeInterval = selectDate.timeIntervalSince1970
                let startTimeInterval = startDate.timeIntervalSince1970
                if selectTimeInterval < startTimeInterval {
                    YHHUD.flash(message: "高管在职结束时间不能早于开始日期")
                } else {
                    mainModel.top_manager_end_at = item.message ?? ""
                }
            } else {
                mainModel.top_manager_end_at = item.message ?? ""
            }
        }
    }
    
    func updateModel(_ item: YHCompanyModelListModel) {
        mainModel.company_name = item.company_name ?? ""
        mainModel.company_introduce = item.company_introduce ?? ""
        mainModel.company_website = item.company_link ?? ""
    }
    
    func updateWduty(_ value: String) {
        mainModel.wduty = value
    }
    
    func updateHighlights(_ value: String) {
        mainModel.highlights = value
    }
    
    func updateIsProjectIntroduction(isOn: Bool) {
        if isOn {
            mainModel.is_project_introduction = 1
        } else {
            mainModel.is_project_introduction = 0
        }
    }
    
    func updateNotNeedUploadFile(value: Int) {
        mainModel.not_need_upload_file = value
    }
    
    func requestWorkExample(callBackBlock:@escaping (_ success: Bool?, _ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.example
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                let dic = json.data
                guard let result = [YHWorkExampleModel].deserialize(from: dic as? [Any]) 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(_ workId: String, callBackBlock:@escaping (_ success: Bool?, _ error:YHErrorModel?)->()) {
//        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.detail + "?id=\(workId)"
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.detail
        let param: [String: Any] = ["id": workId]
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: param) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                let dic = json.data
                guard let result = YHWorkExperienceDetailModel.deserialize(from: dic as? Dictionary) 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)
        }
    }
    
    // 0保存 1下一步
    func saveWorkDetail(_ saveType: Int, orderID: Int, callBackBlock:@escaping (_ success: Bool?, _ error:YHErrorModel?)->()) {
        if mainModel.location.country.contains("中国") {
            mainModel.location_aboard = 0
        } else {
            mainModel.location_aboard = 1
        }
        
        let area: [String] = mainModel.location.area
        let location = ["area": area,
                        "country": mainModel.location.country,
                        "details": mainModel.location.details,
                        "foreign": mainModel.location.foreign] as [String : Any]
        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] = ["administrative_level": mainModel.administrative_level,
                    "business_nature": mainModel.business_nature,
                    "business_remark":mainModel.business_remark,
                    "company_introduce": mainModel.company_introduce,
                    "company_manage_total": mainModel.company_manage_total,
                    "company_member_total": mainModel.company_member_total,
                    "company_name": mainModel.company_name,
                    "company_website": mainModel.company_website,
                    "create_from_appid": mainModel.create_from_appid,
                    "created_at": mainModel.created_at,
                    "customer_center_id": mainModel.customer_center_id,
                    "deleted_at": mainModel.deleted_at,
                    "departure_time": mainModel.departure_time,
                    "duty": mainModel.duty,
                    "entry_time": mainModel.entry_time,
                    "executives_certificate": mainModel.executives_certificate,
                    "file": file,
                    "highlights": mainModel.highlights,
                    "id": mainModel.id,
                    "order_id": orderID,
                    "industry": mainModel.industry,
                    "international_work_experience": mainModel.international_work_experience,
                    "is_executives": mainModel.is_executives,
                    "is_famous_enterprise": mainModel.is_famous_enterprise,
                    "is_project_introduction": mainModel.is_project_introduction,
                    "is_show": mainModel.is_show,
                    "is_synthetic": mainModel.is_synthetic,
                    "location": location,
                    "location_aboard": mainModel.location_aboard,
                    "master_of_important_project": mainModel.master_of_important_project,
                    "match_listing": mainModel.match_listing,
                    "not_need_upload_file": mainModel.not_need_upload_file,
                    "old_id": mainModel.old_id,
                    "operator_english_name": mainModel.operator_english_name,
                    "operator_id": mainModel.operator_id,
                    "operator_name": mainModel.operator_name,
                    "position": mainModel.position,
                    "professional_level": mainModel.professional_level,
                    "professional_other": mainModel.professional_other,
                    "projects": [],
                    "remark": mainModel.remark,
                    "step": mainModel.step,
                    "top_manager_end_at": mainModel.top_manager_end_at,
                    "top_manager_start_at": mainModel.top_manager_start_at,
                    "turnover": mainModel.turnover,
                    "update_from_appid": mainModel.update_from_appid,
                    "updated_at": mainModel.updated_at,
                    "wduty": mainModel.wduty,
                    "work_certificate": mainModel.work_certificate,
                    "verify": saveType
                    ]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.save
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, code in
            guard let self = self else { return }
            if json.code == 200 {
                let dic = json.data
                guard let result = YHWorkExperienceDetailModel.deserialize(from: dic as? Dictionary) 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?)->()){
//        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]
        let _ = YHNetRequest.getRequest(url: strUrl,params: param) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                let dic = json.data
                guard let resultArray = [YHWorkExperienceProjectModel].deserialize(from: dic as? [Any]) else {
                    callBackBlock([],nil)
                    return
                }
                self.projectModels = resultArray as? [YHWorkExperienceProjectModel]
                callBackBlock(self.projectModels, nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock([], error)
            }
        } failBlock: { err in
            callBackBlock([],err)
        }
    }
    
    func requestDeleteWorkExperienceProject(_ orderId: String, callBackBlock:@escaping (_ success: Bool?, _ error:YHErrorModel?)->()) {
        let params: [String : Any] = ["id": orderId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.projectDel
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, code 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?)->()) {
//        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]
        let _ = YHNetRequest.postRequest(url: strUrl,params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                let dic = json.data
                guard let result = YHFileContent.deserialize(from: dic as? Dictionary) 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?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.WorkExperience.fileList
        let params: [String : Any] = ["order_id": orderId]
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                let dic = json.data
                guard let result = [YHWorkExperienceFileModel].deserialize(from: dic as? [Any]) 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 industry = mainModel.industry //用人单位性质
            let country = mainModel.location.country //工作国家
            let area = mainModel.location.area //工作城市
            let foreign = mainModel.location.foreign //工作城市 国外
            let entryTime = mainModel.entry_time //入职年月
            let departureTime = mainModel.departure_time //离职年月
            let workCertificate = mainModel.work_certificate //工作证明文件
            let duty = mainModel.duty //职责性质
            let companyMemberTotal = mainModel.company_member_total //企业人数规模
            let companyManageTotal = mainModel.company_manage_total //下属管理人数
            let professionalLevel = mainModel.professional_level //职位水平类别
            let executivesCertificate = mainModel.executives_certificate //高管证明文件
            let topManagerStartAt = mainModel.top_manager_start_at //高管在职开始时间
            let topManagerEndAt = mainModel.top_manager_end_at //高管在职开始时间
            guard companyName.count > 0 else { return false }
            guard industry.count > 0 else { return false }
            guard country.count > 0 else { return false }
            guard entryTime.count > 0 else { return false }
            guard workCertificate.count > 0 else { return false }
            guard duty.count > 0 else { return false }
            guard companyMemberTotal > 0 else { return false }
            guard companyManageTotal > 0 else { return false }
            guard professionalLevel > 0 else { return false }
            if country.contains("中国") {
                guard area.count > 0 else { return false }
            } else {
                guard foreign.count > 0 else { return false }
            }
            if professionalLevel == 1 {
                guard executivesCertificate.count > 0 else { return false }
                guard topManagerStartAt.count > 0 else { return false }
                guard topManagerEndAt.count > 0 else { return false }
            }
            return true
        } else if step == 1 {
            let message = mainModel.wduty
            guard message.count > 0 else { return false }
            return true
        } else if step == 2 {
            let message = mainModel.highlights
            guard message.count > 0 else { return false }
            return true
        } else if step == 3 {
            return true
        } else {
            return true
        }
    }
}
