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

import UIKit

extension MineMoreViewController {
    // MARK:获取我的自定义接口
    func getMyApplicationListHttpCmd(){
        let cmd:HttpCommand = MyApplicationListHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpMyApplicationListHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpMyApplicationListHttpCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        dic[kHttpMyApplicationListHttpCmd_system] = self.systemType.rawValue
        dic[kHttpMyApplicationListHttpCmd_type] = judgmentStrNil(str: self.scope)
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpMyApplicationListHttpResultResponse(result:RequestResult){
        let r:MyApplicationListHttpResult = result as! MyApplicationListHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getMyApplicationListHttpResult()
            setmineCellModelArray(httpArray: array)
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        getAllApplicationHttpListCmd()
//        group.leave()
    }
    func setmineCellModelArray(httpArray:NSMutableArray){
        for index in 0..<httpArray.count {
            let scopeHttpModel:ApplicationHttpScopListModel = httpArray[index] as! ApplicationHttpScopListModel
            self.mineCellModelArray = scopeHttpModel.application
        }
        AccountInfo.sharedInstance().myApplicationCellNum = String(self.mineCellModelArray.count)
//        AccountInfo.sharedInstance().myApplicationCellNum = String(format: "%d", self.mineCellModelArray.count )
//        tableViewCellModel.className = "MineMoreTableViewCell"
//        tableViewCellModel.lineViewShowType = true
//        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: "%d", self?.tableViewCellModel.collcetionViewSectionModellArray.count ?? Int())
//            self?.getType(model: value1 as! MineMoreCollectionViewCellModel)
//            self?.myTableView.reloadData()
//        }
    }
    
    /// 获取所有
    func getAllApplicationHttpListCmd(){
        let cmd:HttpCommand = AllApplicationHttpListCmd.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[kHttpAllApplicationHttpListCmd_userid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        attrDic[kHttpAllApplicationHttpListCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        attrDic[kHttpAllApplicationHttpListCmd_value] = judgmentStrNil(str: self.scope)
        dic[kHttpAllApplicationHttpListCmd_attr] = attrDic
        dic[kHttpAllApplicationHttpListCmd_orderby] = "createon"
        dic[kHttpAllApplicationHttpListCmd_pageNum] = "1"
        dic[kHttpAllApplicationHttpListCmd_pageSize] = ""
        dic[kHttpAllApplicationHttpListCmd_sort] = "desc"
        let filtersDic:NSMutableDictionary = NSMutableDictionary()
        let filtersArray = NSMutableArray()
        filtersArray.add(filtersDic)
        dic[kHttpAllApplicationHttpListCmd_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:AllApplicationHttpListResult = result as! AllApplicationHttpListResult
        if r.isOk() {
            let array:NSMutableArray = r.getAllApplicationHttpListResult()
            self.settableViewCellModel(modelArray: array)
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        group.leave()

    }
    func settableViewCellModel(modelArray:NSMutableArray){
        tableViewCellModel.className = "MineMoreTableViewCell"
        tableViewCellModel.lineViewShowType = true
        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: "%d", self?.tableViewCellModel.collcetionViewSectionModellArray.count ?? Int())

            self?.getType(model: value1 as! MineMoreCollectionViewCellModel)
            self?.myTableView.reloadData()
        }

        tableViewCellModelTwo.className = "MineMoreTableViewCell"
        tableViewCellModelTwo.lineViewShowType = false
        tableViewCellModelTwo.collcetionViewSectionModellArray = (self.getHttpCollcetionViewModellTwoArray(arrays: modelArray, operationType: .AddType))

        tableViewCellModelTwo.changeBlock = {[weak self] (value:Any)in
            self?.changeBlockAction(model: value as! MineMoreCollectionViewCellModel)
        }
        getTableViewCellAllModel(title: self.title!, isAllType: .OftenType)
        self.dataSource .add(tableViewCellModel)
        getStartEditingTableViewCellModel()
        getNormalTableViewCellAllModel()
        getTableViewCellAllModel(title: "所有", isAllType: .AllType)
        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: "%d", 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: "%d", 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:ApplicationHttpListModel = arrays[index] as! ApplicationHttpListModel

            classModel.collcetionViewSectionModellArray.add(self.getHttpMineMoreCollectionViewCellModel(model:httpModel , operationType: operationType, isAllType: .OftenType))
        }
        classModel.vcTitle = judgmentStrNil(str: self.scopes)
        array.add(classModel)
        return array
    }
    ///处理所有常用或应用 对所有Class 根据tags进行分类
    func getHttpCollcetionViewModellTwoArray(arrays:NSMutableArray,operationType:OperationType)->NSMutableArray {
        let heatArray = NSMutableArray()
        let belongArray = NSMutableArray()
        ///根据tags进行分类
        
        for index in 0..<arrays.count {
            let httpModel:ApplicationHttpListModel = arrays[index] as! ApplicationHttpListModel
            if !belongArray.contains(httpModel.belong as Any){
                let classModel = MineMoreTwoTableViewCellModel()
                classModel.vcTitle = httpModel.belong
                belongArray.add(httpModel.belong as Any)
                heatArray.add(classModel)
            }
        }
        ///根据上层的分类，将所有的Class 添加的分类中
        for index in 0..<heatArray.count {
            let classModel:MineMoreTwoTableViewCellModel = heatArray[index] as! MineMoreTwoTableViewCellModel
            classModel.retractUnfoldType = .Retractype
            classModel.retractUnfoldBlack = {[weak self] (value:Any)in
                if self?.editStatusType == .StartEditing {
                    return
                }
                let retractUnfoldType:RetractUnfoldType = value as! RetractUnfoldType
                classModel.retractUnfoldType = retractUnfoldType == .Retractype ? RetractUnfoldType.UnfoldType : RetractUnfoldType.Retractype
                self?.myTableView.reloadData()
            }
            for i in 0..<arrays.count{
                let httpModel:ApplicationHttpListModel = arrays[i] as! ApplicationHttpListModel
                if classModel.vcTitle == httpModel.belong{
                    classModel.collcetionViewSectionModellArray.add(self.getHttpMineMoreCollectionViewCellModel(model:httpModel , operationType: operationType, isAllType: .AllType))
                }
            }
        }
        return heatArray
    }
    func getHttpMineMoreCollectionViewCellModel(model:ApplicationHttpListModel,operationType:OperationType,isAllType:IsAllType)->MineMoreCollectionViewCellModel{
        let collectionViewCellModel = MineMoreCollectionViewCellModel()
        collectionViewCellModel.className = "MineMoreCollectionViewCell"
        collectionViewCellModel.titleValue = model.name
        collectionViewCellModel.applicationid = model.applicationid
        collectionViewCellModel.platforms = model.platforms
        collectionViewCellModel.isInstallation = self.isInstallation(urlString: judgmentStrNil(str: model.iosopenurl!))
        
        collectionViewCellModel.biaojiNum = model.value2
        collectionViewCellModel.imageName = model.imageUrl
        
        collectionViewCellModel.id = model.id
        collectionViewCellModel.title = model.title
        collectionViewCellModel.status = model.status
        collectionViewCellModel.createon = model.createon
        collectionViewCellModel.createby = model.createby
        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
        if AccountInfo.sharedInstance().oldType == "0" {
            if collectionViewCellModel.comments != nil && collectionViewCellModel.comments?.count != 0{
                collectionViewCellModel.applicationPlatformsType = .WebType
            } else {
                collectionViewCellModel.applicationPlatformsType = .AndroidiOSType
            }
        }
        ///class的点击事件
        collectionViewCellModel.block = {[weak self](value:Any) in
//            self?.classAction(selecHttpModel: model)
            self?.refreshTokenHttpAction(selecHttpModel: model)
        }
        collectionViewCellModel.operationType = operationType
        if isAllType == .OftenType {
            ///将所有的自定义title进行存储
            self.mineTitleCellModelArray.add(model.applicationid!)
        } else {
            
        }
        if isAllType == .AllType && self.mineTitleCellModelArray.contains(model.applicationid!) {
            /// 将所有Class中，已经在我的自定义 里面存在的Class，将其状态更改为可删除状态
            collectionViewCellModel.operationType = .DeleteType
        }
        return collectionViewCellModel
    }

    //编辑保存
    func getSaveApplicationsHttpCmd(){
        showHintView()
        let cmd:HttpCommand = SaveApplicationListHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpSaveApplicationListHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpSaveApplicationListHttpCmd_userid] = AccountInfo.sharedInstance().UserId
        dic[kHttpSaveApplicationListHttpCmd_type] = judgmentStrNil(str: self.scope)
        dic[kHttpSaveApplicationListHttpCmd_system] = self.systemType.rawValue
        let array = NSMutableArray()
        dic[kHttpSaveApplicationListHttpCmd_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 httpSaveApplicationListHttpResultResponse(result:RequestResult){
        let r:SaveApplicationListHttpResult = result as! SaveApplicationListHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getSaveApplicationListHttpResult()
            if array.count != 0{
                SMToastView.showMessage("保存成功！")
                if self.applicationType == .HomeApplicationType {
                    NotificationCenter.default.post(name: Notification.Name(rawValue: "inforHomeAction"), object: "0")
                } else {
                    NotificationCenter.default.post(name: Notification.Name(rawValue: "inforAction"), object: "0")
                }
            }
            hidenHintView()
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
            hidenHintView()
        }
        actionHttpGCD()
    }
    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[kHttpSaveApplicationListHttpCmd_applicationid] =  model.applicationid
            dic[kHttpSaveApplicationListHttpCmd_sort] = String(format: "%d",index+1)
            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.belong
        attrDic[kHttpSelectCompanyHttpCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)+",1"
//        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.sysid == "ERP" || self.selecClassModel.sysid == "erp") {
                    SMToastView.showMessage("ERP部门组织获取失败！")
                    hidenHintView()
                    return
                }
                self.setWebUrlAction(selecClassModel: self.selecClassModel)
            }else if companyListModelArray.count == 1 && departmentListModelArray.count == 0  {
                if (self.selecClassModel.sysid == "ERP" || self.selecClassModel.sysid == "erp") {
                    SMToastView.showMessage("ERP部门组织获取失败！")
                    hidenHintView()
                    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 ?? ApplicationHttpListModel())
        }
    }
}
