//
//  YHLiveShopView.swift
//  galaxy
//
//  Created by EDY on 2024/12/2.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHLiveShopView: UIView {
    enum FromPage {
        case live
        case vod
    }
    
    var fromPage: FromPage = .live
    var closeEvent: (() -> Void)?
    var backData: ((Int) -> Void)?
    var buyData: ((Int) -> Void)?
    var centerView: UIView!
    var titleLabel: UILabel!
    var subTitleLabel: UILabel!
    var closeButton: UIButton!
    // var lineView: UIView!
    var tableView: UITableView!
    var dataSource: [YHLiveGoodsItem] = [] {
        didSet {
            self.tableView.reloadData()
        }
    }
    var viewModel = YHWorkExperienceViewModel()
    var title: String = "" {
        didSet {
            titleLabel.text = title
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        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() {
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(295)
            make.left.right.bottom.equalToSuperview()
        }
        
        let headImageView = {
            let view = UIImageView()
            view.isUserInteractionEnabled = true
            view.image = UIImage(named: "live_shop_head")
            return view
        }()
        centerView.addSubview(headImageView)
        headImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(128)
        }
        
        titleLabel = {
            let label = UILabel()
            label.text = title
            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.top.equalTo(16)
            make.height.equalTo(24)
            make.width.equalTo(200)
            make.centerX.equalToSuperview()
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "my_cer_sheet_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(16)
        }
                
//        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)
//        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHLiveShopViewCell.self)
            return tableView
        }()
        centerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(52)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom())
            make.left.right.equalToSuperview()
        }
        
        centerView.layoutIfNeeded()
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = centerView.bounds
        layer.path = path.cgPath
        centerView.layer.mask = layer
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        dismiss()
    }
    
    static func show(callBack: @escaping ((Int) -> Void)) -> YHLiveShopView {
        let view = YHLiveShopView(frame: CGRect(x: 0, y: KScreenWidth, width: KScreenWidth, height: KScreenHeight))
        view.backData = callBack
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseOut) {
            view.frame.origin.y = 0
        } completion: { _ in }
        return view
    }
    
    @objc func dismiss() {
        // 禁用交互防止动画过程中的重复点击
        isUserInteractionEnabled = false
        centerView.isUserInteractionEnabled = false

        UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn) {
            self.frame.origin.y = KScreenHeight
            self.centerView.alpha = 0
        } completion: { _ in
            self.centerView.removeFromSuperview()
            self.removeFromSuperview()
            self.closeEvent?()
        }
    }
}

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

extension YHLiveShopView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard dataSource.count > indexPath.row else {
            return UITableViewCell()
        }
        let model = dataSource[indexPath.row]
        let cell = tableView.dequeueReusableCell(withClass: YHLiveShopViewCell.self)
        model.flag = indexPath.row + 1
        cell.dataSource = model
        cell.buyEvent = { [weak self] in
            self?.buyData?(indexPath.row)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 130
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    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
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard dataSource.count > indexPath.row else {
            return
        }
        switch fromPage {
        case .live:
            YHAnalytics.track("APP_LivePage_ProductWindowPopup_ClickProduct")
        case .vod:
            YHAnalytics.track("APP_RecordedPage_ProductWindowPopup_ClickProduct")
        }
        
        backData?(indexPath.row)
    }
}

class YHLiveShopViewCell: UITableViewCell {
    var centerImageView: UIImageView!
    var titleLabel: UILabel!
    var messageLabel: UILabel!
    var priceLabel: UILabel!
    var subPriceLabel: UILabel!
    var flagLabel: UILabel!
    var buyButton: UIButton!
    var lineView: UIView!
    // var addButton: UIButton!
    
//    var addEvent: (() -> Void)?
    var buyEvent: (() -> Void)?
    
    var dataSource: YHLiveGoodsItem = YHLiveGoodsItem() {
        didSet {
            if let url = URL(string: dataSource.image) {
                centerImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
            } else {
                centerImageView.image = UIImage(named: "global_default_image")
            }
            titleLabel.text = dataSource.name
            messageLabel.text = dataSource.description
            let a: ASAttributedString = .init("¥", .font(UIFont(name: "D-DIN-PRO-Bold", size: 14) ?? UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor))
            let linePrice = dataSource.linePrice.formattedPrice()
            let b: ASAttributedString = .init("\(linePrice)", .font(UIFont(name: "D-DIN-PRO-Bold", size: 20) ?? UIFont.PFSC_R(ofSize: 20)), .foreground(UIColor.mainTextColor))
            priceLabel.attributed.text = a + b
            let price = dataSource.price.formattedPrice()
            let c: ASAttributedString = .init("¥\(price)", .font(UIFont(name: "D-DIN-PRO-Medium", size: 14) ?? UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor(hex: 0x8993a2)), .strikethrough(.single))
            subPriceLabel.attributed.text = c
            flagLabel.text = "\(dataSource.flag)"
            subPriceLabel.isHidden = dataSource.linePrice == dataSource.price
        }
    }
    
    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() {
        self.backgroundColor = .clear
        
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        contentView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(0)
            make.height.equalTo(0.5)
            make.right.equalTo(-18)
        }
        
        centerImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "global_default_image")
            return imageView
        }()
        contentView.addSubview(centerImageView)
        centerImageView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(20)
            make.height.width.equalTo(98)
        }
        
        titleLabel = {
            let view = UILabel()
            // view.text = "高才A香港企明星(7)"
            view.font = UIFont.PFSC_M(ofSize: 17)
            view.textColor = UIColor.mainTextColor
            view.numberOfLines = 2
            return view
        }()
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(16)
            make.right.equalTo(-20)
            make.top.equalTo(centerImageView.snp.top)
            make.height.equalTo(22)
        }
        
        messageLabel = {
            let view = UILabel()
            // view.text = "高才A香港企明星(7)"
            view.font = UIFont.PFSC_M(ofSize: 13)
            view.textColor = UIColor(hex: 0x6d788a)
            view.numberOfLines = 2
            return view
        }()
        contentView.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(16)
            make.right.equalTo(-20)
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
            make.height.equalTo(22)
        }
        
        priceLabel = {
            let view = UILabel()
            return view
        }()
        contentView.addSubview(priceLabel)
        priceLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(16)
            make.right.equalTo(-20)
            make.bottom.equalTo(centerImageView.snp.bottom)
            make.height.equalTo(20)
        }
        
        subPriceLabel = {
            let view = UILabel()
            return view
        }()
        contentView.addSubview(subPriceLabel)
        subPriceLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(16)
            make.right.equalTo(-20)
            make.bottom.equalTo(priceLabel.snp.top).offset(-2)
            make.height.equalTo(20)
        }
        
        flagLabel = {
            let label = UILabel()
            label.textAlignment = .center
            label.textColor = .white
            label.font = UIFont.PFSC_M(ofSize: 10)
            label.backgroundColor = UIColor(hex: 0x000000).withAlphaComponent(0.5)
            return label
        }()
        centerImageView.addSubview(flagLabel)
        flagLabel.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.equalTo(24)
            make.height.equalTo(20)
        }
        
        buyButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor = UIColor.brandMainColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 11)
            button.contentHorizontalAlignment = .center
            button.setTitle("去抢购", for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.addTarget(self, action: #selector(buy), for: .touchUpInside)
            button.layer.cornerRadius = 2
            button.clipsToBounds = true
            return button
        }()
        contentView.addSubview(buyButton)
        buyButton.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.width.equalTo(68)
            make.bottom.equalTo(centerImageView.snp.bottom)
            make.height.equalTo(28)
        }
        
//        addButton = {
//            let button = UIButton(type: .custom)
//            button.backgroundColor = UIColor(hex: 0xebf0f9)
//            button.setImage(UIImage(named: "live_shop_add"), for: .normal)
//            button.contentHorizontalAlignment = .center
//            button.addTarget(self, action: #selector(add), for: .touchUpInside)
//            return button
//        }()
//        contentView.addSubview(addButton)
//        addButton.snp.makeConstraints { make in
//            make.right.equalTo(-88)
//            make.width.equalTo(46)
//            make.bottom.equalTo(centerImageView.snp.bottom)
//            make.height.equalTo(28)
//        }
    }

//    @objc func add() {
//        addEvent?()
//        //YHHUD.flash(message: "已加入购物车")
//    }
    
    @objc func buy() {
        buyEvent?()
        // YHHUD.flash(message: "已买")
    }
}
