using Fuel.Core;
using Fuel.Core.Models;
using Fuel.Core.Nozzle.Dto;
using Fuel.Core.Transactions.Dto;
using Fuel.Core.WechatServer;
using FuelServer.Core.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Fuel.Application.Service
{
    public class SiteService: ISiteService
    {
        public readonly IFreeSql _fsql;
        public SiteService(IFreeSql freeSql)
        { 
             _fsql = freeSql;
        }
        public async Task<ServiceResponse> GetSiteInfo()
        {
            Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
            var site = _fsql.Select<businessunitinfo>().Where(_ => _.Buid == Buid ).First();
            var SiteInfo = new {
                site = new { 
                  Name = site.Name,//站点名称
                  GpsCoordinates = site.GpsCoordinates,//油站经纬度
                  PaymentMode = site.PaymentMode,//预支付：1，后支付：2
                },
                userInfo = new
                {
                    UserName = "",//用户名称
                    UserAvatarUrl = "",//用户头像地址
                    UserAddress= "",//用户地址
                    UserPhoneNumber = ""//用户手机号
                }
            };
            return ServiceResponse.Ok(SiteInfo);
        }
        public async Task<ServiceResponse> GetAppidSecret(string Code)
        {
            Guid Buid = HttpRequestReader.GetCurrentBuId(); //站点id
            var site = _fsql.Select<businessunitinfo>().Where(_ => _.Buid == Buid).First();
            if (site == null)
            {
                return ServiceResponse.Error("获取站点小程序appid与Secret失败，BUID：" + Buid);
            }
            WechatUserSessionResponse userSession =
               await WechatLoginCodeToSessionKeyNOpenId(Code, site.Appid,site.Secret);
            var thirdSessionKey = GenerateThirdSessionKey();
            WechatUserSessionRepo.AddUserSession(thirdSessionKey, userSession);
            return ServiceResponse.Ok(thirdSessionKey);
        }
        /// <summary>
        /// 微信小程序登录
        /// </summary>
        /// <param name="jsCode"></param>
        /// <param name="AppId"></param>
        /// <param name="AppSecret"></param>
        /// <returns></returns>
        public static async Task<WechatUserSessionResponse> WechatLoginCodeToSessionKeyNOpenId(string jsCode, string AppId, string AppSecret)
        {
            string url = string.Format(WechatConstants.Jscode2sessionUrl,
               AppId, AppSecret, jsCode);
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();

                var userSession = JsonConvert.DeserializeObject<WechatUserSessionResponse>(responseContent);

                return userSession;
            }
            else
            {
                return null;
            }

        }
        private string GenerateThirdSessionKey()
        {
            var thirdSessionKey = Guid.NewGuid();
            return thirdSessionKey.ToString();
        }

    }
}
