using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using ASHermed.SinoInterface.Api.ContractModel.TCTrans.Input;
using ASHermed.SinoInterface.ContractModel;
using ASHermed.SinoInterface.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ASHermed.SinoInterface.WebApi.Controllers.TC
{
    [Route("apt/api/crmtransfer")]
    [ApiController]
    [ApiVersion("1.0")]
    public class CrmTransferController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<CrmTransferController> _logger;

        public CrmTransferController(
            IConfiguration configuration,
            ILogger<CrmTransferController> logger)
        {
            _configuration = configuration;
            _logger = logger;
        }

        [HttpPost("doctoradvice")]
        public async Task<BaseResponse<object>> DoctorAdvice(CallCrmInput input)
        {
            _logger.LogInformation($"{input.ToJson()}");

            var crmResponse = await CallApi(input);

            if (!crmResponse.IsSuccessStatusCode)
            {
                _logger.LogInformation($"调用crm接口出错 input-{input.ToJson()};error-{crmResponse.ReasonPhrase}");

                return new BaseResponse<object>
                {
                    Code = 0,
                    Msg = crmResponse.ReasonPhrase,
                    Data = null
                };
            }

            var responseContent = await crmResponse.Content.ReadAsStringAsync();

            _logger.LogInformation($"调用crm接口成功 input-{input.ToJson()};response-{responseContent}");

            var jObject = JsonConvert.DeserializeObject<JObject>(responseContent);

            return new BaseResponse<object>
            {
                Code = 1,
                Msg = "成功",
                Data = jObject
            };
        }

        #region private method

        private async Task<HttpResponseMessage> CallApi(CallCrmInput input)
        {
            var httpClient = new HttpClient();

            var appId = _configuration["AppSettings:TCCallCRMApi:AppId"];
            var appKey = _configuration["AppSettings:TCCallCRMApi:AppKey"];

            httpClient.DefaultRequestHeaders.Add("appId", appId);
            httpClient.DefaultRequestHeaders.Add("appKey", appKey);

            var timeSpan = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
            var secret = _configuration["AppSettings:TCCallCRMApi:Secret"];
            var token = Sha256(appId + appKey + secret + timeSpan);
            httpClient.DefaultRequestHeaders.Add("timeStamp", timeSpan.ToString());
            httpClient.DefaultRequestHeaders.Add("token", token);

            var requestDto = new PPOrderLinkReqDto
            {
                ReqDto = new ReqDto
                {
                    ThirdPartyContent = input.ToJson()
                }
            };

            var requestContent = new StringContent(requestDto.ToJson(), Encoding.UTF8);
            var url = _configuration["AppSettings:TCCallCRMApi:PPOrderPush"];
            var httpResponseMessage = await httpClient.PostAsync(url, requestContent);

            return httpResponseMessage;
        }

        /// <summary>
        /// sha256加密
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Sha256(string text)
        {
            using var mySha256 = SHA256.Create();
            var byts = Encoding.UTF8.GetBytes(text);
            var sha256 = mySha256.ComputeHash(byts);
            var builder = new StringBuilder();
            foreach (var t in sha256)
            {
                builder.Append(t.ToString("X2"));
            }

            return builder.ToString();
        }

        #endregion

    }
}