//
//  YHGCBasicInfoFillViewController.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/12.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHGCBasicInfoFillViewController: YHBaseViewController {
    var orderId: Int?
    private let basicInfoVM: YHGCBasicInfoFillViewModel = YHGCBasicInfoFillViewModel()
    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 YHGCBasicInfoFillViewController {
    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] = ["orderId": orderId ?? 0, "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 {
                        if item0.answer == "Y" {
                            applicant.updateValue(item0.info.count > 0 ? 1 : 2, forKey: "deny")
                            applicant.updateValue(item0.info, forKey: "denyContent")
                        } else if item0.answer == "N" {
                            applicant.updateValue(0, forKey: "deny")
                            applicant.updateValue("", forKey: "denyContent")
                        }
                    } else if index0 == 1 {
                        if item0.answer == "Y" {
                            applicant.updateValue(item0.info.count > 0 ? 1 : 2, forKey: "crime")
                            applicant.updateValue(item0.info, forKey: "crimeContent")
                        } else if item0.answer == "N" {
                            applicant.updateValue(0, forKey: "crime")
                            applicant.updateValue("", forKey: "crimeContent")
                        }
                    } 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 {
                        if item0.answer == "Y" {
                            applicant.updateValue(item0.info.count > 0 ? 1 : 2, forKey: "deny")
                            applicant.updateValue(item0.info, forKey: "denyContent")
                        } else if item0.answer == "N" {
                            applicant.updateValue(0, forKey: "deny")
                            applicant.updateValue("", forKey: "denyContent")
                        }
                    } else if index0 == 1 {
                        if item0.answer == "Y" {
                            applicant.updateValue(item0.info.count > 0 ? 1 : 2, forKey: "crime")
                            applicant.updateValue(item0.info, forKey: "crimeContent")
                        } else if item0.answer == "N" {
                            applicant.updateValue(0, forKey: "crime")
                            applicant.updateValue("", forKey: "crimeContent")
                        }
                    } else {
                        printLog("其他数据没有处理")
                    }
                }
                applicant.updateValue(basicInfoVM.dataModelForBasicInfo?.spouse?.id ?? 0, forKey: "id")
//                applicant.updateValue(basicInfoVM.dataModelForBasicInfo?.spouse?.name ?? "", forKey: "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 {
                        if item0.answer == "Y" {
                            applicant.updateValue(item0.info.count > 0 ? 1 : 2, forKey: "deny")
                            applicant.updateValue(item0.info, forKey: "denyContent")
                        } else if item0.answer == "N" {
                            applicant.updateValue(0, forKey: "deny")
                            applicant.updateValue("", forKey: "denyContent")
                        }
                    } else if index0 == 1 {
                        if item0.answer == "Y" {
                            applicant.updateValue(item0.info.count > 0 ? 1 : 2, forKey: "crime")
                            applicant.updateValue(item0.info, forKey: "crimeContent")
                        } else if item0.answer == "N" {
                            applicant.updateValue(0, forKey: "crime")
                            applicant.updateValue("", forKey: "crimeContent")
                        }
                    } else {
                        printLog("其他数据没有处理")
                    }
                }

                applicant.updateValue(item.gcModel?.id ?? 0, forKey: "id")
//                applicant.updateValue(item.gcModel?.name ?? "", forKey: "name")
                arr.append(applicant)

                param.updateValue(arr, forKey: "child")
            }
        }

        printLog(param)

        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 YHGCBasicInfoFillViewController: 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
    }
}
