//
//  YHMakePlanViewController.swift
//  galaxy
//
//  Created by EDY on 2025/3/27.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHMakePlanViewController: YHBaseViewController {
    var items: [[Int]] = []
    let viewModel = YHMakePlanViewModel()
        
    lazy var headView: YHMakePlanHeadView = {
        let view = YHMakePlanHeadView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 333.fix + 44 + 35))
        view.block = { tag in
            self.topView.custtomView.updataData(tag)
            let indexPath = IndexPath(row: tag, section: 0)
            let cellRect: CGRect = self.tableView.rectForRow(at: indexPath)
            let targetY = cellRect.origin.y - 104 - k_Height_NavigationtBarAndStatuBar
            self.tableView.setContentOffset(CGPoint(x: 0, y: targetY), animated: true)
        }
        return view
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: YHMakePlanCell.self)
        tableView.tableHeaderView = headView
        return tableView
    }()
    
    lazy var priceView: YHMakePlanBottomView = {
        let view = YHMakePlanBottomView()
        return view
    }()
    
    lazy var topView: YHMakePlanTopView = {
        let view = YHMakePlanTopView()
        view.isHidden = true
        view.block = { tag in
            self.headView.custtomView.updataData(tag)
            let indexPath = IndexPath(row: tag, section: 0)
            let cellRect: CGRect = self.tableView.rectForRow(at: indexPath)
            let targetY = cellRect.origin.y - 104 - k_Height_NavigationtBarAndStatuBar
            self.tableView.setContentOffset(CGPoint(x: 0, y: targetY), animated: true)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
//        gk_navTitle = "续签至永居方案私人订制"
        gk_navTitleColor = .white
        gk_navBarAlpha = 1
//        gk_navBackgroundImage = UIImage(named: "my_scheme_nav")
        gk_backImage = UIImage(named: "back_icon_white")
        addRightItems()
        // Create and add to your view
        view.addSubview(priceView)
        priceView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(98)
        }
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(-98)
        }
        
        view.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(104)
        }
        
        requestData()
    }
    
    func updataPrice() {
        let totalPrice = viewModel.makePlanModel.calculateTotalPrice()
        priceView.configure(price: totalPrice, actionText: "去办理") {
            if totalPrice.double() ?? 0 > 0 {
                YHMakePlanPriceAlertView.show(dataSource: self.viewModel.makePlanModel) { _ in
                    self.addShopCard()
                }
            }
        } nextHandler: {
            self.addShopCard()
        }
    }
    
    func addShopCard() {
        self.viewModel.addShopCard(model: self.viewModel.makePlanModel) { success, _ in
            if success {
                // 跳转购物车
                if let token = YHLoginManager.shared.userModel?.token, token.count > 5 {
                    var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/goods/cart"
                    url = url + "?param=" + YHLoginManager.shared.h5Token
                    printLog("URL: \(url)")
                    var tUrl = url
                    if !url.contains("navigationH=") {
                        tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                        if url.contains("?") {
                            tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                        }
                    }
                    let vc = YHH5WebViewVC()
                    vc.url = tUrl
                    vc.isFullScreenFlag = false
                    vc.navTitle = "购物车"
                    vc.isSupportWebviewInterBackFlag = true
                    UIViewController.current?.navigationController?.pushViewController(vc)
                }
            }
        }
    }
    
    func addRightItems() {
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "share_item_white")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
    }
    
    func addRightWhiteItems() {
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
    }
    
    @objc func share() {
        YHMakePlanShareAlertView.show(url: viewModel.score.share_url) { _ in
            
        }
    }
    
    func requestData() {
        viewModel.getProductList {[weak self] _, _ in
            guard let self = self else { return }
            tableView.reloadData()
            updataPrice()
            getScore()
        }
    }
    
    func getScore() {
        viewModel.getRate(model: viewModel.makePlanModel) {[weak self] _, _ in
            guard let self = self else { return }
            self.headView.dataSource = viewModel.score
            self.topView.dataSource = viewModel.score
        }
    }
    
    func submitTargets() {
               
    }

}

extension YHMakePlanViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        return items.count
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withClass: YHMakePlanCell.self) as? YHMakePlanCell else {
            return UITableViewCell()
        }
        var dataSource: [YHMakePlanMainModel] = []
        if indexPath.row == 0 {
            dataSource = viewModel.makePlanModel.basic
            cell.titleLabel.text = "基础身份续签"
        } else if indexPath.row == 1 {
            dataSource = viewModel.makePlanModel.work
            cell.titleLabel.text = "工作联系提升"
        } else if indexPath.row == 2 {
            dataSource = viewModel.makePlanModel.live
            cell.titleLabel.text = "生活联系提升"
        } else if indexPath.row == 3 {
            dataSource = viewModel.makePlanModel.invest
            cell.titleLabel.text = "投资联系提升"
        }
        cell.dataSource = dataSource
        cell.index = indexPath.row
        cell.actionHandler = { product in
            self.viewModel.makePlanModel.toggleAddCartStatus(for: product)
            self.updataPrice()
            self.getScore()
            self.tableView.reloadData()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        var count = 0
        if indexPath.row == 0 {
            count = viewModel.makePlanModel.basic.count
        } else if indexPath.row == 1 {
            count = viewModel.makePlanModel.work.count
        } else if indexPath.row == 2 {
            count = viewModel.makePlanModel.live.count
        } else if indexPath.row == 3 {
            count = viewModel.makePlanModel.invest.count
        }
        if count == 0 {
            if indexPath.row == 0 {
                return 168 + 32
            } else {
                return 188 + 32
            }
        }
        return CGFloat(36 + 16 + 118 * count)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y + scrollView.contentInset.top
        if offsetY > 0 {
            var alpha = offsetY / k_Height_NavigationtBarAndStatuBar
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            gk_navBackgroundColor = .white
            gk_navTitle = "续签至永居方案私人订制"
            gk_navTitleColor = .black
            gk_backImage = UIImage(named: "nav_black_24")
//            gk_navRightBarButtonItem?.image = UIImage(named: "share_item")
            addRightWhiteItems()
        } else {
            gk_navBarAlpha = 0.0
            gk_navBackgroundColor = .clear
            gk_navTitle = nil
            gk_backImage = UIImage(named: "back_icon_white")
            addRightItems()
        }
        if offsetY > 333.fix - k_Height_NavigationtBarAndStatuBar - 44 - scrollView.contentInset.top {
            topView.isHidden = false
        } else {
            topView.isHidden = true
        }
        if let topRow = tableView.topVisibleRowIndex() {
            self.topView.custtomView.updataData(topRow)
            self.headView.custtomView.updataData(topRow)
        }
    }
}

extension UITableView {
    /// 获取当前显示在最顶部的行索引
    func topVisibleRowIndex() -> Int? {
        // 获取所有可见行的indexPath（按从上到下的顺序排列）
        let visibleRect = CGRect(
            x: self.contentOffset.x,
            y: self.contentOffset.y + 104 + k_Height_NavigationtBarAndStatuBar, // 向下偏移 187px
            width: self.bounds.width,
            height: self.bounds.height
        )

        // 获取该区域内的所有行
        guard let indexPaths = self.indexPathsForRows(in: visibleRect) else {
            return 0
        }

        return indexPaths.first?.row
    }
    
    /// 获取当前显示在最顶部的单元格
    func topVisibleCell() -> UITableViewCell? {
        guard let topRow = topVisibleRowIndex() else {
            return nil
        }
        return self.cellForRow(at: IndexPath(row: topRow, section: 0))
    }
}
