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

import UIKit

class YHMakePlanPriceAlertView: UIView {
    typealias Block = (Int) -> Void
    var block: Block?
    var centerView: UIView!
    var titleLabel: UILabel!
    var closeButton: UIButton!
    var lineView: UIView!
    lazy var priceView: YHMakePlanBottomView = {
        let view = YHMakePlanBottomView()
        return view
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 50
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: YHMakePlanLabelCell.self)
        return tableView
    }()
    
    var dataSource: YHMakePlanModel = YHMakePlanModel() {
        didSet {
            tableView.reloadData()
            let totalPrice = dataSource.calculateTotalPrice()
            priceView.priceButton.setImage(UIImage(named: "make_plan_down"), for: .normal)
            priceView.configure(price: totalPrice, actionText: "去办理") {
                self.dismiss()
            } nextHandler: {
                self.block?(1)
            }
        }
    }
    
    static func show(dataSource: YHMakePlanModel, callBack: @escaping ((Int) -> Void)) {
        let view = YHMakePlanPriceAlertView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.block = callBack
        view.dataSource = dataSource
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.5, alpha: 0.1)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setView() {
        backgroundColor = UIColor(hex: 0x0000, alpha: 0.5)
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius6
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(554)
        }
        
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .center
            label.text = "价格明细"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(16)
            make.height.equalTo(20)
            make.right.equalTo(-18)
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "address_close"), for: .normal)
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.width.equalTo(24)
            make.top.equalTo(18)
        }
        
        closeButton.YH_clickEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(52)
            make.height.equalTo(1)
            make.right.equalTo(-18)
        }
        
        centerView.addSubview(priceView)
        priceView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(98)
        }

        priceView.configure(price: "489800", actionText: "去办理") {
            self.dismiss()
        } nextHandler: {
            self.block?(1)
        }
        
        centerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(52)
            make.bottom.equalTo(-98)
        }
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        dismiss()
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
    @objc func orderButtonClick() {
        if let block = block {
            block(1)
        }
        dismiss()
    }
    
    @objc func guideButtonClick() {
        if let block = block {
            block(2)
        }
        dismiss()
    }
}

extension YHMakePlanPriceAlertView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view == self {
            return true
        }
        return false
    }
}

extension YHMakePlanPriceAlertView: 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: YHMakePlanLabelCell.self) as? YHMakePlanLabelCell else {
            return UITableViewCell()
        }
        var data: [YHMakePlanMainModel] = []
        if indexPath.row == 0 {
            cell.titleLabel.text = "基础身份续签"
            data = dataSource.basic
        } else if indexPath.row == 1 {
            cell.titleLabel.text = "工作联系提升"
            data = dataSource.work
        } else if indexPath.row == 2 {
            cell.titleLabel.text = "生活联系提升"
            data = dataSource.live
        } else if indexPath.row == 3 {
            cell.titleLabel.text = "投资联系提升"
            data = dataSource.invest
        }
        cell.dataSource = data
        let filteredModel = data.filteredByCartStatus()
        if filteredModel.count == 0 {
            cell.isHidden = true
        } else {
            cell.isHidden = false
        }
        if indexPath.row == 3 {
            cell.lineView.isHidden = true
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        var data: [YHMakePlanMainModel] = []
        if indexPath.row == 0 {
            data = dataSource.basic
        } else if indexPath.row == 1 {
            data = dataSource.work
        } else if indexPath.row == 2 {
            data = dataSource.live
        } else if indexPath.row == 3 {
            data = dataSource.invest
        }
        let filteredModel = data.filteredByCartStatus()
        if filteredModel.count == 0 {
            return 0
        }
        return UITableView.automaticDimension
    }
    
    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
    }

}

class YHMakePlanLabelCell: UITableViewCell {
//    typealias InformationBlock = (_ model: YHItemModel) -> Void
    var centerView: UIView!
    var titleLabel: UILabel!
    var mainItemView: UIView!
    var country: String = ""
    var lineView: UIView!
    var dataSource: [YHMakePlanMainModel]? {
        didSet {
            updateAllViews()
        }
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius6
            return view
        }()
        contentView.addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(7)
            make.bottom.equalTo(-7)
        }
        
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor(hex: 0x8993a2)
            label.text = "价格明细"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(16)
            make.height.equalTo(20)
        }
        
        mainItemView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius6
            return view
        }()
        centerView.addSubview(mainItemView)
        mainItemView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(36)
        }
        
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        
    }
    
    func updateAllViews() {
        mainItemView.removeSubviews()
        let filteredModel = dataSource?.filteredByCartStatus() ?? []
        
        var lastView: UIView?
        
        for (i, model) in filteredModel.enumerated() {
            let name = model.sub_product.first?.product_name ?? ""
            let titleLabel = UILabel()
            titleLabel.font = UIFont.PFSC_M(ofSize: 14)
            titleLabel.textColor = UIColor.mainTextColor
            if name == "" {
                titleLabel.text = model.product_name 
            } else {
                titleLabel.text = model.product_name + " | " + name
            }
            titleLabel.numberOfLines = 0
            mainItemView.addSubview(titleLabel)
            
            let price = model.sub_product.first?.price ?? model.price
            let valueLabel = UILabel()
            valueLabel.font = UIFont.PFSC_M(ofSize: 14)
            valueLabel.textColor = UIColor.mainTextColor
            valueLabel.textAlignment = .right
            valueLabel.text = "¥" + price.formattedPrice()
            mainItemView.addSubview(valueLabel)
            
            titleLabel.snp.makeConstraints { make in
                make.left.equalToSuperview()
                make.right.equalTo(valueLabel.snp.left).offset(-8)
                if let lastView = lastView {
                    make.top.equalTo(lastView.snp.bottom).offset(12)
                } else {
                    make.top.equalToSuperview().offset(12)
                }
            }
            
            valueLabel.snp.makeConstraints { make in
                make.right.equalToSuperview()
                make.width.equalTo(100)
                make.top.equalTo(titleLabel)
            }
            
            lastView = titleLabel
            
            // 如果是最后一个元素，连接到底部
            if i == filteredModel.count - 1 {
                titleLabel.snp.makeConstraints { make in
                    make.bottom.equalToSuperview().offset(-12)
                }
            }
        }
    }
}
