using System;
using System.IO;
using RestSharp; //依赖版本106.15.0 https://www.nuget.org/packages/RestSharp/106.15.0
using Newtonsoft.Json; //https://www.nuget.org/packages/Newtonsoft.Json
using System.Web.Http;
using System.Collections.Generic;

namespace WebAPI.Controllers.HSSE
{
    public class ImageRecognitionController : ApiController
    {
        const string API_KEY = "2pHOZ7ff76vYgYoIwQnTIB31";
        const string SECRET_KEY = "8q4Oa8wLi6xorfYQgUlEBqM4OOHqFXL7";


        [HttpPost]
        public Model.ResponeData getImageContent([FromBody] ImageRequest imageRequest)
        {
            var responeData = new Model.ResponeData();
            
            try
            {
                var client = new RestClient($"https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token={GetAccessToken()}");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Content-Type", "application/json");
                string image = imageRequest.Image;
                var body = $@"{{""image"":""{image}"",""image_type"":""BASE64"",""max_face_num"":30}}";
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
                string json = response.Content;
                var responseData = JsonConvert.DeserializeObject<ResponseData>(json);
                int errorCode = responseData.error_code;
                if (errorCode != 0)
                {
                    responeData.message = responseData.error_msg;
                }
                else
                {
                    int faceNum = responseData.result.face_num;
                    responeData.data = faceNum;
                }
            }
            catch (Exception ex)
            {
                responeData.code = 0;
            }

            return responeData;
            
        }

        /**
        * 获取文件base64编码
        * @param path 文件路径
        * @return base64编码信息,不带文件头
        */
        public string GetFileContentAsBase64(string path)
        {
            using (FileStream filestream = new FileStream(path, FileMode.Open))
            {
                byte[] arr = new byte[filestream.Length];
                filestream.Read(arr, 0, (int)filestream.Length);
                string base64 = Convert.ToBase64String(arr);
                return base64;
            }
        }


        /**
        * 使用 AK,SK 生成鉴权签名(Access Token)
        * @return 鉴权签名信息(Access Token)
        */
        public string GetAccessToken()
        {
            var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", API_KEY);
            request.AddParameter("client_secret", SECRET_KEY);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
            return result.access_token.ToString();
        }
        
        public class ImageRequest
        {
            public string Image { get; set; }
        }
        
        public class Location
        {
            public double left { get; set; }
            public double top { get; set; }
            public double width { get; set; }
            public double height { get; set; }
            public double rotation { get; set; }
        }

        public class Angle
        {
            public double yaw { get; set; }
            public double pitch { get; set; }
            public double roll { get; set; }
        }

        public class Face
        {
            public string face_token { get; set; }
            public Location location { get; set; }
            public double face_probability { get; set; }
            public Angle angle { get; set; }
        }

        public class Result
        {
            public int face_num { get; set; }
            public List<Face> face_list { get; set; }
        }

        public class ResponseData
        {
            public int error_code { get; set; }
            public string error_msg { get; set; }
            public long log_id { get; set; }
            public long timestamp { get; set; }
            public int cached { get; set; }
            public Result result { get; set; }
        }
        
    }
}