//
//  HomeViewController+http.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/3/13.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit

extension HomeViewController {
    //MARK：获取对应服务
    func getApplicationByBelongAction(applicationName:String)  {
        showHintView()
        let cmd:HttpCommand = ApplicationByBelongHttpGetCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpApplicationByBelongHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpApplicationByBelongHttpGetCmd_applicationName] = applicationName
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = dic as? [AnyHashable : Any]
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    @objc func httpApplicationByBelongHttpResultResponse(result:RequestResult){
        let r:ApplicationByBelongHttpResult = result as! ApplicationByBelongHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getApplicationByBelongHttpResult()
            if array.count != 0{
                let httpDetailModel:ApplicationHttpListModel = array[0] as! ApplicationHttpListModel
                self.refreshTokenHttpAction(selecHttpModel: httpDetailModel)
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        self.hidenHintView()
    }
    //MARK：获取消息详情
    func getApplicationDetailsHttpActin(applicationName:String)  {
        showHintView()
        let cmd:HttpCommand = ApplicationDetailsHttpGetCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpApplicationDetailsHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpApplicationDetailsHttpGetCmd_applicationName] = applicationName
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = dic as? [AnyHashable : Any]
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    @objc func httpApplicationDetailsHttpResultResponse(result:RequestResult){
        let r:ApplicationDetailsHttpResult = result as! ApplicationDetailsHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getApplicationDetailsHttpResult()
            if array.count != 0{
                let httpDetailModel:ApplicationHttpListModel = array[0] as! ApplicationHttpListModel
                self.refreshTokenHttpAction(selecHttpModel: httpDetailModel)
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        self.hidenHintView()
    }
    
    // MARK: IDM验证Token
//    func isAccess_tokenTrue(){
//        if AccountInfo.sharedInstance().singlePoint_access_token == nil || AccountInfo.sharedInstance().singlePoint_access_token == "" || AccountInfo.sharedInstance().loginType != "1" {
//            return
//        }
//        if isSingOutAction() {return}
//        let cmd:HttpCommand = VerificationTokenHttpPostCmd.init(version: PHttpVersion_v1)
//        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
//            if result != nil {
//                self?.httpVerificationTokenHttpResultResponse(result: result)
//            }else{
//                print("空的")
//            }
//        }
//        let dic:NSMutableDictionary = NSMutableDictionary()
//        dic[kHttpVerificationTokenHttpPostCmd_tokenId] = AccountInfo.sharedInstance().singlePoint_access_token
//        dic[kHttpVerificationTokenHttpPostCmd_remoteIp] = AccountInfo.sharedInstance().singlePoint_remoteIp
//        dic[kHttpVerificationTokenHttpPostCmd_appId] = AccountInfo.sharedInstance().singlePoint_appId
//        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
//        cmd.requestInfo = dic as? [AnyHashable : Any]
//        cmd.completeDelegate=completeDelegate
//        print("url==%@",cmd.getUrl())
//        cmd.execute()
//    }
//    func httpVerificationTokenHttpResultResponse(result:RequestResult){
//        let r:VerificationTokenHttpResult = result as! VerificationTokenHttpResult
//        if r.isOk() {
//            let array:NSMutableArray = r.getVerificationTokenHttpResult()
//            if array.count == 0{
//                print("验证成功！")
//            } else {
//                print("验证失败！")
//                AccountInfo.sharedInstance().clearAccount()
//                self.deAllSelecCompanyDepartment()
//                showOneAlert(title: "温馨提示", message: "您当前登录已失效，需要重新登录！", titleSecondBtn: "确定", blockOtherBtn: {
//                    NotificationCenter.default.post(name: Notification.Name(rawValue: "setLoginWindow"), object: "0")
//                })
//            }
//            self.hidenHintView()
//        }else{
//            SMToastView.showMessage("请查看当前网络状态！")
//        }
//    }
    
    // MARK:消息数量
    func getMessageNunberShowHttpPostCmd(){
        let cmd:HttpCommand = MessageNunberShowHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpMessageNumberShowHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        var filtersArr = NSMutableArray()
//        print(judgmentStrNil(str: AccountInfo.sharedInstance().UserId))
        let dic1:[String:Any] = ["value":judgmentStrNil(str: AccountInfo.sharedInstance().UserId!),"key":"targetid"]
        let dic2:[String:Any] = ["value":"1","key":"state"]
        let dic3:[String:Any] = ["value":"0","key":"status"]
        filtersArr = [dic1,dic2,dic3]
        dic[kHttpMessageNunberShowHttpPostCmd_pageNum] = "1"
        dic[kHttpMessageNunberShowHttpPostCmd_pageSize] = "10"
        dic[kHttpMessageNunberShowHttpPostCmd_orderby] = "create_time"
        dic[kHttpMessageNunberShowHttpPostCmd_sort] = "desc"
        dic[kHttpMessageNunberShowHttpPostCmd_filters] = filtersArr
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = dic as? [AnyHashable : Any]
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
        
    }
    @objc func httpMessageNumberShowHttpResultResponse(result:RequestResult){
        let r:MessageNumberShowHttpResult = result as! MessageNumberShowHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getMessageNumberShowHttpResult()
            if array.count != 0{
                let model:MessageNumberShowModel = array[0] as! MessageNumberShowModel
                AccountInfo.sharedInstance().messageNumber = model.total
            }
        }else{
//            SMToastView.showMessage("请查看当前网络状态！")
        }
        group.leave()
    }
    // MARK:待办已办总数
    func getUpcomingCountHttpPostCmd(){
        /// 获取d统一待办 总数目
        UpcomingNewCountHttpAction.sharedInstance().getAllApplicationHttpListCmd {[weak self] in
            self?.tabBarController?.tabBar.showBadge(onItemIndex: 1, angNum: numBigData(numStr: judgmentStrNil(str: AccountInfo.sharedInstance().upcomingCount))
             )
        }
//        group.leave()
        return
        let cmd:HttpCommand = UpcomingCountHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpUpcomingCountHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpUpcomingCountHttpPostCmd_targetid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        dic[kHttpUpcomingCountHttpPostCmd_empuid] = judgmentStrNil(str:AccountInfo.sharedInstance().sysUserId)
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = dic as? [AnyHashable : Any]
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
        
    }
    @objc func httpUpcomingCountHttpResultResponse(result:RequestResult){
        let r:UpcomingCountHttpResult = result as! UpcomingCountHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getUpcomingCountHttpResult()
            if array.count != 0{
                let model:UpcomingCountModel = array[0] as! UpcomingCountModel
                AccountInfo.sharedInstance().upcomingCount = model.ytotal
                AccountInfo.sharedInstance().doneCount = model.dtotal
                self.tabBarController?.tabBar.showBadge(onItemIndex: 1, angNum: judgmentStrNil(str: AccountInfo.sharedInstance().upcomingCount))
            }
        }else{
//            SMToastView.showMessage("请查看当前网络状态！")
        }
        group.leave()
    }
    // MARK:首页数据
    func getHttpHomeClassListCmd(){
        let cmd:HttpCommand = HttpHomeClassListCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpHttpHomeClassListResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        let attrDic:NSMutableDictionary = NSMutableDictionary()
        attrDic[kHttpHttpHomeClassListCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        attrDic[kHttpHttpHomeClassListCmd_type] = "11"
        dic[kHttpHttpHomeClassListCmd_attr] = attrDic
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
//        cmd.requestInfo = parmeters as? [AnyHashable : Any]
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
        
    }
    func httpHttpHomeClassListResultResponse(result:RequestResult){
        let r:HttpHomeClassListResult = result as! HttpHomeClassListResult
        if r.isOk() {
            let array:NSMutableArray = r.getTheAllData()
            httpInfoModel = array.lastObject as! HomeHttpInfoModel
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
//            let array:NSMutableArray = r.getCacheData()
//            httpInfoModel = array.lastObject as! HomeHttpInfoModel
        }
        self.dataSource = NSMutableArray()
        self.setResolveHttpModel(httpModel: httpInfoModel)
//        self.delegate.dataSource = self.dataSource
        group.leave()

    }
    
    func setResolveHttpModel(httpModel:HomeHttpInfoModel){
        self.addCarouselTableViewCell(bannerModelArray: httpModel.banner, menuModel: httpModel)
//        self.addHttpCellData(menuModel: httpModel)
        self.setScopeList(scopeHttpArray: httpModel.commonly)
        self.addHeadlinesTitleMore(topmore: httpModel.topmore, toptitle: httpModel.toptitle)
        self.addHeadlinesMore(topnews: httpModel.topnews)
    }
    
    //添加轮播图
    func addCarouselTableViewCell(bannerModelArray:NSMutableArray,menuModel:HomeHttpInfoModel){
        bannerArray = NSMutableArray()
        carouseCellModel = HomeCarouselTableViewCellModel()
        carouseCellModel.className = "HomeCarouselTableViewCell"
        for index in 0..<bannerModelArray.count {
            let bannerModel:HomeHttpInfoModelBannerModel = bannerModelArray[index] as! HomeHttpInfoModelBannerModel
            carouseCellModel.imageUrlArray .add(bannerModel.image ?? String())
            carouseCellModel.pageUrlArray.add(bannerModel.comments ?? String())
            carouseCellModel.titleUrlArray.add(bannerModel.title ?? String())
        }
        //print(carouseCellModel.imageUrlArray.count)
        carouseCellModel.block = {(sender: Any) in
//            self?.actionGotoWeb(webViewUrl: sender as! String, isHomePushType: .YesIsHomePushType)
        }
        bannerArray.add(carouseCellModel)
        self.addHttpCellData(menuModel: menuModel)
        self.dataSource .add(bannerArray)
        
    }
    
    func addHttpCellData(menuModel:HomeHttpInfoModel)  {
        classArray = NSMutableArray()
        detailedModel.className = "MineDetailedTableViewCell"
        detailedModel.cellNum = self.cellNum
        detailedModel.detaileArray = NSMutableArray()
        for index in 0..<menuModel.menu.count {
            let httpDetailModel:ApplicationHttpListModel = menuModel.menu[index] as! ApplicationHttpListModel
            let detailModel = MineCollectionViewCellModel()
            detailModel.className = "HomeCollectionViewCell"
            detailModel.titleValue = httpDetailModel.name
            detailModel.imageName = httpDetailModel.imageUrl
            detailModel.comments = httpDetailModel.comments
            detailModel.block = { [weak self](value:Any) in
                //self?.gotoWeb(model: httpDetailModel)
//                self?.actionGotoWeb(webViewUrl: value as! String, isHomePushType: .YesIsHomePushType, isShowTitleType: .YesShowTitleType)
                self?.classAction(selecHttpModel: httpDetailModel)
            }
            detailedModel.detaileArray .add(detailModel)
        }
//        self.addCellModel(array: detailedModel.detaileArray)
        carouseCellModel.detailedModel = detailedModel
        carouseCellModel.collectionViewH = self.getH(arr: detailedModel.detaileArray)
//        print(carouseCellModel.collectionViewH)
    }
    /// 计算高度
    func getH(arr:NSMutableArray) -> CGFloat{
        if arr.count == 0 {
            return 20
        }
        if arr.count >= Int(self.cellNum){
            let index = lroundf(Float(ceil(Double(arr.count)/self.cellNum)))
            return (SCREEN_WHIDTH()/4)*CGFloat(index)*0.8 + 20
        }
        return (SCREEN_WHIDTH()/4)*0.8 + 20
    }
    //上药应用更多
    func addCellModel(array:NSMutableArray){
        detailModel.className = "MineCollectionViewCell"
        detailModel.titleValue = "更多"
        detailModel.imageName = "more_image"
        detailModel.comments = "123"
        detailModel.block = { [weak self](value:Any) in
            self?.gotoHomeMore()
        }
        array .add(detailModel)
    }
    //跳转更多
    func gotoHomeMore(){
        let vc:HomeMoreViewController = HomeMoreViewController()
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    
    //添加上药头条
    func addHeadlinesTitleMore(topmore:NSMutableArray,toptitle:NSMutableArray){
        headlinesTitleArray = NSMutableArray()
        headlinesMoreCellModel.className = "HeadlinesMoreTableViewCell"
        for index in 0..<topmore.count {
            let moreModel:HomeHttpInfoModelTitleContentModel = topmore[index] as! HomeHttpInfoModelTitleContentModel
            headlinesMoreCellModel.moreImageUrl = moreModel.image
            headlinesMoreCellModel.pageUrl = moreModel.comments
        }
        for index in 0..<toptitle.count {
            let moreModel:HomeHttpInfoModelTitleContentModel = toptitle[index] as! HomeHttpInfoModelTitleContentModel
            headlinesMoreCellModel.titleImageUrl = moreModel.image
        }
        headlinesMoreCellModel.block = {[weak self] in
            self?.actionGotoWeb(webViewUrl: (self?.headlinesMoreCellModel.pageUrl!)!, isHomePushType: .YesIsHomePushType, isShowTitleType: .YesShowTitleType, appid: "", isEncryptionType: .NoEncryptionType)
        }
        headlinesTitleArray .add(headlinesMoreCellModel)
        if topmore.count != 0 && toptitle.count != 0 {
            self.dataSource .add(headlinesTitleArray)
        }
    }
    //添加上药头条
    func addHeadlinesMore(topnews:NSMutableArray){
        headlinesArray = NSMutableArray()
        for index in 0..<topnews.count {
            let titleContent:HomeHttpInfoModelTitleContentModel = topnews[index] as! HomeHttpInfoModelTitleContentModel
            self.addHttpAdvisoryTableViewCellModel(array: headlinesArray, httpModel: titleContent)
        }
        self.dataSource .add(headlinesArray)
    }
    
//    func addHeadlinesMoreDetailedTableViewCellModel(array:NSMutableArray,httpModel:HomeHttpInfoModelTitleContentModel){
//        let model = HeadlinesMoreDetailedTableViewCellModel()
//        model.className = "HeadlinesMoreDetailedTableViewCell"
//        model.timeStr = httpModel.publishtime
//        model.titleStr = judgmentStrNil(str: httpModel.title)
//        model.imageUrl = httpModel.image
//        model.block = {[weak self] in
//            self?.openWeb(httpModel: httpModel)
//        }
//        array .add(model)
//    }
    func addHttpAdvisoryTableViewCellModel(array:NSMutableArray,httpModel:HomeHttpInfoModelTitleContentModel){
        let model = AdvisoryTableViewCellModel()
        model.className = "AdvisoryTableViewCell"
        //        model.timeStr = httpModel.createon
        model.timeStr = httpModel.publishtime
        model.titleStr = httpModel.title
        model.imageUrl = httpModel.image
        model.block = {[weak self] in
            self?.openWeb(httpModel: httpModel)
        }
        array .add(model)
    }
    func openWeb(httpModel:HomeHttpInfoModelTitleContentModel){
        let url:String = AccountInfo.sharedInstance().getAdvisoryVCUrl()+httpModel.id!
        //value1 备选页面
        if httpModel.value1?.count != 0 {
            self.actionGotoTitleWeb(webViewUrl: httpModel.value1!, title: "上药头条", isHomePushType: .YesIsHomePushType, appid: "", isEncryptionType: .NoEncryptionType)
        }else{
            self.actionGotoTitleWeb(webViewUrl: url, title: "上药头条", isHomePushType: .YesIsHomePushType, appid: "", isEncryptionType: .NoEncryptionType)
        }
        self.appViewsSstatistics(title: httpModel.title, scope: AppClickType.OftenAppType.rawValue)
    }
    
    
}
