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

import UIKit

extension MineMoreViewController {
    // MARK:获取我的常接口
    func getMyApplicationsHttpCmdTwo(){
        let cmd:HttpCommand = MyApplicationsHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpMyApplicationsHttpResultResponseTwo(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        
        dic[kHttpMyApplicationsHttpCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        if self.applicationType == .MyApplicationType {
            dic[kHttpMyApplicationsHttpCmd_type] = "10"
        }else{
            dic[kHttpMyApplicationsHttpCmd_type] = "11"
        }
        
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
        
    }
    func httpMyApplicationsHttpResultResponseTwo(result:RequestResult){
        let r:MyApplicationsHttpResult = result as! MyApplicationsHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getMyApplicationsHttpResult()
            let httpModel:MyApplicationsHttpModel = array[0] as! MyApplicationsHttpModel
            self.mineCellModelArray = httpModel.listArray
            setmineCellModelArray()
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        group.leave()
    }
    func setmineCellModelArray(){
        tableViewCellModel.className = "MineMoreTableViewCell"
        tableViewCellModel.collcetionViewSectionModellArray = (self.getHttpCollcetionViewModellArray(arrays: self.mineCellModelArray, operationType: .DeleteType))
        tableViewCellModel.block = {[weak self] (value:Any,value1:Any)in
            self?.tableViewCellModel.collcetionViewSectionModellArray = value as! NSMutableArray
            AccountInfo.sharedInstance().myApplicationCellNum = String(format: "%lf", self?.tableViewCellModel.collcetionViewSectionModellArray.count ?? Int())
            
            self?.getType(model: value1 as! MineMoreCollectionViewCellModel)
            self?.myTableView.reloadData()
        }
    }
    
    
    func getMoreApplicationsTwoHttpCmd(){
        let cmd:HttpCommand = MoreApplicationsTwoHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpMoreApplicationsTwoHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        let attrDic:NSMutableDictionary = NSMutableDictionary()
        attrDic[kHttpMoreApplicationsTwoHttpCmd_userid] = AccountInfo.sharedInstance().UserId
        attrDic[kHttpMoreApplicationsTwoHttpCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        dic[kHttpMoreApplicationsTwoHttpCmd_attr] = attrDic
        //dic[kHttpMoreApplicationsTwoHttpCmd_orderby] = "createon"
        dic[kHttpMoreApplicationsTwoHttpCmd_pageNum] = ""
        
        dic[kHttpMoreApplicationsTwoHttpCmd_pageSize] = "200"
        dic[kHttpMoreApplicationsTwoHttpCmd_sort] = "desc"
        let filtersDic:NSMutableDictionary = NSMutableDictionary()
        if self.applicationType == .MyApplicationType {
            filtersDic[kHttpMoreApplicationsTwoHttpCmd_value] = "10"
        }else{
            filtersDic[kHttpMoreApplicationsTwoHttpCmd_value] = "11"
        }
        let filtersArray = NSMutableArray()
        filtersArray.add(filtersDic)
        dic[kHttpMoreApplicationsTwoHttpCmd_filters] = filtersArray
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpMoreApplicationsTwoHttpResultResponse(result:RequestResult){
        let r:MoreApplicationsTwoHttpResult = result as! MoreApplicationsTwoHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getMoreApplicationsTwoHttpResult()
            self.settableViewCellModel(modelArray: array)
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        group.leave()
        
    }
    func settableViewCellModel(modelArray:NSMutableArray){
        tableViewCellModel.className = "MineMoreTableViewCell"
        tableViewCellModel.collcetionViewSectionModellArray = (self.getHttpCollcetionViewModellArray(arrays: self.mineCellModelArray, operationType: .DeleteType))
        tableViewCellModel.block = {[weak self] (value:Any,value1:Any)in
            self?.tableViewCellModel.collcetionViewSectionModellArray = value as! NSMutableArray
            AccountInfo.sharedInstance().myApplicationCellNum = String(format: "%lf", self?.tableViewCellModel.collcetionViewSectionModellArray.count ?? Int())
            
            self?.getType(model: value1 as! MineMoreCollectionViewCellModel)
            self?.myTableView.reloadData()
        }
        
        tableViewCellModelTwo.className = "MineMoreTableViewCell"
        tableViewCellModelTwo.collcetionViewSectionModellArray = (self.getHttpCollcetionViewModellTwoArray(arrays: modelArray, operationType: .AddType))
        
        tableViewCellModelTwo.changeBlock = {[weak self] (value:Any)in
            self?.changeBlockAction(model: value as! MineMoreCollectionViewCellModel)
        }
        self.dataSource .add(tableViewCellModel)
        getTableViewCellAllModel()
        self.dataSource .add(tableViewCellModelTwo)
    }
    func getType(model:MineMoreCollectionViewCellModel){
        let array:NSMutableArray = tableViewCellModelTwo.collcetionViewSectionModellArray
        for index in 0..<array.count {
            let classModel:MineMoreTwoTableViewCellModel = array[index] as! MineMoreTwoTableViewCellModel
            for indexs in 0..<classModel.collcetionViewSectionModellArray.count{
                let models:MineMoreCollectionViewCellModel = classModel.collcetionViewSectionModellArray[indexs] as! MineMoreCollectionViewCellModel
                if model.titleValue == models.titleValue{
                    models.operationType = .AddType
                }
            }
            
        }
    }
    func changeBlockAction(model:MineMoreCollectionViewCellModel) {
        let classModel:MineMoreTwoTableViewCellModel = self.tableViewCellModel.collcetionViewSectionModellArray[0] as! MineMoreTwoTableViewCellModel
        
        for index in 0..<classModel.collcetionViewSectionModellArray.count {
            let models:MineMoreCollectionViewCellModel = classModel.collcetionViewSectionModellArray[index] as! MineMoreCollectionViewCellModel
            if models.titleValue == model.titleValue && model.operationType == .DeleteType {
                //model.operationType = .AddType
                //print("1")
                return
            }else if models.titleValue == model.titleValue && model.operationType == .AddType{
                classModel.collcetionViewSectionModellArray.remove(models)
                AccountInfo.sharedInstance().myApplicationCellNum = String(format: "%lf", classModel.collcetionViewSectionModellArray.count )
                self.myTableView.reloadData()
                //print("2")
                return
            }
        }
        if model.operationType == .DeleteType {
            classModel.collcetionViewSectionModellArray.add(model)
        }else{
            classModel.collcetionViewSectionModellArray.remove(model)
        }
        AccountInfo.sharedInstance().myApplicationCellNum = String(format: "%lf", classModel.collcetionViewSectionModellArray.count)
        self.myTableView.reloadData()
    }
    func getHttpCollcetionViewModellArray(arrays:NSMutableArray,operationType:OperationType)->NSMutableArray {
        let array = NSMutableArray()
        let classModel = MineMoreTwoTableViewCellModel()
        
        for index in 0..<arrays.count {
            let httpModel:AdvisoryHttpListModel = arrays[index] as! AdvisoryHttpListModel

            classModel.collcetionViewSectionModellArray.add(self.getHttpMineMoreCollectionViewCellModel(model:httpModel , operationType: operationType, isAllType: .OftenType))
        }
        if self.applicationType == .MyApplicationType {
            classModel.vcTitle = "我的应用"
        }else{
            ///获取我的自定义的个数 最多11个
//            AccountInfo.sharedInstance().myApplicationCellNum = String(arrays.count)
            AccountInfo.sharedInstance().myApplicationCellNum = String(format: "%lf", arrays.count )
            classModel.vcTitle = "我的常用"
        }
        array.add(classModel)
        return array
    }
    ///处理所有常用或应用 对所有Class 根据tags进行分类
    func getHttpCollcetionViewModellTwoArray(arrays:NSMutableArray,operationType:OperationType)->NSMutableArray {
        let heatArray = NSMutableArray()
        let tagsArray = NSMutableArray()
        ///根据tags进行分类
        for index in 0..<arrays.count {
            let httpModel:AdvisoryHttpListModel = arrays[index] as! AdvisoryHttpListModel
            if !tagsArray.contains(httpModel.tags as Any){
                let classModel = MineMoreTwoTableViewCellModel()
                classModel.vcTitle = httpModel.tags
                tagsArray.add(httpModel.tags as Any)
                heatArray.add(classModel)
            }
        }
        ///根据上层的分类，将所有的Class 添加的分类中
        for index in 0..<heatArray.count {
            let classModel:MineMoreTwoTableViewCellModel = heatArray[index] as! MineMoreTwoTableViewCellModel
            for i in 0..<arrays.count{
                let httpModel:AdvisoryHttpListModel = arrays[i] as! AdvisoryHttpListModel
                if classModel.vcTitle == httpModel.tags{
                    classModel.collcetionViewSectionModellArray.add(self.getHttpMineMoreCollectionViewCellModel(model:httpModel , operationType: operationType, isAllType: .AllType))
                }
            }
        }
        return heatArray
    }
    func getHttpMineMoreCollectionViewCellModel(model:AdvisoryHttpListModel,operationType:OperationType,isAllType:IsAllType)->MineMoreCollectionViewCellModel{
        let collectionViewCellModel = MineMoreCollectionViewCellModel()
        collectionViewCellModel.className = "MineMoreCollectionViewCell"
        collectionViewCellModel.titleValue = model.title
        collectionViewCellModel.applicationType = self.applicationType
        collectionViewCellModel.isInstallation = self.isInstallation(urlString: model.openurl!)
        collectionViewCellModel.openUrl = model.openurl
        if isAllType == .OftenType {
            ///将所有的自定义title进行存储
            self.mineTitleCellModelArray.add(model.title!)
        }
        collectionViewCellModel.biaojiNum = model.value2
        collectionViewCellModel.imageName = model.imageUrl
        ///class的点击事件
        collectionViewCellModel.block = {[weak self](value:Any) in
            self?.classAction(selecHttpModel: model)
        }
        collectionViewCellModel.id =  model.id
        collectionViewCellModel.title =  model.title
        collectionViewCellModel.status =  model.status
        collectionViewCellModel.createon =  model.createon
        collectionViewCellModel.operationType = operationType
        if isAllType == .AllType && self.mineTitleCellModelArray.contains(model.title!) {
            /// 将所有Class中，已经在我的自定义 里面存在的Class，将其状态更改为可删除状态
            collectionViewCellModel.operationType = .DeleteType
        }
        collectionViewCellModel.createby =  model.createby
        collectionViewCellModel.updateon =  model.updateon
        collectionViewCellModel.pid =  model.pid
        collectionViewCellModel.author =  model.author
        collectionViewCellModel.createbyname =  model.createbyname
        collectionViewCellModel.updatebyname =  model.updatebyname
        collectionViewCellModel.image =  model.image
        collectionViewCellModel.homeshow =  model.homeshow
        collectionViewCellModel.comments =  model.comments
        collectionViewCellModel.docname =  model.docname
        collectionViewCellModel.type =  model.type
        collectionViewCellModel.foldertype =  model.foldertype
        collectionViewCellModel.kgimage =  model.kgimage
        collectionViewCellModel.listimage =  model.listimage
        
        collectionViewCellModel.appid =  model.appid
        return collectionViewCellModel
    }
    //点击应用响应事件
    func classAction(selecHttpModel:AdvisoryHttpListModel){
        self.selecClassModel = selecHttpModel
        if self.applicationType == .MyApplicationType {
            myApplicationAction(httpDetailModel: selecHttpModel)
        } else {
            oftenApplicationType(httpDetailModel: selecHttpModel)
        }
    }
    //我的应用响应事件
    private func myApplicationAction(httpDetailModel:AdvisoryHttpListModel){
        if httpDetailModel.comments != nil && httpDetailModel.comments?.count != 0{
            let url:String = httpDetailModel.comments!+"?docId="+judgmentStrNil(str: httpDetailModel.id)+"&userId="+AccountInfo.sharedInstance().UserId!+"&userName="+judgmentStrNil(str: AccountInfo.sharedInstance().userName)
            self.actionGotoTitleWeb(webViewUrl: url, title: httpDetailModel.title!, isHomePushType: .YesIsHomePushType)
            return
        }
        if self.isInstallation(urlString: httpDetailModel.openurl!) == false{
            //打开APP
            self.downloadOpenApp(urlString: httpDetailModel.openurl!, openUrlType: .OpenAppType)
        }else{
            if httpDetailModel.appid?.count == 0{
                SMToastView.showMessage("该应用暂无下载地址，请联系管理员！")
                return
            }
            self.downloadOpenApp(urlString: httpDetailModel.appid!, openUrlType: .DownloadType)
        }
    }
    //我的常用响应事件
    func oftenApplicationType(httpDetailModel:AdvisoryHttpListModel){
        let companyInfo:SelecCompanyDepartmentInfo = getSelecCompanyDepartment(tags: httpDetailModel.tags ?? String())
        if companyInfo.tags == nil {
            getSelectCompanyHttpCmd()
        }else{
            if httpDetailModel.tags == "ERP" && companyInfo.sysOrg == ""{
                SMToastView.showMessage("ERP组织获取失败！")
                return
            }
            self.setCacheAccountInfo(companyInfo: companyInfo, selecClassModel: self.selecClassModel)
            return
        }
    }
    
    //编辑保存
    func getSaveApplicationsHttpCmd(){
        showHintView()
        let cmd:HttpCommand = SaveApplicationsHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpHttpSaveApplicationsHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpSaveApplicationsHttpCmd_userid] = AccountInfo.sharedInstance().UserId
        if self.applicationType == .MyApplicationType {
            dic[kHttpSaveApplicationsHttpCmd_type] = "10"
        }else{
            dic[kHttpSaveApplicationsHttpCmd_type] = "11"
        }
        
        let array = NSMutableArray()
        dic[kHttpSaveApplicationsHttpCmd_list] = getSeaveModelListArray(httpArray: array)
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
        
    }
    func httpHttpSaveApplicationsHttpResultResponse(result:RequestResult){
        let r:SaveApplicationsHttpResult = result as! SaveApplicationsHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getSaveApplicationsHttpResult()
            if array.count != 0{
                SMToastView.showMessage("保存成功！")
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        hidenHintView()
    }
    func getSeaveModelListArray(httpArray:NSMutableArray)->NSMutableArray{
        let classModel:MineMoreTwoTableViewCellModel = self.tableViewCellModel.collcetionViewSectionModellArray[0] as! MineMoreTwoTableViewCellModel
        for index in 0..<classModel.collcetionViewSectionModellArray.count{
            let dic = NSMutableDictionary()
            let model:MineMoreCollectionViewCellModel = classModel.collcetionViewSectionModellArray[index] as! MineMoreCollectionViewCellModel
            dic[kHttpSaveApplicationsHttpCmd_id] =  model.id
            dic[kHttpSaveApplicationsHttpCmd_title] =  model.title
            dic[kHttpSaveApplicationsHttpCmd_status] =  model.status
            dic[kHttpSaveApplicationsHttpCmd_createon] =  model.createon
            dic[kHttpSaveApplicationsHttpCmd_createby] =  model.createby
            dic[kHttpSaveApplicationsHttpCmd_pid] =  model.pid
            dic[kHttpSaveApplicationsHttpCmd_author] =  model.author
            dic[kHttpSaveApplicationsHttpCmd_createbyname] =  model.createbyname
            dic[kHttpSaveApplicationsHttpCmd_updatebyname] =  model.updatebyname
            dic[kHttpSaveApplicationsHttpCmd_image] =  model.image
            dic[kHttpSaveApplicationsHttpCmd_homeshow] =  model.homeshow
            dic[kHttpSaveApplicationsHttpCmd_comments] =  model.comments
            dic[kHttpSaveApplicationsHttpCmd_docname] =  model.docname
            dic[kHttpSaveApplicationsHttpCmd_type] =  model.type
            dic[kHttpSaveApplicationsHttpCmd_foldertype] =  model.foldertype
            dic[kHttpSaveApplicationsHttpCmd_kgimage] =  model.kgimage
            dic[kHttpSaveApplicationsHttpCmd_listimage] =  model.listimage
            httpArray .add(dic)
        }
        return httpArray
    }
    // MARK:获取公司列表
    func getSelectCompanyHttpCmd(){
        showHintView()
        let cmd:HttpCommand = SelectCompanyHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpSelectCompanyHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        let attrDic:NSMutableDictionary = NSMutableDictionary()
        attrDic[kHttpSelectCompanyHttpCmd_companyname] = ""
        attrDic[kHttpSelectCompanyHttpCmd_sysname] = self.selecClassModel.tags
        attrDic[kHttpSelectCompanyHttpCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        dic[kHttpSelectCompanyHttpCmd_attr] = attrDic
        dic[kHttpSelectCompanyHttpCmd_dbName] = ""
        dic[kHttpSelectCompanyHttpCmd_length] = "100"
        dic[kHttpSelectCompanyHttpCmd_start] = "1"
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpSelectCompanyHttpResultResponse(result:RequestResult){
        let r:SelectCompanyHttpResult = result as! SelectCompanyHttpResult
        if r.isOk() {
            let array = r.getSelectCompanyHttpResult()
            let selectCompanyModel:SelectCompanyHttpModel = array[0] as! SelectCompanyHttpModel
            companyListModelArray = selectCompanyModel.sysCompany.data
            departmentListModelArray = selectCompanyModel.orgList.data
            if companyListModelArray.count == 0{
                //SMToastView.showMessage("暂无公司！")
                if (self.selecClassModel.tags == "ERP" || self.selecClassModel.tags == "erp") {
                    SMToastView.showMessage("ERP部门组织获取失败！")
                    return
                }
                self.setWebUrlAction(selecClassModel: self.selecClassModel)
            }else if companyListModelArray.count == 1 && departmentListModelArray.count == 0  {
                if (self.selecClassModel.tags == "ERP" || self.selecClassModel.tags == "erp") {
                    SMToastView.showMessage("ERP部门组织获取失败！")
                    return
                }
                //SMToastView.showMessage("暂无部门！")
                self.selectOneCompany(companyListArray: companyListModelArray)
                //setUrl()
            }else if companyListModelArray.count == 1 && departmentListModelArray.count == 1  {
                self.selectCompanyDeparttment(companyListArray: companyListModelArray, departmentListArray: departmentListModelArray)
            }else if companyListModelArray.count != 1 || departmentListModelArray.count != 1  {
                gotoCompanyListVC()
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        hidenHintView()
    }
    //解析出只有一个公司和只有一个部门时
    func selectCompanyDeparttment(companyListArray:NSMutableArray,departmentListArray:NSMutableArray){
        let companyModel:SelectCompanyHttpCompanyDataModel = companyListModelArray[0] as! SelectCompanyHttpCompanyDataModel
        let departmentModel:SelectCompanyHttpOrgListDataModel = departmentListArray[0] as! SelectCompanyHttpOrgListDataModel
        self.setClassWebUrlAccountInfo(selecClassModel: self.selecClassModel, companyModel: companyModel, departmentModel: departmentModel)
    }
    //解析出只有一个公司时
    func selectOneCompany(companyListArray:NSMutableArray){
        let companyModel:SelectCompanyHttpCompanyDataModel = companyListModelArray[0] as! SelectCompanyHttpCompanyDataModel
        self.setClassWebUrlAccountInfo(selecClassModel: self.selecClassModel, companyModel: companyModel, departmentModel: SelectCompanyHttpOrgListDataModel())
        
    }
    func gotoCompanyListVC()  {
        let vc:SelectCompanyViewController=SelectCompanyViewController.createViewController(createArgs: nil) as! SelectCompanyViewController
        vc.selecClassModel = self.selecClassModel
        vc.block = {[weak self] (value:Any) in
            self?.mineGotoWebVC()
        }
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    //拼接URl
    @objc func mineGotoWebVC(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.setWebUrlAction(selecClassModel: self.selecClassModel ?? AdvisoryHttpListModel())
        }
    }
}
