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

import UIKit
import AttributedString

class YHMakePlanCardView: UIView {
    var actionHandler: ((Int) -> Void)?

    // MARK: - UI Elements
    var data: YHMakePlanMainModel?
    
    lazy var containerView: UIButton = {
        let view = UIButton()
        view.backgroundColor = .white
        view.addTarget(self, action: #selector(gotoDetail), for: .touchUpInside)
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_M(ofSize: 16)
        label.textColor = .mainTextColor
        label.numberOfLines = 1
        return label
    }()
    
    private lazy var subtitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.textColor = UIColor(hex: 0x8993a2)
        label.numberOfLines = 1
        return label
    }()
    
    private lazy var companyImageView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "global_default_image")
        return view
    }()
    
    private lazy var storeButton: YHImageTextButton = {
        let button = YHImageTextButton(title: "星企航(7年)", image: UIImage(named: "make_plan_left"))
        button.layer.cornerRadius = 2
        button.backgroundColor = UIColor(hex: 0xf5f6f8)
        button.addTarget(self, action: #selector(selectAction), for: .touchUpInside)
        return button
    }()
    
    private lazy var priceTagView: UILabel = {
        let label = UILabel()
        let a: ASAttributedString = .init("¥", .font(UIFont(name: "D-DIN-PRO-Bold", size: 14) ?? UIFont()), .foreground(UIColor.mainTextColor))
        let b: ASAttributedString = .init("58999.00", .font(UIFont(name: "D-DIN-PRO-Bold", size: 20) ?? UIFont()), .foreground(UIColor.mainTextColor))
        label.attributed.text = a + b
        return label
    }()
    
    private lazy var selectButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "make_plan_select"), for: .selected)
        button.setImage(UIImage(named: "make_plan_normal"), for: .normal)

        button.addTarget(self, action: #selector(handleAction), for: .touchUpInside)
        return button
    }()
    
    // MARK: - Initialization
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    
    private func setupUI() {
        addSubview(containerView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(subtitleLabel)
        containerView.addSubview(companyImageView)
        containerView.addSubview(priceTagView)
        containerView.addSubview(storeButton)
        containerView.addSubview(selectButton)
    }
    
    private func setupConstraints() {
        containerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.left.equalToSuperview().offset(110)
            make.right.equalToSuperview().offset(-16)
        }
        
        subtitleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(40)
            make.left.equalToSuperview().offset(110)
            make.right.equalToSuperview().offset(-16)
        }
        
        companyImageView.snp.makeConstraints { make in
            make.top.equalTo(18)
            make.left.equalTo(16)
            make.height.width.equalTo(86)
        }
        
        storeButton.translatesAutoresizingMaskIntoConstraints = false
        storeButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(60)
            make.left.equalToSuperview().offset(110)
//            make.width.equalTo(97)
            make.height.equalTo(22)
        }

        priceTagView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(86)
            make.left.equalToSuperview().offset(110)
            make.right.equalToSuperview().offset(-16)
        }
        
        selectButton.snp.makeConstraints { make in
            make.right.bottom.equalTo(-18)
            make.height.width.equalTo(16)
        }

    }
    
    @objc func gotoDetail() {
        if selectButton.isHidden {
            return
        }
        
        var id = self.data?.product_id ?? 0
        if self.data?.price == "" {
            let count = self.data?.sub_product.count ?? 0
            var index = 0
            for i in 0 ..< count {
                let flag = self.data?.sub_product[i].is_add_cart ?? false
                if flag {
                    index = i
                }
            }
            if count > 0 {
                let subModel = data?.sub_product[index]
                id = subModel?.product_id ?? 0
            }
        }
        
        var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/goods/sales-detail" + "?id=\(id)" + "&source=renewal_customize&hidelive=1"

        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            let urlHasParam = String.hasQueryParameters(urlString: url)
            if urlHasParam {
                url = url + "&param=" + token
            } else {
                url = url + "?param=" + token
            }
        }
        // 2.增加导航栏高度 https://test-hklife.galaxy-immi.com/superAppBridge.html#/goods/sales-detail?id=
        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.isHideNavigationBar = false
        UIViewController.current?.navigationController?.pushViewController(vc)
    }
    
    @objc func selectAction() {
        YHMakePlanSelectAlertView.show(dataSource: data ?? YHMakePlanMainModel()) { tag in
            self.actionHandler?(tag)
            self.selectButton.isSelected = true
            let count = self.data?.sub_product.count ?? 0
            for i in 0 ..< count {
                if tag == self.data?.sub_product[i].product_id {
                    self.data?.sub_product[i].is_add_cart = true
                } else {
                    self.data?.sub_product[i].is_add_cart = false
                }
            }
            self.configure(with: self.data ?? YHMakePlanMainModel())
        }
    }
    
    @objc func handleAction() {
        selectButton.isSelected = !selectButton.isSelected
        var product = self.data?.product_id ?? 0
        let count = self.data?.sub_product.count ?? 0
        if count != 0 {
            var index = self.data?.sub_product.indexOfLowestPrice() ?? 0
            for i in 0 ..< count {
                let flag = self.data?.sub_product[i].is_add_cart ?? false
                if flag {
                    index = i
                }
            }
            if count > 0 {
                let subModel = data?.sub_product[index]
                product = subModel?.product_id ?? 0
            }
        }
        self.actionHandler?(product)
    }
    // MARK: - Configuration
    
    func configure(with data: YHMakePlanMainModel) {
        self.data = data
        titleLabel.text = data.product_name
        subtitleLabel.text = data.product_desc
        var price = data.price
        if data.price == "" {
            storeButton.isHidden = false
            let count = self.data?.sub_product.count ?? 0
            var index = self.data?.sub_product.indexOfLowestPrice() ?? 0
            for i in 0 ..< count {
                let flag = self.data?.sub_product[i].is_add_cart ?? false
                if flag {
                    index = i
                }
            }
            if count > 0 {
                let subModel = data.sub_product[index]
                price = subModel.price
                storeButton.setTitle(subModel.product_name, for: .normal)
            }
        } else {
            storeButton.isHidden = true
        }
        
        let a: ASAttributedString = .init("¥", .font(UIFont(name: "D-DIN-PRO-Bold", size: 14) ?? UIFont()), .foreground(UIColor.mainTextColor))
        let b: ASAttributedString = .init("\(price.formattedPrice())", .font(UIFont(name: "D-DIN-PRO-Bold", size: 20) ?? UIFont()), .foreground(UIColor.mainTextColor))
        priceTagView.attributed.text = a + b
        
        if let url = URL(string: data.cover_img) {
            companyImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
        }
        
        if data.is_add_cart {
            selectButton.isSelected = true
        } else {
            selectButton.isSelected = false
        }
        
        storeButton.updateContent()
    }
    
    func configureSub(with data: YHMakePlanSubModel) {
        titleLabel.text = data.product_name
        subtitleLabel.text = data.product_desc
        let a: ASAttributedString = .init("¥", .font(UIFont(name: "D-DIN-PRO-Bold", size: 14) ?? UIFont()), .foreground(UIColor.mainTextColor))
        let b: ASAttributedString = .init("\(data.price.formattedPrice())", .font(UIFont(name: "D-DIN-PRO-Bold", size: 20) ?? UIFont()), .foreground(UIColor.mainTextColor))
        priceTagView.attributed.text = a + b
        selectButton.isHidden = true
        storeButton.isHidden = true
        if let url = URL(string: data.cover_img) {
            companyImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
        }
        storeButton.updateContent()
    }
}

class YHImageTextButton: UIButton {
    
    var spacing: CGFloat = 4 // 文字和图片之间的间距
    var horizontalPadding: CGFloat = 8 // 左右边距
    
    init(title: String, image: UIImage?) {
        super.init(frame: .zero)
        
        // 基础配置
        setTitle(title, for: .normal)
        setImage(image, for: .normal)
        setTitleColor(UIColor(hex: 0x6a7586), for: .normal)
        titleLabel?.font = UIFont.PFSC_R(ofSize: 12)
        
        // 关键配置：图片在右侧
        semanticContentAttribute = .forceRightToLeft
        contentHorizontalAlignment = .center
        
        // 禁用系统默认的inset调整
        adjustsImageWhenHighlighted = false
        imageView?.translatesAutoresizingMaskIntoConstraints = false
        titleLabel?.translatesAutoresizingMaskIntoConstraints = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 关键：正确计算固有内容大小
    override var intrinsicContentSize: CGSize {
        let titleSize = titleLabel?.intrinsicContentSize ?? .zero
        let imageSize = imageView?.intrinsicContentSize ?? .zero
        
        // 总宽度 = 文字宽度 + 图片宽度 + 间距 + 左右边距×2
        let totalWidth = titleSize.width + imageSize.width + spacing + 2 * horizontalPadding
        let maxHeight = max(titleSize.height, imageSize.height)
        
        return CGSize(width: totalWidth, height: maxHeight)
    }
    
    // 关键：手动布局子视图
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard let titleLabel = titleLabel, let imageView = imageView else { return }
        
        // 手动计算布局
        let totalContentWidth = titleLabel.intrinsicContentSize.width + spacing + imageView.intrinsicContentSize.width
        let startX = (bounds.width - totalContentWidth) / 2
        
        // 定位文字和图片
        titleLabel.frame = CGRect(
            x: startX,
            y: (bounds.height - titleLabel.intrinsicContentSize.height) / 2,
            width: titleLabel.intrinsicContentSize.width,
            height: titleLabel.intrinsicContentSize.height
        )
        
        imageView.frame = CGRect(
            x: titleLabel.frame.maxX + spacing,
            y: (bounds.height - imageView.intrinsicContentSize.height) / 2,
            width: imageView.intrinsicContentSize.width,
            height: imageView.intrinsicContentSize.height
        )
    }
    
    // 在文本或图片变化时调用
    func updateContent() {
        invalidateIntrinsicContentSize()
        setNeedsLayout()
    }
}

extension String {
    func formattedPrice() -> String {
        // 检查是否包含小数点
        guard let number = Double(self) else { return self }
                
        // 2. 检查小数点后两位是否为 0
        let isInteger = (number * 100).truncatingRemainder(dividingBy: 100) == 0
        
        // 3. 使用 NumberFormatter 控制显示格式
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.minimumFractionDigits = isInteger ? 0 : 2  // 整数部分不显示小数，否则保留 2 位
        formatter.maximumFractionDigits = 2
        
        return formatter.string(from: NSNumber(value: number)) ?? self
    }
}
