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

import UIKit
import GKNavigationBarSwift

class YHGCPreviewMainViewController: YHBaseViewController {
    var productType : Int = 0 //0-优才  1-高才A 2-高才B 3-高才C
    private let previewVM : YHGCPreviewViewModel =  YHGCPreviewViewModel()
    
    var orderId : Int?
    
    var canScroll : Bool = true
    var myCellHeight : CGFloat {
        get {
            return view.bounds.size.height - k_Height_NavigationtBarAndStatuBar
        }
    }
    
    var myDefaultIndex : Int = 0 {
        didSet {
            DispatchQueue.global().asyncAfter(wallDeadline: .now() ) {[weak self] in
                DispatchQueue.main.async {
                    self?.cellView.myDefaultNavItemIndex = self?.myDefaultIndex ?? 0
                }
            }
        }
    }
    
    lazy var cellView: YHGCPreviewControllerHoldViewController = {
        let ttt = YHGCPreviewControllerHoldViewController()
        ttt.productType = self.productType
        ttt.myDefaultNavItemIndex = self.myDefaultIndex
        return ttt
    }()
    
    var homeTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    
    var myHeadView : UIView = {
        let view = UIView(frame: CGRect(x: kMargin, y: 0, width: KScreenWidth - kMargin * 2, height: 131))
        view.backgroundColor = .white
        return view
    }()
    
    
    //头像
    private lazy var headImagV : UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "mine_head_default"))
        imageV.contentMode = .scaleAspectFill
        imageV.layer.cornerRadius = 26.5
        imageV.clipsToBounds = true
        imageV.layer.borderWidth = 2
        imageV.layer.borderColor = UIColor.white.cgColor
        return imageV
    }()
    
    //姓名
    private lazy var nameLable : UILabel = {
        let lable0 = UILabel(text: "")
        lable0.textColor = UIColor.mainTextColor
        lable0.font = UIFont.PFSC_M(ofSize: 19)
        return lable0
    }()
    
    //电话号码
    private lazy var phoneLable : UILabel = {
        let lable0 = UILabel(text: "")
        lable0.textColor = UIColor.labelTextColor2
        lable0.font = UIFont.PFSC_R(ofSize: 14)
        return lable0
    }()
    
    
    // MARK: - 生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(leaveTopOp), name:Notification.Name(rawValue: "leaveTop0"), object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(beginDragging), name:Notification.Name(rawValue: "scrollViewWillBeginDragging0"), object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(endDragging), name:Notification.Name(rawValue: "scrollViewDidEndDragging0"), object: nil)
        
        //1.UI
        initView()
        
        //2.网络请求
        loadData()
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        cellView.view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: myCellHeight)
    }
}

// MARK: - 私有方法
extension YHGCPreviewMainViewController {
    func loadData() {
        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
            previewVM.getPreviewForMainApplicationInfo(params: ["order_id" : orderID]) { success, error in
                if success == true {
                    
                    var title = ""
                    if let tmp = self.previewVM.mainApplicationInfoPreviewModel?.username,tmp.isEmpty == false {
                        title = tmp + "的个人信息表"
                    } else {
                        title = "未知 "
                    }
                    
                    self.nameLable.text = title
//                    self.phoneLable.text = self.previewVM.mainApplicationInfoPreviewModel?.mobile ?? "-"
                    
                    var text = "高才"
                    // 1-高才A 2-高才B 3-高才C
                    if self.productType == 1 {
                        text = "高才A类"
                        
                    } else if self.productType == 2 {
                        text = "高才B类"
                        
                    } else if self.productType == 3 {
                        text = "高才C类"
                    }
                    self.phoneLable.text = text
//                    self.handleHeaderIcon()
                    
                } else {
                    
                }
                self.homeTableView.reloadData()
            }
        } else {
            printLog("error : orderID 为空")
        }
    }
    
    private func handleHeaderIcon() {
        
        //缺少头像字段
//        guard let model = previewVM.mainApplicationInfoPreviewModel,let icon = model. else {
//            return
//        }
//        previewVM.getPublicImageUrl(imgString) {[weak self] success, error in
//            guard let self = self else { return }
//            guard success != nil else { return }
//            self.resultView.kf.setImage(with: URL(string: success))
//        }
    }
    
    private func initView()->Void {
        gk_navigationBar.isHidden = false
        gk_backStyle = .black
        gk_navTitle = "预览"
        gk_navBackgroundColor = .white
        gk_navTitleColor = UIColor(hex:0x0F1214)
        gk_navBarAlpha = 1
        gk_navTitleFont = UIFont.PFSC_B(ofSize: 17)
        
        
        
        homeTableView.delegate = self
        homeTableView.dataSource = self
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.bottom.equalToSuperview()
        }
        
        homeTableView.tableHeaderView = myHeadView
        
        
        let headSubView = UIView()
        headSubView.backgroundColor = .clear
        headSubView.layer.cornerRadius = kCornerRadius6
        headSubView.clipsToBounds = true
        myHeadView.addSubview(headSubView)
        headSubView.snp.makeConstraints { make in
            make.top.equalTo(17)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(105)
        }
        
        let bkgImageV = UIImageView(image: UIImage(named: "person_info_head_bkg"))
        bkgImageV.contentMode = .scaleAspectFill
        headSubView.addSubview(bkgImageV)
        bkgImageV.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
        
        
        // 头像 名称 电话号码
        headSubView.addSubview(headImagV)
        headImagV.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(20.5)
            make.width.height.equalTo(53)
        }
       
        
        
        headSubView.addSubview(nameLable)
        nameLable.snp.makeConstraints { make in
            make.top.equalTo(headImagV.snp.top)
            make.left.equalTo(headImagV.snp.right).offset(12)
            make.height.equalTo(26.5)
            make.right.equalTo(-kMargin)
        }
        
        headSubView.addSubview(phoneLable)
        phoneLable.snp.makeConstraints { make in
            make.top.equalTo(nameLable.snp.bottom)
            make.left.equalTo(headImagV.snp.right).offset(12)
            make.height.equalTo(20)
            make.right.equalTo(-20.5)
        }
    }
}

// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHGCPreviewMainViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.001))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.001))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return myCellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cellView.view.frame = CGRect(x: 0, y: 0, width: cell.contentView.bounds.size.width, height: myCellHeight)
        cell.contentView.addSubview(cellView.view)
        cellView.view.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension YHGCPreviewMainViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let bottomCellOffset: CGFloat = homeTableView.rect(forSection: 0).origin.y
        if (scrollView.contentOffset.y >= bottomCellOffset) {
            scrollView.contentOffset = CGPointMake(0, bottomCellOffset)
            if canScroll == true {
//                canScroll = false
//                //传递参数到 子VC
//                cellView.canScroll = true
            }
            
            canScroll = false
            //传递参数到 子VC
            cellView.canScroll = true
        }else{
            if canScroll == false {
                scrollView.contentOffset = CGPoint(x: 0, y: bottomCellOffset)
            }
        }
        self.homeTableView.showsVerticalScrollIndicator = false
    }
}

extension YHGCPreviewMainViewController {
    @objc func leaveTopOp() {
        canScroll = true
    }
    
    @objc func beginDragging() {
        homeTableView.isScrollEnabled = false
        canScroll = false
    }
    
    @objc func endDragging() {
        homeTableView.isScrollEnabled = true
        canScroll = true
    }
}
