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

import UIKit
import GKNavigationBarSwift
/*
 基本资料信息填写
 */

class YHBasicInfoFillViewController: YHBaseViewController {
    var orderId : Int?
    private let basicInfoVM : YHBasicInfoFillViewModel = YHBasicInfoFillViewModel()
    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(YHBasicInfoFillCell.self,forCellReuseIdentifier: YHBasicInfoFillCell.cellReuseIdentifier)
        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.0
        initView()
        
        //2.0
        loadData()
    }
}

// MARK: - private methods
extension YHBasicInfoFillViewController {
    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)
        }
    }
    
    private func loadData() {
        guard let orderId = orderId else { return}
        let param = ["order_id":orderId]
        basicInfoVM.getBasicInfo(params: param) { success, error in
            if success == true {
                self.homeTableView.reloadData()
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "发生错误,请重试")
                self.navigationController?.popViewController(animated: true)
            }
            self.homeTableView.reloadData()
        }
    }
    
    
    private func saveData() {
        //保存
        submitAndSaveDataOp(isSaveFlag: true)
    }
    
    private func submitData() {
        //提交
        //1.校验
        if dataIsOK() == true {
            //提交数据
            submitAndSaveDataOp(isSaveFlag: false)
        } else {
            homeTableView.reloadData()
            YHHUD.flash(message: "您还有信息未填写")
        }
    }
    
    //检查数据是否合法
    private func dataIsOK() -> Bool {
        var returnValue : Bool = true
        
        let arr = basicInfoVM.arrBasicInfoSessionDataForEdit
        for item in arr {
            for (_,item0) in item.arrQuestionItem.enumerated() {
                if (item0.answer == "Y" && item0.info.count < 1) || item0.answer == "" {
                    item0.needCheckFlag = true
                    returnValue = returnValue && false
                }
            }
        }
        return returnValue
    }
    
    private func submitAndSaveDataOp(isSaveFlag :  Bool) {
        //保存
        let arr = basicInfoVM.arrBasicInfoSessionDataForEdit
        
        
        var param : [String : Any] = ["order_id":orderId as Any,"save_type": isSaveFlag ? "save" : "submit"]
        
        for item in arr {
            if item.sessionTitle == "主申请人" {
                var applicant : [String : Any] = [:]
                for (index0,item0) in item.arrQuestionItem.enumerated() {
                    if index0 == 0 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "has_conviction")
                    }
                    else if index0 == 1 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "has_departure")
                    }
                    else if index0 == 2 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "has_deny")
                    }
                    else if index0 == 3 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "has_breaking_law")
                    }
                    else if index0 == 4 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "has_other_id")
                    } else {
                        printLog("其他数据没有处理")
                    }
                }
                applicant.updateValue(basicInfoVM.dataModelForBasicInfo?.applicant?.id ?? 0, forKey: "id")
                param.updateValue(applicant, forKey: "applicant")
            } else if item.sessionTitle == "配偶" {
                var applicant : [String : Any] = [:]
                for (index0,item0) in item.arrQuestionItem.enumerated() {
                    if index0 == 0 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "child_departure")
                    } else if index0 == 1 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "child_deny")
                    } else {
                        printLog("其他数据没有处理")
                    }
                }
                applicant.updateValue(basicInfoVM.dataModelForBasicInfo?.spouse?.id ?? 0, forKey: "id")
                applicant.updateValue(basicInfoVM.dataModelForBasicInfo?.spouse?.subset_name ?? 0, forKey: "subset_name")
                param.updateValue(applicant, forKey: "spouse")
            } else if item.sessionTitle.hasPrefix("子女") {
                var arr : [[String:Any]] = []
                if let tArr = param["child"] as? [[String : Any]] {
                    arr = tArr
                }
                
                var applicant : [String : Any] = [:]
                for (index0,item0) in item.arrQuestionItem.enumerated() {
                    if index0 == 0 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "child_departure")
                    } else if index0 == 1 {
                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
                        applicant.updateValue(value, forKey: "child_deny")
                    } else {
                        printLog("其他数据没有处理")
                    }
                }
                
                applicant.updateValue(item.model?.id ?? 0, forKey: "id")
                applicant.updateValue(item.model?.subset_name ?? "", forKey: "subset_name")
                arr.append(applicant)
                
                param.updateValue(arr, forKey: "child")
            }
//            else if item.sessionTitle == "家庭背景" {
//                var applicant : [String : Any] = [:]
//                for (index0,item0) in item.arrQuestionItem.enumerated() {
//                    if index0 == 0 {
//                        let value = ["has":item0.answer,"info":item0.answer == "Y" ? item0.info : ""]
//                        applicant.updateValue(value, forKey: "background_member")
//                    } else {
//                        printLog("其他数据没有处理")
//                    }
//                }
//                param.updateValue(applicant, forKey: "background")
//            }
            else {
                
            }
        }
        
        printLog(param)
        
        self.basicInfoVM.saveBasicInfo(params: param) {[weak self] success, error in
            if success == true {
                let title = isSaveFlag ? "保存成功" : "提交成功"
                YHHUD.flash(message: title)
                
                if isSaveFlag == false {
                    self?.navigationController?.popViewController(animated: true)
                }
            } else {
                
                let title = isSaveFlag ? "保存失败" : "提交失败"
                let msg = error?.errorMsg ?? title
                YHHUD.flash(message: msg)
            }
        }
    }
}

// MARK: - delegates
// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHBasicInfoFillViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return basicInfoVM.arrBasicInfoSessionDataForEdit.count
    }
    
    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: YHBasicInfoFillCell.self)
        cell.dataModel = basicInfoVM.arrBasicInfoSessionDataForEdit[indexPath.section]
        cell.indexPath = indexPath
        cell.block = { indexPath in
            if let indexPath = indexPath {
                tableView.reloadRows(at: [indexPath], with: .none)
            }
        }
        return cell
    }
}
