//
//  HomeViewController.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/9/4.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit

class HomeViewController: BaseViewController,UIPopoverPresentationControllerDelegate {
    @objc
    
    var dataSource = NSMutableArray()
    var delegate:HomeViewControllerDelegate!
    var cellNum:Double = 4
    var offsetY:CGFloat = 0
    
    
    var bannerArray = NSMutableArray()
    var classArray = NSMutableArray()
    var headlinesTitleArray = NSMutableArray()
    var headlinesArray = NSMutableArray()
    
    var carouseCellModel = HomeCarouselTableViewCellModel()
    var detailedModel = MineDetailedTableViewCellModel()
    var detailModel = MineCollectionViewCellModel()
    var headlinesMoreCellModel = HeadlinesMoreTableViewCellModel()
    
    var companyListModelArray = NSMutableArray()
    var departmentListModelArray = NSMutableArray()
    var selecClassModel:ApplicationHttpListModel!
    
    //顶部刷新
    var header = MJRefreshNormalHeader()
    //底部刷新
    var footer = MJRefreshAutoNormalFooter()
    var page = 0
    var httpInfoModel = HomeHttpInfoModel()
    var placeholderString:String!
    
    lazy var searchTextField : SearchTextField = {
        let searchTextField = SearchTextField.init(frame: CGRect(x:90*WHIDTH_RATIO(), y: 7, width: SCREEN_WHIDTH()-(90+55)*WHIDTH_RATIO() , height:30 ))
        searchTextField.isEnabled = false
        //        searchTextField.delegate = self
        return searchTextField;
    }()
    lazy var addN : UIBarButtonItem = {
        let addImageView:UIImageView = UIImageView.init(frame: CGRect(x:16, y: 8, width:20 , height:20 ))
        addImageView.contentMode = .scaleAspectFit
        addImageView.image = UIImage.init(named: "add_image")
        let addBtn:UIButton = UIButton.init(type: .custom)
        addBtn.frame = CGRect(x:0, y: 0, width:36 , height:36)
        addBtn.contentMode = .scaleAspectFit
        addBtn.addTarget(self, action: #selector(shouwPopover), for: .touchUpInside)
        addBtn.addSubview(addImageView)
        let addN:UIBarButtonItem = UIBarButtonItem.init(customView: addBtn)
        return addN;
    }()
    
    lazy var myTableView: UITableView = {
        let myTableView = UITableView.init()
        self.view.addSubview(myTableView)
        myTableView.snp.makeConstraints { (make) in
            make.width.height.equalToSuperview()
            make.center.equalToSuperview()
        }
        if #available(iOS 11.0, *) {
            myTableView.contentInsetAdjustmentBehavior = .never
            myTableView.scrollIndicatorInsets = myTableView.contentInset
//            myTableView.contentInset = UIEdgeInsetsMake(UIApplication.shared.statusBarFrame.size.height, 0, 0, 0)
            myTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }else{
            myTableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0)
        }
        registerCell(myTableView, cell: HomeCarouselTableViewCell.self)
        registerCell(myTableView, cell: MineDetailedTableViewCell.self)
        registerCell(myTableView, cell: AdvisoryTableViewCell.self)
        registerCell(myTableView, cell: HeadlinesMoreTableViewCell.self)
        registerCell(myTableView, cell: MineTitleTableViewCell.self)
        registerCell(myTableView, cell: MineDetailedTableViewCell.self)
        registerCell(myTableView, cell: MineWebTableViewCell.self)
        myTableView.backgroundColor = UIColorFromRGB(rgbValue: 0xF4F9FD)
        setExtraCellLineHidden(tableView: myTableView)
        return myTableView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        hideNavigationBar()
//        WRNavigationBar.wr_setDefaultNavBarBarTintColor(statusBarColor)
//        addNotificationCenter()
        self.appViewsSstatistics(title: "首页", scope: AppClickType.OftenAppType.rawValue)
        self.wr_setNavBarBarTintColor(statusBarColor)
        self.wr_setNavBarBackgroundAlpha(0)
        if #available(iOS 13.0, *) {
            if SCREEN_HEIGHT() >= 812 {
                self.wr_setNavBarShadowImageHidden(true)
            }
        } else {
            self.wr_setNavBarShadowImageHidden(true)
        }
        isAccess_tokenTrue()
        judgmentLoginTypeHttpAction()
        judgmentDeactivateEnableHome()
        getUnReadNumberHttpPostCmd()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        NotificationCenter.default.removeObserver(self)
//        addRemoveObserver()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        initTitleBar()
        initReturnBtn()
        
//        addSearchBar()
        NotificationCenter.default.addObserver(self, selector: #selector(actionHttpGCD), name: NSNotification.Name(rawValue: "inforHomeAction"), object: nil)
        
//        addPositionView()
        addInitTableView()
        addHeaderFooter()
        actionHttpGCD()
        
//        setStatusBarBackgroundColor()
//        self.title = "首页"
        // Do any additional setup after loading the view.
    }
    //左侧返回按钮
    override func initReturnBtn(){
        
        let messageImageView:UIImageView = UIImageView.init(frame: CGRect(x:16, y: 8, width:20 , height:20 ))
        messageImageView.contentMode = .scaleAspectFit
        if AccountInfo.sharedInstance().messageNumber != "0" {
           messageImageView.image = UIImage.init(named: "newMessage_image")
        } else {
            messageImageView.image = UIImage.init(named: "message_image")
        }
        let messageBtn:UIButton = UIButton.init(type: .custom)
        messageBtn.frame = CGRect(x:0, y: 0, width:36 , height:36)
        messageBtn.contentMode = .scaleAspectFit
        messageBtn.addTarget(self, action: #selector(gotoMessage), for: .touchUpInside)
        messageBtn.addSubview(messageImageView)
        let messageN:UIBarButtonItem = UIBarButtonItem.init(customView: messageBtn)
//        self.navigationItem.rightBarButtonItem = addN
        self.navigationItem.rightBarButtonItems = [addN, messageN]
    }
    
    @objc func gotoMessage(){
        /// 跳转消息列表
//        let url = AccountInfo.sharedInstance().getMessageListUrl()
        self.appViewsSstatistics(title: "我的消息", scope: AppClickType.OftenAppType.rawValue)
        self.getApplicationDetailsHttpActin(applicationName: "我的消息")
//        self.actionGotoWeb(webViewUrl: url, isHomePushType: .YesIsHomePushType, isShowTitleType: .NoShowTitleType, appid: "", isEncryptionType: .YesEncryptionType)
    }
    override func gotoIntelligentCustomerService(){
        self.getApplicationByBelongAction(applicationName: "IT_ROBOT")
    }
    /// 应用访问量
    func appViewsSstatistics(title:String,scope:String){
        let model = ClickRateModel()
        model.name = title
        model.belong = "门户"
        model.scope = scope
        model.type = "1"
        self.getClickRateHttpCmd(infoModel: model)
    }
    func addSearchBar(){
        self.navigationItem.titleView = searchTextField
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func addHeaderFooter(){
        self.header.setRefreshingTarget(self, refreshingAction: #selector(upPullLoadData))
        self.header.lastUpdatedTimeLabel.isHidden = true
        self.header.stateLabel.isHidden = true
        self.footer.setRefreshingTarget(self, refreshingAction: #selector(downPlullLoadData))
        self.footer.stateLabel.isHidden = false
        self.footer.isRefreshingTitleHidden = true
        self.myTableView.mj_header = self.header
        self.myTableView.mj_footer = self.footer
        self.footer.setTitle("", for: .idle)
    }
    
    //MARK:下拉刷新
    @objc func upPullLoadData(){
        actionHttpGCD()
        
    }
    //MARK:上拉加载
    @objc func downPlullLoadData(){
        self.myTableView.mj_footer.endRefreshing()
        self.footer.setTitle("已经到底啦", for: .idle)
    }
    
    @objc func actionHttpGCD(){
        showHintView()
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getHttpHomeClassListCmd()
        })
//        queue.async(group: group, execute: {[weak self] in
//            self?.group.enter()
//            self?.getUpcomingCountHttpPostCmd()
//        })
        queue.async {[weak self] in
            self?.getUpcomingCountHttpPostCmd()
        }
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getMessageNunberShowHttpPostCmd()
        })
        group.notify(queue: DispatchQueue.main) {[weak self] in
            self?.delegate.dataSource = self?.dataSource
            self?.myTableView.delegate = self?.delegate
            self?.myTableView.dataSource = self?.delegate
            self?.myTableView.reloadData()
            self?.myTableView.mj_header.endRefreshing()
            self?.initReturnBtn()
            self?.hidenHintView()
        }
    }
    
    override func gotoMessageVC(){
        self.actionGotoMessageWeb(messageId: judgmentStrNil(str: AccountInfo.sharedInstance().messageId!), isHomePushType: .YesIsHomePushType)
    }
}

