//
//  YHLiveAppointmentViewController.swift
//  galaxy
//
//  Created by alexzzw on 2024/12/28.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHLiveAppointmentViewController: YHBaseViewController {
    private let viewModel = YHLiveSalesViewModel()
    private var liveInfo: YHShareLiveInfoModel?
    private lazy var topImageView: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFit
        return view
    }()
    
    private lazy var topbgImageView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "global_default_image_bg")
        return view
    }()

    private lazy var centerContainerView: YHBaseDynamicCornerRadiusView = {
        let view = YHBaseDynamicCornerRadiusView(cornerRadius: 6, corner: .allCorners)
        view.backgroundColor = .white
        return view
    }()

    private lazy var flagLabel: YHPaddedLabel = {
        let label = YHPaddedLabel(padding: UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4))
        label.text = "预告"
        label.font = .PFSC_R(ofSize: 10)
        label.backgroundColor = .brandMainColor
        label.textColor = .white
        return label
    }()

    private lazy var liveNameLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_B(ofSize: 16)
        label.textColor = .mainTextColor
        return label
    }()

    private lazy var avatarImageView: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFit
        view.clipsToBounds = true
        view.layer.cornerRadius = 10
        return view
    }()

    private lazy var anchorLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textColor = UIColor(hexString: "#435163")
        return label
    }()

    private lazy var subContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .contentBkgColor
        return view
    }()

    private lazy var infoContentLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textColor = UIColor(hexString: "#435163")
        label.numberOfLines = 0
        label.lineBreakMode = .byCharWrapping
        return label
    }()

    private lazy var infoTimeLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_B(ofSize: 14)
        label.textColor = UIColor.brandMainColor
        return label
    }()

    private lazy var appointmentButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        button.setTitle("立即预约", for: .normal)
        button.setTitle("立即预约", for: .highlighted)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .normal)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .highlighted)
        button.addTarget(self, action: #selector(clickAppointmentButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .brandMainColor
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        getLiveInfo()
    }
    
    private let liveId: Int
    init(liveId: Int) {
        self.liveId = liveId
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        gk_navTitle = "直播预约"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
        
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(topImageView)
        topImageView.addSubview(topbgImageView)
        view.addSubview(centerContainerView)
        centerContainerView.addSubview(flagLabel)
        centerContainerView.addSubview(liveNameLabel)
        centerContainerView.addSubview(avatarImageView)
        centerContainerView.addSubview(anchorLabel)
        centerContainerView.addSubview(subContainerView)
        subContainerView.addSubview(infoContentLabel)
        centerContainerView.addSubview(infoTimeLabel)
        centerContainerView.addSubview(appointmentButton)
        topImageView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.width.equalTo(topImageView.snp.height)
        }
        topbgImageView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(100)
        }
        centerContainerView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalTo(topImageView.snp.bottom).offset(-74)
        }
        flagLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        liveNameLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        flagLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(18)
        }
        liveNameLabel.snp.makeConstraints { make in
            make.left.equalTo(flagLabel.snp.right).offset(8)
            make.centerY.equalTo(flagLabel)
            make.right.lessThanOrEqualToSuperview().offset(-16)
        }
        avatarImageView.snp.makeConstraints { make in
            make.left.equalTo(flagLabel)
            make.top.equalTo(flagLabel.snp.bottom).offset(10)
            make.width.height.equalTo(20)
        }
        anchorLabel.snp.makeConstraints { make in
            make.left.equalTo(avatarImageView.snp.right).offset(4)
            make.centerY.equalTo(avatarImageView)
            make.right.lessThanOrEqualToSuperview().offset(-16)
        }
        subContainerView.snp.makeConstraints { make in
            make.left.equalTo(flagLabel)
            make.right.equalToSuperview().offset(-16)
            make.top.equalTo(avatarImageView.snp.bottom).offset(8)
        }
        infoContentLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(12)
            make.right.lessThanOrEqualToSuperview().offset(-12)
            make.bottom.equalToSuperview().offset(-12)
        }
        infoTimeLabel.snp.makeConstraints { make in
            make.left.equalTo(flagLabel)
            make.top.equalTo(subContainerView.snp.bottom).offset(12)
            make.right.lessThanOrEqualToSuperview().offset(-16)
        }
        appointmentButton.snp.makeConstraints { make in
            make.left.equalTo(flagLabel)
            make.top.equalTo(infoTimeLabel.snp.bottom).offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(46)
            make.bottom.equalToSuperview().offset(-16)
        }
    }
    
    private func updateViews(_ liveInfo: YHShareLiveInfoModel) {
        if let url = URL(string: liveInfo.image) {
            topImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
        } else {
            topImageView.image = UIImage(named: "global_default_image")
        }
        if let url = URL(string: liveInfo.avatar) {
            avatarImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
        } else {
            avatarImageView.image = UIImage(named: "global_default_image")
        }
        liveNameLabel.text = liveInfo.title
        anchorLabel.text = liveInfo.account
        let content = liveInfo.watch
        
        if content.isEmpty {
            infoContentLabel.text = content
            infoContentLabel.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(0)
                make.left.equalToSuperview().offset(12)
                make.right.lessThanOrEqualToSuperview().offset(-12)
                make.bottom.equalToSuperview().offset(0)
            }
        } else {
            infoContentLabel.text = "直播看点：\n" + content
            infoContentLabel.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(12)
                make.left.equalToSuperview().offset(12)
                make.right.lessThanOrEqualToSuperview().offset(-12)
                make.bottom.equalToSuperview().offset(-12)
            }
        }
        var timeStr = "直播时间：" + liveInfo.start_time
        if !liveInfo.end_time.isEmpty, !liveInfo.start_time.isEmpty {
            let endTime = isSameDayAndGetShortEndTime(date1String: liveInfo.start_time, date2String: liveInfo.end_time)
            timeStr += "~" + endTime
        }
        infoTimeLabel.text = timeStr
        updateAppointmentButton(!liveInfo.is_schedule_live)
    }
    
    private func isSameDayAndGetShortEndTime(date1String: String, date2String: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM月dd日HH:mm"
        let date1 = dateFormatter.date(from: date1String)
        let date2 = dateFormatter.date(from: date2String)
        guard let date1 = date1, let date2 = date2 else {
            return date2String
        }
        let calendar = Calendar.current
        let components1 = calendar.dateComponents([.month, .day, .hour, .minute], from: date1)
        let components2 = calendar.dateComponents([.month, .day, .hour, .minute], from: date2)
        if components1.month == components2.month &&
            components1.day == components2.day {
            let hour = components2.hour ?? 0
            let minute = components2.minute ?? 0
            return String(format: "%02d:%02d", hour, minute)
        }
        return date2String
    }

    private func updateAppointmentButton(_ isEnable: Bool) {
        appointmentButton.isEnabled = isEnable
        appointmentButton.backgroundColor = isEnable ? .brandMainColor : UIColor(hexString: "#B3C8E9")
        appointmentButton.setTitle(isEnable ? "立即预约" : "已预约", for: .normal)
    }
    
    @objc private func share() {
        guard let liveInfo = liveInfo else {
            return
        }
        DispatchQueue.global().async {
            YHShareManager.shared.createMutilShareShortUrl(type: 1, param: ["LiveID": String(self.liveId)]) { shortUrl, _ in
                if let url = shortUrl {
                    let tmpT = url.base64Encoded ?? ""// 对deepLink使用 base64编码
                    var oldUrl = liveInfo.live_h5_url
                    if oldUrl.contains("?") {
                        oldUrl += "&appDeepLink=\(tmpT)"
                    } else {
                        oldUrl += "?appDeepLink=\(tmpT)"
                    }
                    
                    DispatchQueue.main.async {
                        YHShareAlertView.show(image: liveInfo.image, title: "@" + liveInfo.account, subMessage: liveInfo.title, linkUrl: oldUrl, isLive: true, fromAiSale: true)
                    }
                    return
                }
                DispatchQueue.main.async {
                    YHShareAlertView.show(image: liveInfo.image, title: "@" + liveInfo.account, subMessage: liveInfo.title, linkUrl: liveInfo.live_h5_url, isLive: true, fromAiSale: true)
                }
            }
        }
    }

    @objc private func clickAppointmentButton() {
        bookLive()
    }
    
    private func getLiveInfo() {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getShareLiveInfo(liveId: liveId, shareType: 1) { [weak self] liveInfo, error in
            guard let self = self else {
                return
            }
            YHHUD.hide()
            guard let liveInfo = liveInfo else {
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                return
            }
            self.liveInfo = liveInfo
            self.updateViews(liveInfo)
        }
    }
    
    private func bookLive() {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.postLiveBook(id: liveId) { [weak self] success, error in
            guard let self = self else {
                return
            }
            YHHUD.hide()
            if success {
                self.updateAppointmentButton(false)
            } else {
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
}
