//
//  YHFamilyInfoConfirmViewController.swift
//  galaxy
//
//  Created by edy on 2024/8/16.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHFamilyInfoConfirmViewController: YHBaseViewController {

    var orderId: Int = 0
    var sectionItems: [String] = ["", "", "", ""]
    var familyArr: [YHApplicantInfoModel] = []
    let viewModel = YHFamilyInfoConfirmViewModel()
    let princleVM = YHPrincleViewModel()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 16.0
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hex: 0xF8F9FB)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHRiskWarningCell.self, forCellReuseIdentifier: YHRiskWarningCell.cellReuseIdentifier)
        tableView.register(YHApproverInfoVerifyCell.self, forCellReuseIdentifier: YHApproverInfoVerifyCell.cellReuseIdentifier)
        tableView.register(YHCertificateInfoPhotoCell.self, forCellReuseIdentifier: YHCertificateInfoPhotoCell.cellReuseIdentifier)
        tableView.register(YHFamilyWarmTipsCell.self, forCellReuseIdentifier: YHFamilyWarmTipsCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var bottomBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("确认修改，下一步", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didBottomBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "家庭信息确认"
        self.view.backgroundColor = .white
        self.view.addSubview(self.tableView)
        self.view.addSubview(bottomView)
        self.tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar+16)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(98)
        }
        requetRiskAlert()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getFamilyInfo()
    }
    
    @objc func didBottomBtnClicked() {
        
        for member in self.familyArr {
            if member.confirmStatus == 0 {
                YHHUD.flash(message: "存在未确认信息，此信息涉及后续【香港身份证办理】，辛苦核对")
                return
            }
        }
        viewModel.submitFaimiyInfoWithOrderId(orderId) {
            [weak self] success, error in
            guard let self = self else { return }
            if success {
                self.navigationController?.popToRootViewController(animated: false)
                YHButlerServiceManager.shared.sessionGoBack()
                goTabBarBy(tabType: .service)
                let tipsKey = "family_info_confirm_warm_tips_\(self.orderId)"
                if let isShow = UserDefaults.standard.value(forKey: tipsKey) as? Bool, isShow {
                    
                } else {
                    YHFamilyInfoWarmTipsView.tipsView().show()
                    UserDefaults.standard.set(true, forKey: tipsKey)
                    UserDefaults.standard.synchronize()
                }
                return
            }
            let msg = error?.errorMsg ?? "确认修改失败"
            YHHUD.flash(message: msg)
            
        }
    }
    
    func requetRiskAlert() {
        viewModel.requetRiskAlertShow {
           [weak self] isHaveShow in
            guard let self = self else { return }
            
            if isHaveShow {
                return
            }
            let alert = YHFamilyMemberRiskWarningAlertView.alertView()
            alert.confirmBlock = {
                [weak self] in
                guard let self = self else { return }
                self.princleVM.postAlertStatus(3) { _, _ in
                }
            }
            alert.show()
        }
    }
}

extension YHFamilyInfoConfirmViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionItems.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                
        if 0 <= indexPath.section && indexPath.section < sectionItems.count {
            if indexPath.section == 0 {
                let warningCell = tableView.dequeueReusableCell(withIdentifier: YHRiskWarningCell.cellReuseIdentifier, for: indexPath)
                return warningCell
            }
            if indexPath.section == 1 {
                guard let approveCell = tableView.dequeueReusableCell(withIdentifier: YHApproverInfoVerifyCell.cellReuseIdentifier, for: indexPath) as? YHApproverInfoVerifyCell else { return UITableViewCell()}
                approveCell.updateFamilyArr(self.familyArr, familyGroup: self.viewModel.familyInfo)
                return approveCell
            }
            if indexPath.section == 2 {
                guard let certificateInfoCell = tableView.dequeueReusableCell(withIdentifier: YHCertificateInfoPhotoCell.cellReuseIdentifier, for: indexPath) as? YHCertificateInfoPhotoCell else {
                    return UITableViewCell()
                }
                return certificateInfoCell
            }
        }

        guard let warmTipsCell = tableView.dequeueReusableCell(withIdentifier: YHFamilyWarmTipsCell.cellReuseIdentifier, for: indexPath) as? YHFamilyWarmTipsCell else { return UITableViewCell() }
        return warmTipsCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.section && indexPath.section < sectionItems.count {
            
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 16.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}

extension YHFamilyInfoConfirmViewController {
    
    func getFamilyInfo() {
        YHHUD.show(.progress(message: "加载中..."))
        self.viewModel.getFamilyInfo(param: ["orderId": orderId]) {
            [weak self] _, _ in
            YHHUD.hide()
            guard let self = self else { return }
            self.familyArr.removeAll()
            if self.viewModel.familyInfo.main.info.id > 0 {
                self.familyArr.append(self.viewModel.familyInfo.main)
            }
            if self.viewModel.familyInfo.spouse.info.id > 0 {
                self.familyArr.append(self.viewModel.familyInfo.spouse)
            }
            for child in self.viewModel.familyInfo.children {
                self.familyArr.append(child)
            }
            self.tableView.reloadData()
        }
    }
}
