//Created  on 2019/7/3 by  LCD:https://github.com/liucaide .

/***** 模块文档 *****
 *
 */




import Foundation
import CaamDau
import Alamofire
import SwiftyJSON

public class App_Net: CD_AppDelegate {
    
    var observer:[NSObjectProtocol] = []
    
    let domainGetPath = "/xinke_zmb/config.js"
    var domainType:Int = 0
    func domainGet(_ type:Int) -> (String, String) {
        switch type {
        case -1:
            return ("http://mxinktv2.5mall.com", "开发环境")
        case 0:
            return ("http://mxinktv2.5mall.com", "测试环境")
        case 1:
            if let url = UserDefaults.standard.string(forKey: "appdomain"), url.hasPrefix("http") {
                return (url, "生产环境")
            }
            return ("http://mxinktv2.5mall.com", "生产环境")
        case 2:
            return ("http://mxinktv2.5mall.com", "生产环境")
        default:
            return ("", "未配置环境")
        }
    }
    ///- 生产、测试环境 域名配置
    func domainSwitching(_ type:Int) {
        domainType = type
        CD_Net.config.baseURL = domainGet(type).0
    }
    var count = 0
    /// 从网络配置请求域名
    func requestDomain() {
        let temp = Int(arc4random()%10000)+1
        CD_Net()
            .baseURL("http://appdomain.5mall.com/m/domain")
            .path(domainGetPath)
            .parameters(["d" : temp])
            .method(.get)
            .success({ [weak self](res) in
                let json = JSON(res)
                if let domain = json["domain"].string {
                    UserDefaults.standard.set(domain, forKey: "appdomain")
                    UserDefaults.standard.synchronize()
                    self?.domainSwitching(1)
                }else{
                    self?.requestDomainFailure()
                }
            })
            .failure({ [weak self](_) in
                self?.requestDomainFailure()
            }).request(isSubjoin: false, handler: nil)
    }
    func requestDomainFailure() {
        if let url = UserDefaults.standard.string(forKey: "appdomain"), url.hasPrefix("http") {
            self.domainSwitching(1)
        }
        else if count < 10 {
            count += 1
            requestDomain()
        }
    }

    
    public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        /*/ - 生产、测试环境 域名配置
        #if DEBUG
        let type = -1
        #else
        let type = 1
        #endif
        domainSwitching(type)
        /// 从网络配置请求域名
        requestDomain()
        */
        //CD_Net.ssl(whthCer: "certificate", bundleForm: (App_Net.self, "UtilNet"))
        
        // - 基本网络配置
        CD_Net.config.method = .post
        CD_Net.config.encoding = JSONEncoding(options: [])
        // responseStyle 默认为.data
        //CD_Net.config.responseStyle = .json
        CD_Net.config.headers = ["User-Agent":"Mozilla/5.0 (compatible; mobile; ios;android;zzb;fwpt;)"]
        //UserDefCore.domain.save(url)
        CD_Net.config.log = true
        CD_Net.config.logHandler = { (res, h, p) in
            guard let res = res else { return }
            var url:URL?
            var value:Any?
            if let res = res as? DataResponse<Any> {
                url = res.request?.url
                value = res.result.value
            }
            else if let res = res as? DataResponse<Data> {
                url = res.request?.url
                value = res.result.value
            }
            else if let res = res as? DataResponse<String> {
                url = res.request?.url
                value = res.result.value
            }
            debugPrint("---👉👉👉", url ?? "")
            debugPrint("Parameters：", p ?? "")
            debugPrint(JSON( value ?? "未知数据"))
            debugPrint("----------  👻")
        }
        
        // - 登录登出  接口增补参数配置
        if !User.shared.info.userid.isEmpty {
            CD_Net.config.parametersSubjoin = [
                "userid":User.shared.info.userid,
                "companyid":User.shared.info.company_info_id]
            CD_Net.config.parametersHandler = { (p) -> [String:Any]? in
                /// 执行参数签名
                return p
            }
            userMessageOnCache()
            App_Net.requestData()
        }
        observer.append(User.notice.signIn.add(block: { (_) in
            CD_Net.config.parametersSubjoin = [
                "userid":User.shared.info.userid,
                "companyid":User.shared.info.company_info_id]
            App_Net.requestData()
        }))
        observer.append(User.notice.signOut.add(block: { (n) in
            CD_Net.config.parametersSubjoin = [:]
        }))
        observer.append(User.notice.signForced.add(block: { (n) in
            CD_Net.config.parametersSubjoin = [:]
        }))
        
        
        debuggingDomainChange()
        return true
    }
    /// 获取用户信息
    func userMessageOnCache() {
        /// 从缓存中读取
        CD_Net()
            .path("/m/login/index.jhtml")
            .onCache(withData: User.shared.account) { (data) in
                guard let m = data.mapBase(User.Detail.self),
                    m.success == "2" else {
                        return
                }
                guard User.shared.detail.success.isEmpty else {
                    return
                }
                let num = User.shared.detail.carNum
                User.shared.detail = m
                User.shared.detail.carNum = num
        }
    }
    
    public static func requestData() {
        requestUserMessage()
        requestCarList()
    }
    
    public static func requestUserMessage() {
        /// 从网络中读取
        CD_Net()
            .path("/m/login/index.jhtml")
            .toCache(withData: User.shared.account)
            .mapModel(withCodable: User.Detail.self, succeed: { (e) in
                let num = User.shared.detail.carNum
                User.shared.detail = e
                User.shared.detail.carNum = num
                User.notice.infoUpdate.post()
            })
            .request()
        requestUserInfo()
    }
    
    static func requestUserInfo() {
        CD_Net()
            .path("/m/member/getInfo.jhtml")
            .toCache(withData: User.shared.account)
            .mapJSON({ (json) in
                User.shared.info.memo = json["memo"].stringValue
            })
            .request()
    }
    
    // 购物车
    public static func requestCarList() {
        CD_Net()
            .path("/m/cart/list.jhtml")
            .mapJSON({ (json) in
                //User.shared.detail.carNum = json["datas"].arrayValue.compactMap{$0["items"].arrayValue.count}.reduce(0, +)
                let num = json["datas"].arrayValue.compactMap{$0["items"].arrayValue.compactMap{$0["quantity"].intValue}.reduce(0, +)}.reduce(0, +)
                User.shared.detail.carNum = num
                User.notice.other.post("carNum")
            })
            .request()
    }
}



extension App_Net {
    func debuggingDomainChange(){
        let notice = NotificationCenter.default
        let name = Notification.Name("App_Debugging.domainChange")
        observer.append(notice.addObserver(forName: name, object: nil, queue: nil) { [weak self](n) in
            guard let self = self else{ return }
            var domain = self.domainGet(self.domainType)
            if domain.0 != CD_Net.config.baseURL {
                domain.0 = CD_Net.config.baseURL
            }
            UIAlertController.cd_init(style: .actionSheet).cd
                .title("环境切换")
                .message("当前：" + domain.1 + "：" + domain.0)
                .action("取消", style: .cancel)
                .action("开发环境", handler: { [weak self](a) in
                    self?.domainSwitching(-1)
                    User.shared.signOut(User.shared.account)
                    CD.window?.hud_msg("环境已切换:"+CD_Net.config.baseURL)
                })
                .action("测试环境", handler: { [weak self](a) in
                    self?.domainSwitching(0)
                    User.shared.signOut(User.shared.account)
                    CD.window?.hud_msg("环境已切换:"+CD_Net.config.baseURL)
                })
                .action("生产环境", handler: { [weak self](a) in
                    self?.domainSwitching(1)
                    User.shared.signOut(User.shared.account)
                    CD.window?.hud_msg("环境已切换:"+CD_Net.config.baseURL)
                })
                .show()
        })
    }
}
