//
//  YHSelectViewController.swift
//  galaxy
//
//  Created by EDY on 2024/11/26.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString
import JXSegmentedView

class YHSelectViewController: YHBaseViewController {
    var sectionView: YHSelectLookView!
    var tableView: UITableView!
    var headView: YHSelectLookHeadView!
    var viewModel: YHSelectViewModel = YHSelectViewModel()
    var selectItem: Int = 0
    var buttonItem: Int = 0

    var selectMenuView: YHSelectMenuView!
    var canShowMenu: Bool = true
    var hideFlag: Bool = false

    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无产品", kEmptyCommonBgName)
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.viewModel.getLiveList {[weak self] _, _ in
            guard let self = self else { return }
            self.sectionView.items = self.viewModel.liveArr
            if self.viewModel.liveArr.count == 0 {
                sectionView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 0)
            } else {
                sectionView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 92)
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.selectMenuView != nil {
            self.selectMenuView.removeFromSuperview()
        }
    }
}

extension YHSelectViewController {
    func loadData() {
        self.viewModel.getCategoryList {[weak self] _, _ in
            guard let self = self else { return }
            var dataSource: [String] = []
            for item in self.viewModel.categoryArray {
                dataSource.append(item.name)
            }
            self.headView.items = dataSource
        }
        var id = "0"
        if selectItem < self.viewModel.categoryArray.count {
            let model = self.viewModel.categoryArray[selectItem]
            id = model.id
        }
        self.viewModel.getGoodsList(categoryID: id, sortType: 0) {[weak self] _, _ in
            guard let self = self else { return }
            self.tableView.reloadData()
            if self.viewModel.goodsArray.count == 0 {
                noDataView.isHidden = false
            } else {
                noDataView.isHidden = true
            }
        }
        self.viewModel.getLiveList {[weak self] _, _ in
            guard let self = self else { return }
            self.sectionView.items = self.viewModel.liveArr
            if self.viewModel.liveArr.count == 0 {
                sectionView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 0)
            } else {
                sectionView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 92)
            }
        }
    }
    
    func updataData() {
        if selectItem < self.viewModel.categoryArray.count {
            let model = self.viewModel.categoryArray[selectItem]
            self.viewModel.getGoodsList(categoryID: model.id, sortType: buttonItem) {[weak self] _, _ in
                guard let self = self else { return }
                self.tableView.reloadData {
                    if self.viewModel.liveArr.count != 0 {
                        self.tableView.setContentOffset(CGPoint(x: 0, y: 92), animated: true)
                    }
                }
                if self.viewModel.goodsArray.count == 0 {
                    noDataView.isHidden = false
                } else {
                    noDataView.isHidden = true
                }
            }
        }
    }
    
    func setupUI() {
        if hideFlag {
            gk_navigationBar.isHidden = true
        } else {
            gk_navTitle = "银河甄选"
        }
        view.backgroundColor = .white
        sectionView = {
            let view = YHSelectLookView()
            return view
        }()
        sectionView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 92)
        headView = {
            let head = YHSelectLookHeadView()
            head.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 78)
            head.block = { index in
                self.selectItem = index
                self.buttonItem = 0
                self.updataData()
            }
            head.buttonBlock = { index in
            self.buttonItem = index
                self.updataData()
            }
            return head
        }()
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .plain)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .white
            tableView.separatorStyle = .none
            tableView.showsHorizontalScrollIndicator = false
            tableView.showsVerticalScrollIndicator = false
            tableView.dataSource = self
            tableView.delegate = self
            tableView.tableHeaderView = sectionView
            tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 250))
            tableView.register(cellWithClass: YHSelectLookTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            if hideFlag {
                make.top.equalToSuperview()
            } else {
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            }
        }
        
        tableView.es.addYHPullToRefresh {
            self.loadData()
            self.tableView.es.stopPullToRefresh()
        }
         
        tableView.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(150)
        }
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
    }
}

extension YHSelectViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.goodsArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHSelectLookTableViewCell.self)
        cell.number = indexPath.row
        cell.dataSource = self.viewModel.goodsArray[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 102
        }
        return 114
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 66
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        if selectItem < self.viewModel.categoryArray.count {
//            let model = self.viewModel.categoryArray[selectItem]
//            headView.itemButton.setTitle(model.name, for: .normal)
//            headView.itemButton.iconInRight(with: 0.5)
//        }
        return headView
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.viewModel.goodsArray[indexPath.row]
        var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/goods/sales-detail" + "?id=\(model.id)"
        YHAnalytics.track("APP_GalaxySelectionPage_ClickProduct", properties: ["productID": model.id])

        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
        // 进详情页关闭小窗
        YHPlayerManager.shared.exitFloating()
        UIViewController.current?.navigationController?.pushViewController(vc)
    }
}

extension YHSelectViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
    
    func listWillDisappear() {
//        self.headView.itemButton.isSelected = false
//        if (self.selectMenuView != nil) {
//            self.selectMenuView.removeFromSuperview()
//        }
    }
}

class YHSelectLookTableViewCell: UITableViewCell {
    var centerImageView: UIImageView!
    var titleLabel: UILabel!
    var subTitleLabel: UILabel!
    var flagLabel: UILabel!
    var itemView: UIView!
    var number: Int = 100
    var dataSource: YHSelectGoodsModel? {
        didSet {
            guard let dataSource = dataSource else { return }
            if number == 0 {
                centerImageView.snp.remakeConstraints { make in
                    make.bottom.equalTo(-20)
                    make.left.equalTo(20)
                    make.height.width.equalTo(74)
                }
            }
            self.titleLabel.text =  dataSource.name
            flagLabel.isHidden = true
            if dataSource.catAttr == 2 {
                flagLabel.isHidden = false
            }
            let currencyString = (dataSource.currency == "HKD") ? "HK$" : "¥"
            let a: ASAttributedString = .init("\(currencyString)", .font(UIFont(name: "D-DIN-PRO-Medium", size: 14) ?? UIFont.PFSC_M(ofSize: 14)), .foreground(UIColor.mainTextColor))
            let b: ASAttributedString = .init("\(dataSource.linePrice.formattedPrice()) ", .font(UIFont(name: "D-DIN-PRO-Bold", size: 20) ?? UIFont.PFSC_B(ofSize: 20)), .foreground(UIColor.mainTextColor))
            let c: ASAttributedString = .init("\(currencyString)\(dataSource.price.formattedPrice())", .font(UIFont(name: "D-DIN-PRO-Medium", size: 14) ?? UIFont.PFSC_M(ofSize: 14)), .foreground(UIColor(hex: 0x8993a2)), .strikethrough(.single))
            if dataSource.linePrice == dataSource.price {
                self.subTitleLabel.attributed.text = a + b
            } else {
                self.subTitleLabel.attributed.text = a + b + c
            }
            itemView.removeSubviews()
            var i = 0
            for item in dataSource.icons {
                let label = UILabel()
                label.text = " " + item.description + " "
                label.textColor = UIColor(hexString: item.color)
                label.font = UIFont.PFSC_R(ofSize: 10)
                label.tag = 100 + i
                label.layer.borderWidth = 0.5
                label.layer.borderColor = UIColor(hexString: item.color)?.withAlphaComponent(0.3).cgColor
                itemView.addSubview(label)
                label.snp.makeConstraints { make in
                    make.top.equalToSuperview()
                    make.height.equalTo(16)
                    if i == 0 {
                        make.left.equalTo(0)
                    } else {
                        let view = itemView.viewWithTag(100 + i - 1)
                        make.left.equalTo(view?.snp.right ?? 0).offset(4)
                    }
                }
                i += 1
            }
            guard let url = URL(string: dataSource.image) else { return }
            self.centerImageView.kf.setImage(with: url)
        }
    }
    
    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 = .white
        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(74)
        }
        
        titleLabel = {
            let view = UILabel()
            view.text = "高才A香港企明星(7)"
            view.font = UIFont.PFSC_M(ofSize: 16)
            view.textColor = UIColor.mainTextColor
            view.numberOfLines = 2
            return view
        }()
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(12)
            make.right.equalTo(-20)
            make.top.equalTo(centerImageView.snp.top)
            make.height.equalTo(22)
        }
        
        subTitleLabel = {
            let view = UILabel()
            let a: ASAttributedString = .init("¥", .font(UIFont.PFSC_B(ofSize: 14)), .foreground(UIColor.mainTextColor))
            let b: ASAttributedString = .init("61000", .font(UIFont.PFSC_B(ofSize: 20)), .foreground(UIColor.mainTextColor))
            let c: ASAttributedString = .init("¥61000", .font(UIFont.PFSC_M(ofSize: 14)), .foreground(UIColor(hex: 0x8993a2)), .strikethrough(.single))
            view.attributed.text = a + b + c
            return view
        }()
        contentView.addSubview(subTitleLabel)
        subTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(12)
            make.right.equalTo(-20)
            make.bottom.equalTo(centerImageView.snp.bottom)
            make.height.equalTo(20)
        }
        
        flagLabel = {
            let label = UILabel()
            label.text = "套餐"
            label.textAlignment = .center
            label.textColor = .white
            label.backgroundColor = .brandMainColor
            label.font = UIFont.PFSC_R(ofSize: 10)
            return label
        }()
        centerImageView.addSubview(flagLabel)
        flagLabel.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.equalTo(28)
            make.height.equalTo(16)
        }
        
        itemView = {
            let view = UIView()
            return view
        }()
        contentView.addSubview(itemView)
        itemView.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(12)
            make.right.equalTo(-20)
            make.top.equalTo(centerImageView.snp.top).offset(26)
            make.height.equalTo(18)
        }
        let line = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        contentView.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
    }

}
