//
//  MineViewController.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/3/11.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit

class MineViewController: BaseViewController,UIPopoverPresentationControllerDelegate {
    
    var delegate:MineViewControllerDelegate!
    var dataSource:NSMutableArray!
    var cellNum:Double = 4
    var companyLabel:UILabel!
    var linView:UIView!
    var offsetY:CGFloat = 0
    
    var headArray = NSMutableArray()
    var headCellModel = MineHeadTableViewCellModel()
    var inforHttpModel = MyInformationHttpModel()
    
    var myClassArray = NSMutableArray()
    var oftenClassArray = NSMutableArray()
    //底部刷新
    var footer = MJRefreshAutoNormalFooter()
    //顶部刷新
    var header = MJRefreshNormalHeader()
    
    var companyListModelArray = NSMutableArray()
    var departmentListModelArray = NSMutableArray()
//    var selecClassModel:AdvisoryHttpListModel!
    var selecClassModel:ApplicationHttpListModel!
    
    lazy var loginView : LoginView = {
        let loginView = LoginView.init(frame: self.view.frame)
        return loginView;
    }()
    
    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 myTableView: UITableView = {
        let myTableView = UITableView.init()
        if #available(iOS 11.0, *) {
            myTableView.contentInsetAdjustmentBehavior = .never
            myTableView.scrollIndicatorInsets = myTableView.contentInset
//            myTableView.contentInset = UIEdgeInsetsMake(UIApplication.shared.statusBarFrame.size.height, 0, 20, 0)
            myTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }else{
//            myTableView.contentInset = UIEdgeInsetsMake(-44, 0, 0, 0)
            myTableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0)
        }
        registerCell(myTableView, cell: MineTitleTableViewCell.self)
        registerCell(myTableView, cell: MineDetailedTableViewCell.self)
        registerCell(myTableView, cell: MineHeadTableViewCell.self)
        registerCell(myTableView, cell: MineWebTableViewCell.self)
        myTableView.backgroundColor = loginBg_Color
        myTableView.separatorStyle = .none
        setExtraCellLineHidden(tableView: myTableView)
        return myTableView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        hideNavigationBar()
        self.appViewsSstatistics(title: "首页", scope: AppClickType.OftenAppType.rawValue)
        self.wr_setNavBarBarTintColor(statusBarColor)
        self.wr_setNavBarTitleColor(UIColor.white)
        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()
        getUnReadNumberHttpPostCmd()
//        addNotificationCenter()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //        NotificationCenter.default.removeObserver(self)
        //        addNotificationCenter()
        addRemoveObserver()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        initTitleBar()
        self.title = "我的"
//        WRNavigationBar.wr_setDefaultNavBarTitleColor
        
        initIsLogin()
        NotificationCenter.default.addObserver(self, selector: #selector(actionHttpGCD), name: NSNotification.Name(rawValue: "inforAction"), object: nil)
        
        // Do any additional setup after loading the view.
    }
    //左侧返回按钮
    override func initReturnBtn(){
        let leftN:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: ""), style: .plain, target: self, action: #selector(arrowResponse))
        self.navigationItem.leftBarButtonItem = leftN
    }
    //左侧返回按钮
    func initAddBtn(){
        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)
        
//        let messageImageView:UIImageView = UIImageView.init(frame: CGRect(x:16, y: 8, width:20 , height:20 ))
//        messageImageView.contentMode = .scaleAspectFit
//        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)
        
        let searchImageView:UIImageView = UIImageView.init(frame: CGRect(x:16, y: 8, width:20 , height:20 ))
        searchImageView.contentMode = .scaleAspectFit
        searchImageView.image = UIImage.init(named: "search_image")
        let searchBtn:UIButton = UIButton.init(type: .custom)
        searchBtn.frame = CGRect(x:0, y: 0, width:36 , height:36)
        searchBtn.contentMode = .scaleAspectFit
        searchBtn.addTarget(self, action: #selector(gotoVoiceDialogueVC), for: .touchUpInside)
        searchBtn.addSubview(searchImageView)
        let searchN:UIBarButtonItem = UIBarButtonItem.init(customView: searchBtn)
        //        self.navigationItem.rightBarButtonItem = messageN
//        self.navigationItem.rightBarButtonItems = [addN, messageN, searchN]
        self.navigationItem.rightBarButtonItems = [addN, searchN]
    }
    @objc func gotoMessage(){
        
    }
    func addSearchBar(){
        self.navigationItem.titleView = searchTextField
    }
    override func arrowResponse(){
        shouwPopover()
    }
    /// 我的信息
    func gotoMineInfoVC(){
        let vc:MineInfoViewController=MineInfoViewController()
        vc.signOutBlock = {[weak self] in
            self?.loginAction()
        }
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK:判断是否登录
    func initIsLogin(){
//        if AccountInfo.sharedInstance().UserId == nil {
//            loginAction()
//        }else{
            notLoginAction()
//        }
        
    }
    //页面清除
    func removeView(){
        loginView.isHidden = true
        //companyLabel.isHidden = true
        //linView.isHidden = true
        self.myTableView.isHidden = false
        //self.navigationItem.leftBarButtonItem = nil
        //self.navigationItem.rightBarButtonItem = nil
    }
    //MARK:登陆
    func loginAction(){
        searchTextField.isHidden = true
        self.myTableView.isHidden = true
        initReturnBtn()
        addInitLoginView()
        setStatusBarBackgroundColor()
    }
    func notLoginAction(){
        searchTextField.isHidden = false
        loginView.isHidden = true
        self.myTableView.isHidden = false
        initAddBtn()
//        addSearchBar()
        addPositionView()
        addInitTableView()
        addHeaderFooter()
        actionHttpGCD()
//        setStatusBarBackgroundColor()
    }
    
    //MARK:添加上拉加载 下拉刷新
    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 = true
        self.footer.isRefreshingTitleHidden = true
        self.myTableView.mj_header = self.header
        //self.myTableView.mj_footer = self.footer
    }
    
    //MARK:下拉刷新
    @objc func upPullLoadData(){
        
        actionHttpGCD()
        //self.myTableView.reloadData()
    }
    //MARK:上拉加载
    @objc func downPlullLoadData(){
        
    }
    @objc func actionHttpGCD(){
        if AccountInfo.sharedInstance().oldType == "0" {
//            oldHttpAction()
        } else {
            newHttpAction()
        }
    }
    /// 新接口
    func newHttpAction(){
        showHintView()
        
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getMessageNunberShowHttpPostCmd()
        })
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getMyInformationHttpGetCmd()
        })
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getMyApplicationListHttpCmd()
        })
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getUpcomingCountHttpPostCmd()
        })
        group.notify(queue: DispatchQueue.main) {[weak self] in
            self?.dataSource = NSMutableArray()
            self?.dataSource.add(self?.headArray ?? NSMutableArray())
            self?.dataSource.add(self?.oftenClassArray ?? NSMutableArray())
            self?.myTableView.mj_header.endRefreshing()
            self?.delegate.dataSource = self?.dataSource
            self?.myTableView.delegate = self?.delegate
            self?.myTableView.dataSource = self?.delegate
            self?.myTableView.reloadData()
            self?.hidenHintView()
        }
    }
  
    override func gotoMessageVC(){
        self.actionGotoMessageWeb(messageId: AccountInfo.sharedInstance().messageId!, isHomePushType: .YesIsHomePushType)
    }
    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)
    }
}
