//
//  CustomerServiceRootVC+ClassAction.swift
//  MobilePortal
//
//  Created by caiyang on 2020/6/4.
//  Copyright © 2020 yin chen. All rights reserved.
//

import UIKit

extension CustomerServiceRootVC {
    /// MARK: 刷新RefreshToken
    func refreshTokenHttpAction(selecHttpModel:ApplicationHttpListModel) {
        self.selecClassModel = selecHttpModel
        if (AccountInfo.sharedInstance().loginType != nil && AccountInfo.sharedInstance().loginType == "1") {
            SinglePointWeChatHttp.sharedInstance().judgmentTokenExpired(resultBlock: {[weak self] (value) in
                self?.classAction(selecHttpModel: selecHttpModel)
            }) { [weak self] (value) in
                self?.classAction(selecHttpModel: selecHttpModel)
            }
        } else {
            self.classAction(selecHttpModel: selecHttpModel)
        }
    }
    //点击应用响应事件
    func classAction(selecHttpModel:ApplicationHttpListModel){
        if AccountInfo.sharedInstance().oldType == "0" {
            classActionOld(selecHttpModel: selecHttpModel, type: .OftenApplicationType)
            return
        }
        self.selecClassModel = selecHttpModel
        if selecHttpModel.pointstate == "0" {
            SMAlertView.showAlert("单点未开启,请联系管理员！")
            return
        }
        if self.selecClassModel.applicationPlatformsType == .AndroidiOSType {
            myApplicationAction(httpDetailModel: selecHttpModel)
        } else {
            oftenApplicationType(httpDetailModel: selecHttpModel)
        }

    }
    //我的应用响应事件
    private func myApplicationAction(httpDetailModel:ApplicationHttpListModel){
        if self.isInstallation(urlString: httpDetailModel.iosopenurl!) == false{
            //打开APP
            self.appViewsSstatisticsAction(httpModel: httpDetailModel, type: "3")
            self.downloadOpenApp(urlString: self.getSignInAction(model: httpDetailModel), openUrlType: .OpenAppType)
        }else{
            if httpDetailModel.iosurl?.count == 0{
                SMToastView.showMessage("该应用暂无下载地址，请联系管理员！")
                return
            }
            self.appViewsSstatisticsAction(httpModel: httpDetailModel, type: "2")
            self.downloadOpenApp(urlString: httpDetailModel.iosurl!, openUrlType: .DownloadType)
        }
    }
    // MARK:web响应事件
    func oftenApplicationType(httpDetailModel:ApplicationHttpListModel){
        if httpDetailModel.pointstate == "0" {
            self.setWebUrlAction(selecClassModel: httpDetailModel)
        }
        let companyInfo:SelecCompanyDepartmentInfo = getSelecCompanyDepartment(tags: httpDetailModel.sysid ?? String())
        if companyInfo.tags == nil {
            getSelectCompanyHttpCmd()
        }else{
            if httpDetailModel.sysid == "ERP" && companyInfo.sysOrg == ""{
                SMToastView.showMessage("ERP组织获取失败！")
                hidenHintView()
                return
            }
            self.setCacheAccountInfo(companyInfo: companyInfo, selecClassModel: self.selecClassModel)
            return
        }
    }
    /// 点击响应事件
    func classActionOld(selecHttpModel:ApplicationHttpListModel,type:ApplicationType){
        self.selecClassModel = selecHttpModel
        if type == .MyApplicationType {
            self.myApplicationActionOld(httpDetailModel: selecHttpModel)
        } else {
            self.oftenApplicationTypeOld(httpDetailModel: selecHttpModel)
        }
    }
    /// 我的应用
    func myApplicationActionOld(httpDetailModel:ApplicationHttpListModel){
        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: "", isHomePushType: .YesIsHomePushType, appid: httpDetailModel.appid!, isEncryptionType: .YesEncryptionType)
            return
        }
        if self.isInstallation(urlString: httpDetailModel.openurl!) == false{
            self.downloadOpenApp(urlString: httpDetailModel.openurl!, openUrlType: .OpenAppType)
        }else{
            if httpDetailModel.appid?.count == 0{
                SMToastView.showMessage("该应用暂无下载地址，请联系管理员！")
                return
            }
            self.downloadOpenApp(urlString: httpDetailModel.appid!, openUrlType: .DownloadType)
        }
    }
    /// 我的常用
    func oftenApplicationTypeOld(httpDetailModel:ApplicationHttpListModel) {
        let companyInfo:SelecCompanyDepartmentInfo = getSelecCompanyDepartment(tags: httpDetailModel.sysid ?? String())
        if companyInfo.tags == nil {
            getSelectCompanyHttpCmd()
        }else{
            if httpDetailModel.belong == "ERP" && companyInfo.sysOrg == ""{
                SMToastView.showMessage("ERP组织获取失败！")
                return
            }
            self.setCacheAccountInfo(companyInfo: companyInfo, selecClassModel: self.selecClassModel)
            return
        }
    }
    // 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()
    }
    private 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()
                return
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        hidenHintView()
    }
    // MARK:解析出只有一个公司和只有一个部门时
    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)
    }
    // MARK:解析出只有一个公司时
    func selectOneCompany(companyListArray:NSMutableArray){
        let companyModel:SelectCompanyHttpCompanyDataModel = companyListModelArray[0] as! SelectCompanyHttpCompanyDataModel
        self.setClassWebUrlAccountInfo(selecClassModel: self.selecClassModel, companyModel: companyModel, departmentModel: SelectCompanyHttpOrgListDataModel())
        
    }
    // MARK: 跳转公司
    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)
    }
    
    @objc func mineGotoWebVC(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.setWebUrlAction(selecClassModel: self.selecClassModel ?? ApplicationHttpListModel())
        }
    }
}
