//
//  WeChatAPI.swift
//  MobilePortal
//
//  Created by caiyang on 2020/5/9.
//  Copyright © 2020 yin chen. All rights reserved.
//

import UIKit
import Moya
import HandyJSON
import SwiftyJSON

let WeChatProvider = MoyaProvider<WeChatAPI>()

enum WeChatAPI {
    case weChatAccessToken(value:String)
    case weChatRefreshToken(value:String)
    case weChatUserInfo(value:String)
    case weChatIsAccessToken(value:String)
}
extension WeChatAPI: TargetType {
    var baseURL: URL {
//        https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
//        https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
//        https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        return URL(string: "https://api.weixin.qq.com/sns")!
    }
    
    var path: String {
        switch self {
        case .weChatAccessToken: return "/oauth2/access_token"
        case .weChatRefreshToken: return "/oauth2/refresh_token"
        case .weChatUserInfo: return "/userinfo"
        case .weChatIsAccessToken: return "/auth"
        }
    }
    
    var method: Moya.Method {
        return .get
    }
    
    var sampleData: Data { return "".data(using: String.Encoding.utf8)! }
    var headers: [String : String]? {
        return ["Content-type":"application/json;charset=utf-8"]
    }
    
    var task: Task {
        var parmeters:[String:Any] = [:]
        switch self {
        case .weChatAccessToken( _):
            /// 应用唯一标识，在微信开放平台提交应用审核通过后获得
            parmeters["appid"] = AccountInfo.sharedInstance().weChat_appid
            /// 应用密钥 AppSecret，在微信开放平台提交应用审核通过后获得
            parmeters["secret"] = "432766727e242829aabc0add3afb67fd"
            /// 填写第一步获取的 code 参数
            parmeters["code"] = AccountInfo.sharedInstance().weChat_code
            /// 填 authorization_code
            parmeters["grant_type"] = "authorization_code"
        case .weChatRefreshToken( _):
            parmeters["appid"] = AccountInfo.sharedInstance().weChat_appid
            parmeters["grant_type"] = "refresh_token"
            parmeters["refresh_token"] = AccountInfo.sharedInstance().weChat_refresh_token
        case .weChatUserInfo( _):
            parmeters["access_token"] = AccountInfo.sharedInstance().weChat_access_token
            parmeters["openid"] = AccountInfo.sharedInstance().weChat_unionid
            parmeters["lang"] = "zh_CN"
        case .weChatIsAccessToken( _):
            parmeters["access_token"] = AccountInfo.sharedInstance().weChat_access_token
            parmeters["openid"] = AccountInfo.sharedInstance().weChat_openid
        }
        //        return .requestData(jsonToData(jsonDic: parmeters)!)
        return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
    }
}
