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

import UIKit

class YHGCMainApplicantInformationViewController: YHBaseViewController {
    var stepView: YHStepView!
    var bottomView: YHBottomNextView!
    var tableView: UITableView!
    var viewModel: YHGCMainApplicantInformationViewModel!
    var dataSource: [YHSectionItemModel]?
    var isShowPrompt: Bool = false
    var orderId: Int = 0
    private var displayedOrderIDs: Set<String> {
        get {
            return Set(UserDefaults.standard.stringArray(forKey: "displayedOrderIDs") ?? [])
        }
        set {
            UserDefaults.standard.set(Array(newValue), forKey: "displayedOrderIDs")
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHGCMainApplicantInformationViewModel()
        gk_navTitle = "主申请人信息填写"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1
        setView()
        getData()
        // Do any additional setup after loading the view.
    }
    
    func getData() {
        viewModel.requestMainInformation("\(orderId)") {[weak self] _, _ in
            guard let self = self else { return }
            self.stepView.maxIndex = self.viewModel.mainModel.step
            self.stepView.currentIndex = self.viewModel.mainModel.step
            self.updateDataSource()
            if self.stepView.currentIndex == 3 {
                self.bottomView.nextButton.setTitle("提交", for: .normal)
            } else {
                self.bottomView.nextButton.setTitle("下一步", for: .normal)
            }
        }
    }
    
    func updateDataSource() {
        if self.stepView.currentIndex == 0 {
            self.dataSource = self.viewModel.getBaseDataSource(isShowPrompt)
            self.bottomView.nextButton.setTitle("下一步", for: .normal)
        } else if self.stepView.currentIndex == 1 {
            self.dataSource = self.viewModel.getIDCardDataSource(isShowPrompt)
            self.bottomView.nextButton.setTitle("下一步", for: .normal)
        } else if self.stepView.currentIndex == 2 {
            self.dataSource = self.viewModel.getDocumentInformation(isShowPrompt)
            self.bottomView.nextButton.setTitle("下一步", for: .normal)
        } else if self.stepView.currentIndex == 3 {
            self.dataSource = self.viewModel.getDetailDataSource(isShowPrompt)
            self.bottomView.nextButton.setTitle("提交", for: .normal)
        }
        self.tableView.reloadData()
    }
    
    private func hasDisplayedPopup(for orderID: String) -> Bool {
        return displayedOrderIDs.contains(orderID)
    }
    
    func setView() {
        view.backgroundColor = .contentBkgColor
        
        stepView = {
            let step = YHStepView()
            step.dataSource = ["初始信息", "证件上传", "证件信息", "基本信息"]
            step.block = { [weak self] (_) in
                guard let self = self else { return }
                self.updateDataSource()
            }
            return step
        }()
        view.addSubview(stepView)
        stepView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalTo(view)
            make.height.equalTo(104)
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHMainInformationTableViewCell.self)
            tableView.register(cellWithClass: YHGCMainInformationCardTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + YHStepView.height)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.bottom.equalTo(view)
        }
        
        bottomView = {
            let bottom = YHBottomNextView()
            bottom.nextblock = { [weak self] in
                bottom.nextButton.isEnabled = false
                guard let self = self else { return }
                if self.viewModel.isCanNext(self.stepView.currentIndex) {
                    if self.stepView.currentIndex == 1 && !hasDisplayedPopup(for: orderId.string) {
                        bottom.nextButton.isEnabled = true
                        YHTravelCertificateUsageTipsView.alertView().show()
                        displayedOrderIDs.insert(orderId.string)
                        return
                    }
                    self.viewModel.mainModel.step = self.stepView.currentIndex
                    self.viewModel.updateMainInformation(.submit, self.orderId, self.stepView.currentIndex) {[weak self] _, error  in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            YHHUD.hideFlashMessage()
                            self.stepView.currentIndex += 1
                            self.isShowPrompt = false
                            self.stepView.currentIndex = self.stepView.currentIndex
                            if self.stepView.currentIndex == 3 {
                                self.bottomView.nextButton.setTitle("提交", for: .normal)
                            } else {
                                self.bottomView.nextButton.setTitle("下一步", for: .normal)
                            }
                            if self.stepView.currentIndex == self.stepView.dataSource?.count {
                                YHHUD.flash(message: "提交成功")
                                self.navigationController?.popViewController()
                            } else {
                                self.updateDataSource()
                            }
                        }
                    }
                } else {
                    bottom.nextButton.isEnabled = true
                    self.isShowPrompt = true
                    self.updateDataSource()
                    YHHUD.flash(message: "您还有信息未填写")
                }
            }
            bottom.saveBlock = { [weak self] in
                guard let self = self else { return }
                self.viewModel.updateMainInformation(.save, self.orderId, self.stepView.currentIndex) {[weak self] _, error  in
                    guard let _ = self else { return }
                    if let error = error {
                        YHHUD.flash(message: error.errorMsg )
                    } else {
                        YHHUD.flash(message: "保存成功")
                    }
                }
            }
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        bottomView.layoutIfNeeded()
        bottomView.nextButton.addYinHeGradualLayer()
    }
}

extension YHGCMainApplicantInformationViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if stepView.currentIndex == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHGCMainInformationCardTableViewCell.self)
            if dataSource?[indexPath.row].models?.first?.id == .id5 {
                cell.type = .identity
            }
            if dataSource?[indexPath.row].models?.first?.id == .id6 {
                cell.type = .passport
            }
            if dataSource?[indexPath.row].models?.first?.id == .id7 {
                cell.type = .other
            }
            cell.viewModel = viewModel
            cell.backSurfaceDeleteButton.isHidden = true
            cell.frontDeleteButton.isHidden = true
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHMainInformationTableViewCell.self)
            cell.country = self.viewModel.mainModel.address.country
            cell.dataSource = dataSource?[indexPath.row]
            cell.informationBlock = {[weak self] model in
                guard let self = self else { return }
                self.viewModel.updateModel(model)
                let id = model.id
                if id != .id32 && id != .id4 && id != .id8 && id != .id9 && id != .id12 && id != .id13 && id != .id17 && id != .id18 && id != .id21 && id != .id22 && id != .id23 && id != .id26 && id != .id34 && id != .id29 && id != .id30 && id != .id35 {
                    self.updateDataSource()
                }
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if stepView.currentIndex == 1 {
            return 227.0
        } else {
            let array = dataSource?[indexPath.row].models ?? []
            var h = 0
            for i in 0..<array.count {
                let data = array[i]
                let isShow = data.isShowPrompts ?? false
                let message = data.message ?? ""
                let isNeed = data.isNeed ?? false
                if data.id == .id3 || data.id == .id4 || data.id == .id32 || data.id == .id33 || data.id == .id40 {
                    if isShow && message.count == 0 && isNeed {
                        h = h + 72 + 20
                    } else {
                        h += 72
                    }
                } else {
                    if isShow && message.count == 0 && isNeed {
                        h = h + 52 + 20
                    } else {
                        h += 52
                    }
                }
            }
            return CGFloat(h + 52 + 14)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 7
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}
