//
//  YHOtherInfoFillViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/2/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import GKNavigationBarSwift
/*
 其他信息
 */

class YHOtherInfoFillViewController: YHBaseViewController {
    var orderId : Int?
    private let otherInfoVM : YHOtherInfoFillViewModel = YHOtherInfoFillViewModel()
    var homeTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style:.grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(YHOtherInfoFillCell.self,forCellReuseIdentifier: YHOtherInfoFillCell.cellReuseIdentifier)
        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.0
        initView()
        
        //2.0
        loadData()
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - private methods
extension YHOtherInfoFillViewController {
    private func initView() {
        gk_backStyle = .black
        gk_navTitle = "其他信息填写"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1
        
        let bottomView = YHBasicInfoFillBottomView()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(YHBasicInfoFillBottomView.viewH)
        }
        
        bottomView.block = { tag in
            if tag == 0 {
                //点击了保存按钮                
                printLog("点击了保存按钮")
                self.saveData()
            } else {
                //点击了提交按钮
                printLog("点击了提交按钮")
                self.submitData()
            }
        }
        
        
        homeTableView.delegate = self
        homeTableView.dataSource = self
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
        }
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(didRevModelChanged(_:)), name: Notification.Name(rawValue: "com.yinhe.myCertificate.wechat.otherInfo_remark_notification"), object: nil)
    }
    
    @objc func didRevModelChanged(_ notification: Notification) {
        if let model = notification.object as? LanguageDetailModel {
            printLog(model)
            if let tModel = otherInfoVM.otherInfoFillData,tModel.language_detail_new.count > 0 {
                
                for(index,item) in tModel.language_detail_new_data.enumerated() {
                    if item.id == model.id {
                        tModel.language_detail_new_data[index] = model
                        break
                    }
                }
            }
        }
    }
    
    
    private func loadData() {
        guard let orderId = orderId else { return}
        let param = ["order_id":orderId]
        otherInfoVM.getOtherInfo(params: param) { success, error in
            if success == true {
                self.homeTableView.reloadData()
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "发生错误,请重试")
            }
            self.homeTableView.reloadData()
        }
    }
    
    
    private func saveData() {
        //保存
        submitDataOp(flag: false)
    }
    
    private func submitData() {
        //提交
        if dataIsOK() == true {
            submitDataOp(flag: true)
        } else {
            
            let model = otherInfoVM.otherInfoFillData
            model?.needCheckFlag = true
            
            YHHUD.flash(message: "您还有信息未填写")
            homeTableView.reloadData()
        }
    }
    
    private func submitDataOp(flag : Bool) {
        //提交
        let model = otherInfoVM.otherInfoFillData
        var tID = 0
        if let arrr = model?.language_detail_new_data,arrr.count > 0 {
            var arrO : [LanguageDetailNew] = []
            for(_,item) in arrr.enumerated() {
                tID = 0
                if item.select {
                    let fakeData : LanguageDetailNew = LanguageDetailNew()
                    
                    if let arr = model?.language_detail_new,arr.count > 0 {
                        for(_,tttt) in arr.enumerated() {
                            if tttt.first_select == item.id {
                                tID = tttt.id
                            }
                        }
                    }
                    fakeData.id = tID
                    
                    fakeData.first_select = item.id
                    fakeData.other_instructions = item.other_instructions
                    
                    arrO.append(fakeData)
                    
                    var isFirst : Bool = true
                    for(_,tt) in item.options.enumerated() {
                        
                        if tt.select {
                            
                            if isFirst {
                                fakeData.second_select = String(tt.id)
                                isFirst = false
                            } else {
                                fakeData.second_select = fakeData.second_select + "," + String(tt.id)
                            }
                        }
                    }
                }
            }
            model?.language_detail_new = arrO
        } else {
            model?.language_detail_new = []
        }
        
        model?.is_update = flag
        //保存
        if let param = model?.toDictionary() {
            
            printLog("param ==>")
            printLog(param)
            
            otherInfoVM.saveOtherInfo(params: param) { success, error in
                if success == true {
                    
                    let msg = flag ? "提交成功" : "保存成功"
                    
                    YHHUD.flash(message:msg)
                    if flag == true {
                        self.navigationController?.popViewController(animated: true)
                    }
                } else {
                    
                    let tips = flag ? "提交失败" : "保存失败"
                    let msg = error?.errorMsg ?? tips
                    YHHUD.flash(message: msg)
                }
            }
        } else {
            printLog("error:  参数 转换 出错")
        }
    }
    
    
    //检查数据是否合法
    private func dataIsOK() -> Bool {
        var returnValue : Bool = true
        if let model = otherInfoVM.otherInfoFillData {
//            //1.居住信息
//            for item in model.residences {
//                if item.country.isEmpty || item.start_time.isEmpty || item.end_time.isEmpty {
//                    returnValue = false
//                    return returnValue
//                }
//            }
            
//            //2.语言水平
//            if model.language_detail?.levelDes.isEmpty == true {
//                returnValue = false
//                return returnValue
//            } else {
//                if let language = model.language_detail,language.level == 4 {
//                    if language.name.isEmpty || language.remark.isEmpty {
//                        returnValue = false
//                        return returnValue
//                    }
//                }
//                
//            }
            
            if !model.language_detail_new_data.isEmpty {
                var mutilFlag : Bool = false
                for(_,item) in model.language_detail_new_data.enumerated() {
                    mutilFlag  = item.select || mutilFlag
                }
                
                if !mutilFlag {
                    return false
                }
                
                for(_,item) in model.language_detail_new_data.enumerated() {
                    if item.select {
                        if item.id == 3,item.other_instructions.isEmpty {
                            return false
                        }
                        
                        var singleFlag : Bool = false
                        for(_,iitem) in item.options.enumerated() {
                            singleFlag = singleFlag || iitem.select
                        }
                        
                        if !singleFlag {
                            return false
                        }
                    }
                }
                
                if !mutilFlag {
                    return false
                }
            }
            
            //3.专业技能行业
            if model.profession?.optionDes.isEmpty == true {
                returnValue = false
                return returnValue
            }  else {
                if let language = model.profession,language.option == 15 {
                    if language.remark.isEmpty {
                        returnValue = false
                        return returnValue
                    }
                }
                
            }
            
            //4.辅助资料
            if let model = model.question {
                //问题1
                if model.professional_qualification < 1 {
                    returnValue = false
                    return returnValue
                }
                //问题2
                if model.paper < 1 {
                    returnValue = false
                    return returnValue
                }
                //问题3
                if model.scholarship < 1 {
                    returnValue = false
                    return returnValue
                }
                //问题4
                if model.media_interview < 1 {
                    returnValue = false
                    return returnValue
                }
            }
        }
        return returnValue
    }
}

// MARK: - delegates
// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHOtherInfoFillViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 15
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 15))
        view.backgroundColor = .clear
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHOtherInfoFillCell.self)
        cell.selectionStyle = .none
        cell.block = {
            self.homeTableView.reloadData()
        }
        cell.dataModel = otherInfoVM.otherInfoFillData
        return cell
    }
}
