//
//  YHPreviewMainViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/1/29.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import GKNavigationBarSwift

class YHPreviewMainViewController: YHBaseViewController {
    private let previewVM: YHPreviewViewModel =  YHPreviewViewModel()
    
    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: YHPreviewControllerHoldViewController = {
        let ttt = YHPreviewControllerHoldViewController()
        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 YHPreviewMainViewController {
    func loadData() {
        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
            previewVM.getPreviewForMainApplicationInfo(params: ["order_id": orderID]) { success, _ 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 ?? "-"
                    self.phoneLable.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() {
        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 YHPreviewMainViewController: 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 YHPreviewMainViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let bottomCellOffset: CGFloat = homeTableView.rect(forSection: 0).origin.y
        if scrollView.contentOffset.y >= bottomCellOffset {
            scrollView.contentOffset = CGPoint(x: 0, y: 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 YHPreviewMainViewController {
    @objc func leaveTopOp() {
        canScroll = true
    }
    
    @objc func beginDragging() {
        homeTableView.isScrollEnabled = false
        canScroll = false
    }
    
    @objc func endDragging() {
        homeTableView.isScrollEnabled = true
        canScroll = true
    }
}
