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

import UIKit

class YHGCApplicationTypeController: YHBaseViewController {
    
    private lazy var datas: [[YHGCApplicationModel]] = {
        let typeA = YHGCApplicationModel(type: .typeA, isSelected: false)
        let typeB = YHGCApplicationModel(type: .typeB, isSelected: false)
        let typeC = YHGCApplicationModel(type: .typeC, isSelected: false)
        return [[typeA], [typeB], [typeC]]
    }()
    
    private lazy var headerView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 104))
        let label = UILabel()
        label.text = "您好，请选择申请类别"
        label.textColor = .mainTextColor
        label.font = .PFSC_M(ofSize: 21)
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(32)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-10)
        }
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight), style: .grouped)
        view.estimatedSectionHeaderHeight = 0.01
        view.estimatedSectionFooterHeight = 20
        view.sectionHeaderHeight = 0.01
        view.sectionFooterHeight = 20
        view.contentInsetAdjustmentBehavior = .never
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.rowHeight = UITableView.automaticDimension
        view.estimatedRowHeight = 148.0
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(YHGCApplicationTypeSelectCell.self, forCellReuseIdentifier: YHGCApplicationTypeSelectCell.cellReuseIdentifier)
        return view
    }()
    
    private lazy var bgIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "gc_application_type_bg")
        return view
    }()
    
    private lazy var submitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        button.setTitle("提交", for: .normal)
        button.setTitle("提交", for: .highlighted)
        button.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
        button.setTitleColor( UIColor(hex: 0xffffff), for: .highlighted)
        button.addTarget(self, action: #selector(clickSubmitButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .brandMainColor
        return button
    }()
    
    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var viewModel = YHGCApplicationTypeViewModel()
    private var didAppear: Bool = false
    
    private let orderId: Int
    init(orderId: Int) {
        self.orderId = orderId
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if !didAppear {
            didAppear.toggle()
            requestData(isNeedLoading: true)
        } else {
            requestData(isNeedLoading: false)
        }
        
    }
}

extension YHGCApplicationTypeController {
    
    @objc private func clickSubmitButton() {
        guard let model = datas.flatMap({ $0 }).first(where: { model in
            model.isSelected == true
        }) else {
            YHHUD.flash(message: "请选择申请类别")
            return
        }
        YHCommonAlertView.show("", "确定是否提交申请类别？提交后将不能修改", "取消", "确认", fullGuestureEnable: false) {
            //
        } callBack: { [weak self] in
            guard let self = self else {
                return
            }
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.submitApplyType(orderId, model.type.rawValue) { [weak self] success, error in
                guard let self = self else {
                    return
                }
                YHHUD.hide()
                if success {
                    YHHUD.flash(message: "提交成功")
                    // self.requestData(isNeedLoading: false)
                    self.gotoResultPage(model)
                } else {
                    var errorMsg = "提交失败"
                    if let error = error, error.errorMsg.count > 0 {
                        errorMsg = error.errorMsg
                    }
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
    
    private func gotoResultPage(_ model: YHGCApplicationModel) {
        if let navigationController = self.navigationController {
            let ctl = YHGCApplicationTypeResultController(type: model.type)
            var viewControllers = navigationController.viewControllers
            viewControllers.removeLast()
            viewControllers.append(ctl)
            navigationController.setViewControllers(viewControllers, animated: true)
        }
    }
    
    private func setupUI() {
        gk_navTitle = "申请类别"
        gk_navBarAlpha = 0
        gk_navigationBar.backgroundColor = .clear
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(bgIcon)
        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.addSubview(submitButton)
        let ratio = 318.0 / 375.0
        bgIcon.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(bgIcon.snp.width).multipliedBy(ratio)
        }
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-66)
        }
        
        submitButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kMargin)
            make.right.equalToSuperview().offset(-kMargin)
            make.top.equalToSuperview().offset(8)
            make.height.equalTo(48)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        tableView.tableHeaderView = headerView
    }
    
    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getApplyType(orderId: orderId) { [weak self] model, error in
            guard let self = self else {
                return
            }
            if isNeedLoading {
                YHHUD.hide()
            }
            guard let model = model else {
                printLog("YHGCApplicationTypeController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                return
            }
            self.datas.flatMap { $0 }.forEach {
                if $0.type.rawValue == model.apply_type {
                    $0.isSelected = true
                } else {
                    $0.isSelected = false
                }
            }
            self.tableView.reloadData()
        }
    }
    
    private func showPopVC(type: YHGCApplicationType) {
        let vc = YHGCVisaProgramPopVC(type: type)
        let pc = YHBottomPresentationController(presentedViewController: vc, presenting: self)
        pc.customRadius = 8.0
        vc.transitioningDelegate = pc
        vc.sureButtonEvent = { [weak vc] in
            vc?.dismiss(animated: true)
        }
        present(vc, animated: true, completion: nil)
    }
}

extension YHGCApplicationTypeController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        return datas[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return UITableViewCell()
        }
        let model = sectionArr[indexPath.row]
        if let cell = tableView.dequeueReusableCell(withIdentifier: YHGCApplicationTypeSelectCell.cellReuseIdentifier) as? YHGCApplicationTypeSelectCell {
            cell.setupCellInfo(type: model.type, isCurrentSelected: model.isSelected)
            cell.actionBtnEvent = { [weak self] in
                self?.showPopVC(type: model.type)
            }
            return cell
        }
        return UITableViewCell()
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 148.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard datas.count > indexPath.section else {
            return
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return
        }
        tableView.deselectRow(at: indexPath, animated: true)
        let model = sectionArr[indexPath.row]
        model.isSelected.toggle()
        datas.flatMap { $0 }.forEach {
            if $0.type != model.type, $0.isSelected {
                $0.isSelected = false
            }
        }
        tableView.reloadData()
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 20
    }
    
    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
    }
}
