using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using MadRunFabirc.Model;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using Newtonsoft.Json;
using WechatApi.IRepositories;
using WechatApi.Model;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WechatApi.Controllers
{
    [ApiVersion("6.0")]
    //[Authorize]
    [Produces("application/json")]
    [Route("api/Location/[action]")]
    public class LocationController : BaseController
    {
        private readonly ILogger<LocationController> _logger;
        private readonly ILocationRepository _locationRepository;
        private readonly IDistributedCache _cache;
        private readonly IConfiguration _configuration;
        //private 
        public LocationController(
            ILogger<LocationController> logger,
            ILocationRepository locationRepository,
            IDistributedCache cache,
            IConfiguration configuration)
        {
            _logger = logger;
            _locationRepository = locationRepository;
            _cache = cache;
            _configuration = configuration;
        }

        [Authorize]
        /// <summary>
        /// 供APP调用，APP发送定位信息到服务端
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PutLocationAsync(LocationInput input)
        {
            #region 参数检查
            if (string.IsNullOrWhiteSpace(input.Longitude))
                return Error("经度是必需字段");
            if (string.IsNullOrWhiteSpace(input.Latitude))
                return Error("纬度是必需字段");
            #endregion

            #region 存入mongodb
            var location = new Location
            {
                usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value,
                longitude = input.Longitude,
                latitude = input.Latitude,
                createtime = DateTime.Now.ToLocalTime()
            };
            var flag = await _locationRepository.Add(location);

            #endregion


            var timespan = 0;
            int.TryParse(_configuration["AppSendLocationTimespan"], out timespan);
            if (!flag)
                return Error("定位存储操作失败");

            #region 存入redis缓存
            await _cache.SetStringAsync($"location{location.usercode}", location.ToJson());
            #endregion

            var resultobj = new object();

            #region 根据经纬度获取位置详情--腾讯地图api
            string url = _configuration["location:url"];
            string key = _configuration["location:key"];
            string poi = _configuration["location:poi"];

            string strresult = HttpMethods.HttpGet(url + $"?location={location.longitude},{location.latitude}&key={key}&get_poi={poi}");
            if (!string.IsNullOrEmpty(strresult))
            {
                var result = strresult.ToJObject();
                if (result["status"].ToString() == "0")
                {
                    resultobj = result["result"];
                }
            } 
            #endregion

            var obj = new
            {
                timesapn = timespan > 0 ? timespan : 30,
                result = resultobj
            };

            return Success("成功", obj);
        }


        /// <summary>
        /// 供微信端调用，获取指定维修人员最新的定位信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetLocationAsync(string usercode = "")
        {
            #region 参数检查
            if (string.IsNullOrWhiteSpace(usercode))
                return Error("工号是必需字段");
            #endregion

            Location location = null;
            #region 从Redis缓存中查询定位信息,如果Redis缓存中不存在，从MongoDB中查询

            var locationStr = await _cache.GetStringAsync($"location{usercode}");
            if (!string.IsNullOrWhiteSpace(locationStr))
            {
                //location = JsonConvert.DeserializeObject<List<Location>>(locationStr)
                //   .Where(x => x.usercode == usercode)
                //   .OrderBy(x => x.createtime).LastOrDefault();

                location = locationStr.ToObject<Location>();
            }

            if (location == null)
            {
                var sort = Builders<Location>.Sort.Descending("createtime");
                location = await _locationRepository.GetSingle(x => x.usercode == usercode, sort);
            }

            #endregion

            if (location == null)
                return Error("获取定位失败");

            #region 存入redis缓存
            await _cache.SetStringAsync($"location{location.usercode}", location.ToJson());
            #endregion

            return Success("成功", location);
        }
    }
}
