using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Common
{
    public class HttpRequest
    {
        public string GetToken()
        {
            string serviceAddress = "http://10.1.213.213:8765/oauth/token?client_id=c1&client_secret=secret&grant_type=password&username=jk-znjl&password=jk-znjl";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "POST";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding == null || encoding.Length < 1)
            {
                encoding = "UTF-8"; //默认编码  
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            string retString = reader.ReadToEnd();
            Token stu = new Token();
            Token stu1 = JsonConvert.DeserializeObject<Token>(retString);
            return stu1.access_token;
        }
        public string getCarNo(string code, string token)
        {
            //string serviceAddress = "http://ymt.jiugang.com:5555/transport8766/tpwaybillcumstom/getTmsWaybillGoodsListByTmsWaybill?tmsWaybillId=" + code;
            string serviceAddress = "http://10.1.213.213:8766/tpwaybillcumstom/getWaybillStateById?tmsWayBillId=" + code;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.Headers.Add("Authorization", "bearer " + token);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            JObject res = JsonConvert.DeserializeObject<JObject>(retString);
            string carNo = string.IsNullOrEmpty(res.SelectToken("data.['vehicleId']").Value<string>()) ? "" : res.SelectToken("data.['vehicleId']").Value<string>().Replace("-","");
            return carNo;
        }
    }

    public class Token
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string refresh_token { get; set; }
        public string scope { get; set; }
        public string jti { get; set; }
        public string expires_in { get; set; }
    }

}
