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

import UIKit

class YHCompanyAuthorizationViewController: YHBaseViewController {
    
    // MARK: - Properties
    var detailModel: YHResourceDetailModel?  // 详情数据
    var completionBlock: (() -> Void)?
    private lazy var viewModel: YHResourceViewModel = {
        return YHResourceViewModel()
    }()
    private var items: [YHSettingItem] = []
    
    // MARK: - UI Components
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: YHCompanyAuthSettingCell.self)
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    private lazy var completeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = UIColor.brandGrayColor8
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        button.setTitle("完成", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 3
        button.addTarget(self, action: #selector(completeAction), for: .touchUpInside)
        return button
    }()
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
    // MARK: - Setup
    private func setupUI() {
        gk_navTitle = "信息授权"
        view.backgroundColor = .white
        
        view.addSubview(tableView)
        view.addSubview(completeButton)
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(completeButton.snp.top).offset(-12)
        }
        
        completeButton.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 12)
            make.height.equalTo(48)
        }
    }
    
    // MARK: - Data
    private func loadData() {
        guard let detailModel = detailModel else {
            return
        }
        viewModel.isMyCompanyOpen = detailModel.isSettlement
        let item = YHSettingItem.init(type: .companyToStrange, title: "允许公开您的公司信息", subTitle: "开启后，您的公司信息将展示在资源列表，包括企业服务与企业需求", isSelect: viewModel.isMyCompanyOpen, isShowAlert: true)
        self.items = [item]
        self.tableView.reloadData()
    }
    
    // MARK: - Actions
    @objc private func completeAction() {
        guard let detailModel = detailModel else {
            return
        }
        // 2-开启，3-关闭
        let status = detailModel.isSettlement ? 3 : 2
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.companyAuthor(status: status) { [weak self] success, errorMsg in
            guard let self = self else {
                return
            }
            YHHUD.hide()
            if success {
                self.completionBlock?()
                self.navigationController?.popViewController(animated: true)
            } else {
                YHHUD.flash(message: errorMsg ?? "授权失败，请重试")
            }
        }
    }
    
    @objc private func infoButtonTapped(_ sender: UIButton) {
        guard sender.tag < items.count else { return }
        let model = items[sender.tag]
        showExplanationView(for: model)
    }
    
    // MARK: - Private Methods
    private func handleSwitchToggle(at index: Int, isOn: Bool) {
        guard index < items.count else { return }
        let model = items[index]
        
        switch model.type {
        case .companyToStrange:
            if !isOn {
                YHGrayCommonAlertView.show(
                    "",
                    "关闭后，您的公司信息将不展示在资源列表",
                    "仍然关闭",
                    "保持开启",
                    fullGuestureEnable: false,
                    cancelCallBack: { [weak self] in
                        self?.updateModelState(at: index, isEnabled: false)
                    },
                    callBack: { [weak self] in
                        self?.revertSwitchState(at: index, to: true)
                    }
                )
            } else {
                updateModelState(at: index, isEnabled: true)
            }
                        
        default:
            break
        }
    }
    
    private func updateModelState(at index: Int, isEnabled: Bool) {
        items[index].isSelect = isEnabled
        viewModel.isMyCompanyOpen = isEnabled
        tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
    }
    
    private func revertSwitchState(at index: Int, to value: Bool) {
        items[index].isSelect = value
        tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
    }
    
    private func showExplanationView(for model: YHSettingItem) {
        let view = YHSetExplainView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.type = model.type
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
}

// MARK: - UITableViewDelegate & DataSource
extension YHCompanyAuthorizationViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHCompanyAuthSettingCell.self)
        let model = items[indexPath.row]
        
        cell.configure(with: model)
        cell.infoButton.tag = indexPath.row
        cell.infoButton.addTarget(self, action: #selector(infoButtonTapped(_:)), for: .touchUpInside)
        cell.onSwitchToggle = { [weak self] isOn in
            self?.handleSwitchToggle(at: indexPath.row, isOn: isOn)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}
