Newer
Older
Meterage_iOS / Meterage / ViewControllers / Home / HomePageViewController.swift
//
//  HomePageViewController.swift
//  Meterage
//
//  Created by 203 on 2023/2/1.
//

import Alamofire
import DefaultsKit
import SnapKit
import SwiftyJSON
import UIKit
import IQKeyboardManagerSwift

class HomePageViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var searchBorderView: UIView!
    @IBOutlet weak var inputTextView: UITextField!
    @IBOutlet weak var noticeView: UIImageView!
    @IBOutlet weak var noticeCountView: UILabel!
    @IBOutlet weak var noticeLayout: UIView!
    @IBOutlet weak var noticeContentView: UILabel!
    @IBOutlet weak var noticeTimeView: UILabel!
    @IBOutlet weak var reminderContentView: UIView!
    @IBOutlet weak var reminderTableView: UITableView!

    private var collectionView: UICollectionView!

    private let keyboardManager = IQKeyboardManager.shared
    private let defaults = Defaults.shared
    private let device = DeviceSizeUtil.shared

    override func viewDidLoad() {
        super.viewDidLoad()
        keyboardManager.enable = true
        keyboardManager.keyboardDistanceFromTextField = 30
        keyboardManager.shouldResignOnTouchOutside = true
        keyboardManager.toolbarDoneBarButtonItemText = "完成"
        // 首页 Tab页不显示导航标题
        navigationController?.setNavigationBarHidden(true, animated: false)
        // Do any additional setup after loading the view.

        /// 顶部搜索栏
        searchBorderView.layer.borderColor = UIColor.mainThemeColor.cgColor
        searchBorderView.layer.borderWidth = 1
        searchBorderView.layer.cornerRadius = 17.5
        searchBorderView.layer.masksToBounds = true

        /// 给UIImageView添加点击事件
        let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(imageViewClick))
        noticeView.addGestureRecognizer(singleTapGesture)
        noticeView.isUserInteractionEnabled = true
        
        noticeCountView.layer.cornerRadius = 7
        noticeCountView.layer.masksToBounds = true

        // 数据请求
        let token = defaults.get(for: tokenKey) ?? ""
        let baseURL = defaults.get(for: serverConfigKey)!
        let noticeListURL = baseURL + Constant.noticeList.rawValue + "?limit=20&offset=1"
        let paramDic: [String: Any] = ["noticeNo": "", "noticeTitle": "", "noticePublisher": "", "noticeStartTime": "", "noticeEndTime": ""]
        Alamofire.request(HttpRequestCreator.shared.createPostRequest(url: noticeListURL, dic: paramDic, token: token)).responseJSON { [self] response in
            switch response.result {
            case let .success(value):
                let notice = NoticeListModel(respJson: JSON(value)).data
                if notice.total > 9 {
                    noticeCountView.text = "9+"
                } else {
                    noticeCountView.text = String(notice.total)
                }
            case .failure:
                AlertHub.shared.showWaringAlert(controller: self, message: "请求失败,请检查网络")
            }
        }

        /// 九宫格
        let layout = UICollectionViewFlowLayout()
        // 宽高
        layout.itemSize = CGSize(width: SCREEN_WIDTH / 6, height: CGFloat(5) + SCREEN_WIDTH / 6)
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        collectionView.register(UINib(nibName: "HomeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "homeCollectionViewCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.isScrollEnabled = false
        view.addSubview(collectionView)
        // 计算View高度
        let collectionViewHeight = CGFloat(3 * Int(layout.itemSize.height))
        // 动态布局
        collectionView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(SCREEN_WIDTH - 20)
            make.height.equalTo(collectionViewHeight)
            // 距离searchBorderView底部10
            make.top.equalTo(searchBorderView.snp.bottom).offset(10)
        }

        /// 滚动消息条
        noticeLayout.layer.cornerRadius = 7
        noticeLayout.layer.masksToBounds = true
        noticeLayout.backgroundColor = .white
        view.addSubview(noticeLayout)
        noticeLayout.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(SCREEN_WIDTH - 20)
            make.height.equalTo(BUTTON_HEIGHT)
            // 距离searchBorderView底部10
            make.top.equalTo(collectionView.snp.bottom).offset(15)
        }

        /// 下部待办列表
        reminderContentView.layer.cornerRadius = 7
        reminderContentView.layer.masksToBounds = true
        reminderContentView.backgroundColor = .white
        view.addSubview(reminderContentView)
        // 计算View高度
        let safeAreaHeight = device.getSafeAreaFrame(self).height
        // Home页没有navigationBar,高度需要加上34
        let reminderViewHeight = safeAreaHeight - searchBorderView.bounds.height - collectionViewHeight - noticeLayout.bounds.height - 3 * 10 + 34
        reminderContentView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(SCREEN_WIDTH - 20)
            make.height.equalTo(reminderViewHeight)
            make.top.equalTo(noticeLayout.snp.bottom).offset(10)
        }

        reminderTableView.register(UINib(nibName: "ReminderTableViewCell", bundle: nil), forCellReuseIdentifier: "reminderTableViewCell")
        reminderTableView.delegate = self
        reminderTableView.dataSource = self
        reminderTableView.separatorColor = .hintColor
        reminderTableView.backgroundColor = .clear
        reminderTableView.tableFooterView = UIView(frame: CGRect.zero)
    }

    /// 消息图标点击事件
    @objc func imageViewClick(){
        let destinationController = NoticeListViewController(nibName: "NoticeListViewController", bundle: nil)
        let navigation = UINavigationController(rootViewController: destinationController)
        navigation.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        present(navigation, animated: true, completion: nil)
    }
    
    /// UICollectionView
    // 显示多少个Item
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        HOME_FUNC_OPERATE.count
    }

    // 每个cell显示的内容
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: HomeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "homeCollectionViewCell", for: indexPath) as! HomeCollectionViewCell
//        cell.funcImageView.image = UIImage(named: MINE_IMAGE_ARRAY[indexPath.row])
        cell.funcTitleView.text = HOME_FUNC_OPERATE[indexPath.row]
        return cell
    }

    /// UITableView
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        45
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        REMINDER_PROCESS_ARRAY.count
    }

    private let REMINDER_PROCESS_ARRAY = ["审批", "提醒", "审批", "校准", "校准", "校准", "校准", "校准"]
    private let REMINDER_TITLE_ARRAY = ["计量检定合同", "万用表校准", "计量检定合同", "万用表校准", "万用表校准", "万用表校准", "万用表校准", "万用表校准"]
    private let REMINDER_TIME_ARRAY = ["3小时前", "13小时前", "23小时前", "6-11", "6-11", "6-11", "6-11", "6-11"]

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: ReminderTableViewCell = tableView.dequeueReusableCell(withIdentifier: "reminderTableViewCell", for: indexPath) as! ReminderTableViewCell
        cell.reminderProcessView.text = REMINDER_PROCESS_ARRAY[indexPath.row]
        cell.reminderTitleView.text = REMINDER_TITLE_ARRAY[indexPath.row]
        cell.reminderTimeView.text = REMINDER_TIME_ARRAY[indexPath.row]
//        if(){
//            cell.reminderStateView
//        }else{
//            cell.reminderStateView
//        }
        //设置分割线上下左右边距
        cell.separatorInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
        cell.selectionStyle = .none
        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    }
}