using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using MySystem.Models;
using Library;
using LitJson;
using MySystem.Models.Main;

namespace MySystem
{
    /// <summary>
    /// 获取腾讯地图地址
    /// </summary>
    public class GetTencentAddressInfoService
    {
        public readonly static GetTencentAddressInfoService Instance = new GetTencentAddressInfoService();
        private GetTencentAddressInfoService()
        { }

        public void Start()
        {
            Thread th = new Thread(GetTencentAddress);
            th.IsBackground = true;
            th.Start();
        }

        public void GetTencentAddress()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("GetTencentAddressInfoQueueHd");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        JsonData jsonObj = JsonMapper.ToObject(data);
                        int Id = int.Parse(jsonObj["MerChantId"].ToString());
                        string Address = jsonObj["Address"].ToString();
                        string Key = Library.ConfigurationManager.AppSettings["TencentKey"].ToString();
                        var info = function.GetWebRequest("https://apis.map.qq.com/ws/geocoder/v1/?address=" + Address + "&key=" + Key);
                        JsonData result = JsonMapper.ToObject(info);
                        //创建成功
                        if (result["status"].ToString() == "0")
                        {
                            WebCMSEntities db = new WebCMSEntities();
                            var merInfo = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                            if (merInfo.Id > 0)
                            {
                                merInfo.Longitude = decimal.Parse(result["result"]["location"]["lng"].ToString());
                                merInfo.Latitude = decimal.Parse(result["result"]["location"]["lat"].ToString());
                                db.SaveChanges();
                                db.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "获取腾讯地图地址线程异常");
                    }
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
    }
}