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

import UIKit
import JXSegmentedView
import IQKeyboardManagerSwift

let isNeedShowAutoPictureMsg = "isNeedShowAutoPictureMsg"
let isNeedShowAIChatKeyBoard = "isNeedShowAIChatKeyBoard"

class YHAIServiceListViewController: YHBaseViewController {
    
    var serviceArr: [YHEntranceconfigModel] = []
    
    let viewModel = YHAIViewModel()
    let manager = YHAIRequestManager()

    lazy var collectionView: UICollectionView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumInteritemSpacing = 10.0
        flowLayout.minimumLineSpacing = 28.0
        flowLayout.scrollDirection = .vertical
        
        let collectView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectView.backgroundColor = .clear
        collectView.delegate = self
        collectView.dataSource = self
        collectView.register(YHAIProductCell.self, forCellWithReuseIdentifier: YHAIProductCell.cellReuseIdentifier)
        collectView.register(YHAIGreetCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: YHAIGreetCollectionReusableView.reuseIdentifier)
        collectView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "UICollectionReusableView")
        collectView.contentInset = .zero
        collectView.showsVerticalScrollIndicator = false
        return collectView
    }()
    
    lazy var bottomInputView: YHAITextInputView = {
        let v = YHAITextInputView(frame: .zero)
        v.backgroundColor = .clear
        v.disable = true
        let btn = UIButton()
        btn.addTarget(self, action: #selector(didInputButtonClicked), for: .touchUpInside)
        v.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        return v
    }()
    
    @objc func didInputButtonClicked() {
        let dict: [String: Any] = [isNeedShowAutoPictureMsg: false,
                                   isNeedShowAIChatKeyBoard: true]
        NotificationCenter.default.post(name: YhConstant.YhNotification.didSwitchToAIChatNotification, object: dict)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        IQKeyboardManager.shared.isEnabled = false

        view.backgroundColor = .clear
        view.addSubview(collectionView)
        view.addSubview(bottomInputView)

        collectionView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalToSuperview()
        }
        
        bottomInputView.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom).offset(8)
            make.left.right.bottom.equalToSuperview()
        }
    }
}

extension YHAIServiceListViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    // 返回单元格数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return serviceArr.count
    }
    
    // 返回每个单元格的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = floor((KScreenWidth-16.0*2.0-10.0)/2.0)
        let height = width * (200.0/166.0)
        return CGSize(width: width, height: height)
    }
    
    // 返回自定义单元格
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHAIProductCell.cellReuseIdentifier, for: indexPath) as? YHAIProductCell else {
            return UICollectionViewCell()
        }
        
        if 0 <= indexPath.item && indexPath.item < serviceArr.count {
            let model = serviceArr[indexPath.item]
            cell.model = model
            // 根据索引设置旋转
            cell.rotateToRight(indexPath.item % 2 == 0)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if 0 <= indexPath.item && indexPath.item < serviceArr.count {
            let model = serviceArr[indexPath.item]
            
            if model.redirectMode == 1 { // web页面
                if !model.redirectPath.isEmpty {
                    let vc = YHH5WebViewVC()
                    vc.url = model.redirectPath
                    UIViewController.current?.navigationController?.pushViewController(vc, animated: true)
                }
                
            } else if model.redirectMode == 2 {
                // customerVoice -> APP客户心声  productList -> APP-首页银河甄选  AppServiceTab -> 服务页
                if model.redirectPath == YHAIJumpPageType.customerHeart.rawValue {
                    // 客户心声
                    let vc = YHOtherServiceViewController()
                    vc.classID = 5
                    UIViewController.current?.navigationController?.pushViewController(vc)
                    
                } else if model.redirectPath == YHAIJumpPageType.galaxySelect.rawValue {
                    
                    YHAnalytics.track("APP_ChanPinZhenXuan")

                    // 银河甄选
                    let vc = YHSelectViewController()
                    vc.hideFlag = false
                    UIViewController.current?.navigationController?.pushViewController(vc, animated: true)
                    
                } else if model.redirectPath == YHAIJumpPageType.appServiceTab.rawValue {
                    
                    YHAnalytics.track("APP_FuWuJinDu")

                    // 服务页
                    UIViewController.current?.navigationController?.popToRootViewController(animated: false)
                    goTabBarBy(tabType: .service)
                }
                
            } else if model.redirectMode == 3 { // agent
                
                if model.businessType == YHAIRobotType.main.rawValue {
                    // 切到主Robot
                    let dict: [String: Any] = [isNeedShowAutoPictureMsg: true,
                                               isNeedShowAIChatKeyBoard: false]
                    NotificationCenter.default.post(name: YhConstant.YhNotification.didSwitchToAIChatNotification, object: dict)

                } else {
                    
                    if model.businessType == YHAIRobotType.education.rawValue {
                        YHAnalytics.track("APP_JiaoYuBao")
        
                    } else if model.businessType == YHAIRobotType.sale.rawValue {
                        YHAnalytics.track("APP_GuiHuaShi")
                    } else if model.businessType == YHAIRobotType.business.rawValue {
//                        YHAnalytics.track("APP_Gangxiaobao_Galaxy_Business_Planner")
                    }
                        
                    self.manager.getSubRobotChatConversationId(listItemId: "\(model.id)") {
                        sesseionId in
                        let vc = YHAIRobotChatViewController()
                        vc.isNeedShowBannerHeader = model.isNeedShowBannerHeader()
                        vc.myTitle = model.title
                        vc.robotId = model.redirectPath
                        vc.listItemId = model.id
                        vc.conversationId = sesseionId
                        vc.robotType = model.businessType
                        vc.title = model.titleName
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionView.elementKindSectionHeader {
            guard let headerView: YHAIGreetCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: YHAIGreetCollectionReusableView.reuseIdentifier, for: indexPath) as? YHAIGreetCollectionReusableView else {
                return UICollectionReusableView()
            }
            headerView.updateGreetingText()
            return headerView
        }
        
        let footerView: UICollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "UICollectionReusableView", for: indexPath)
        return footerView
         
    }
        
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection: Int) -> CGSize {
        
        return CGSize(width: KScreenWidth, height: 177)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection: Int) -> CGSize {
        
        return CGSize(width: KScreenWidth, height: 42.0)
    }
}

extension YHAIServiceListViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
