using Com.FirmLib.Entity;
using FirmHttpDao;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Com.FirmLib.Bll
{
    #region 关联类
    public class SearchResultList<T> : List<T>
    {
        public SearchResultList()
        {

        }
        public int TotalCount { get; set; }
    }
    #endregion
    /// <summary>
    /// 数据平台管理
    /// </summary>
    public class PlatformBll : BaseHttpBll
    {
        private PlatformBll() : base(@"")
        {

        }
        #region 资产相关
        #region 查询资产
        /// <summary>
        /// 获取资产信息
        /// </summary>
        /// <param name="projectSetting"></param>
        /// <param name="limit"></param>
        /// <param name="filter"></param>
        /// <param name="criteria"></param>
        /// <returns>如果返回值为null;则查询发生错误</returns>
        public SearchResultList<TdAssetItem> GetAssetItems(ProjectSetting projectSetting, SearchLimit limit, SearchFilter filter, SearchCriteria criteria)
        {
            //返回null,表示查询失败
            string tempUrlExtension = BllHttpSetting.Instance.EquipmentUri + string.Format(@"/property/relation_query?projectId={0}&secret={1}", projectSetting.ProjectId, projectSetting.Secret);
            JObject jObject = new JObject();
            jObject.Add("limit", limit.ToJObject());
            jObject.Add("filter", filter.ToJObject());
            jObject.Add("criteria", criteria.ToJObject());
            var result = PostJsonAsync(new Uri(tempUrlExtension, UriKind.RelativeOrAbsolute), jObject);

            SearchResultList<TdAssetItem> items = new SearchResultList<TdAssetItem>();
            int total = 0;
            HandlerResult(result, (jo) =>
            {
                total = Convert.ToInt32(jo["TotalCount"]?.ToString() ?? "0");
                var listStr = jo["Content"].ToString();
               // JArray array = JArray.Parse(listStr);
                items = JsonConvert.DeserializeObject<SearchResultList<TdAssetItem>>(listStr);
            }, (jo) => { this.ErrorMessage = jo["ResultMsg"].ToString(); });
            items.TotalCount = total;
            return items;
        }
        #endregion
        #region 创建资产
        /// <summary>
        /// 在制定项目下创建资产
        /// </summary>
        /// <param name="projectSetting"></param>
        /// <param name="items"></param>
        public BatchResult<List<string>> CreateAssetItems(ProjectSetting projectSetting, List<TdAssetItem> items)
        {
            BatchResultType resultFlag = BatchResultType.Failed;
            //projectSetting.Secret = "123";
            string tempUrlExtension = BllHttpSetting.Instance.EquipmentUri + string.Format(@"/property/create?projectId={0}&secret={1}", projectSetting.ProjectId, projectSetting.Secret);
            List<JObject> jobjects = new List<JObject>();
            items.ForEach(ci => jobjects.Add(ci.ToJObject()));
            var jarray = JArray.FromObject(jobjects);
            JObject jObject = new JObject();
            jObject.Add("criterias", jarray);
            var result = PostJsonAsync(new Uri(tempUrlExtension, UriKind.RelativeOrAbsolute), jObject);
            HandlerResult(result, (jo) =>
            {
              
                if (jo.TryGetValue("Error", out JToken error))
                {
                      resultFlag  = BatchResultType.PartSuccessed;;
                     return;
                }
                if (jo.TryGetValue("Content", out JToken jToken))
                {
                    resultFlag= BatchResultType.Successed;
                    items = JsonConvert.DeserializeObject<SearchResultList<TdAssetItem>>(jToken?.ToString());
                    return;
                }
            }, (jo) => { this.ErrorMessage = jo["ResultMsg"].ToString(); });
            BatchResult<List<string>> batchResult = new BatchResult<List<string>>();
            batchResult.Result = resultFlag;
            if (resultFlag == BatchResultType.Successed)
            {
                 batchResult.AttachInfo = new List<string>(items.Select(a=>a.Id));
            }          
            return batchResult;
        }
        #endregion
        #region 更改
        /// <summary>
        /// 在制定项目下创建资产
        /// </summary>
        /// <param name="projectSetting"></param>
        /// <param name="items"></param>
        public bool UpdateAssetItems(ProjectSetting projectSetting, List<TdAssetItem> items)
        {
            //此时TdAssetItem Infos中的信息和，查询创建不一样，更改的是value的数组形式存值
            bool resultFlag = false;
            string tempUrlExtension = BllHttpSetting.Instance.EquipmentUri + string.Format(@"/property/update?projectId={0}&secret={1}", projectSetting.ProjectId, projectSetting.Secret);
            List<JObject> jobjects = new List<JObject>();
            items.ForEach(ci => jobjects.Add(ci.ToJObject()));
            var jarray = JArray.FromObject(jobjects);
            JObject jObject = new JObject();
            jObject.Add("criterias", jarray);
            var result = PostJsonAsync(new Uri(tempUrlExtension, UriKind.RelativeOrAbsolute), jObject);
            HandlerResult(result, (jo) =>
            {
                resultFlag = true;
            }, (jo) => { this.ErrorMessage = jo["ResultMsg"].ToString(); });

            return resultFlag;
        }
        #endregion

        #region 查询推荐资产
        /// <summary>
        /// 获取资产信息
        /// </summary>
        /// <param name="projectSetting"></param>
        /// <param name="limit"></param>
        /// <param name="filter"></param>
        /// <param name="criteria"></param>
        /// <returns>如果返回值为null;则查询发生错误</returns>
        public SearchResultList<TdAssetItem> GetRecomendAssetItems(ProjectSetting projectSetting, SearchLimit limit, SearchFilter filter, SearchCriteria criteria)
        {
            //返回null,表示查询失败
            string tempUrlExtension = BllHttpSetting.Instance.DpUri + string.Format(@"/recommend?projectId={0}&secret={1}", projectSetting.ProjectId, projectSetting.Secret);
            JObject jObject = new JObject();
            jObject.Add("limit", limit.ToJObject());
            jObject.Add("filter", filter.ToJObject());
            jObject.Add("criteria", criteria.ToJObject());
            var result = PostJsonAsync(new Uri(tempUrlExtension, UriKind.RelativeOrAbsolute), jObject);

            SearchResultList<TdAssetItem> items = new SearchResultList<TdAssetItem>();
            int total = 0;
            HandlerResult(result, (jo) =>
            {
                  total = Convert.ToInt32(jo["TotalCount"]?.ToString() ?? "0");
                if(jo.TryGetValue("Content",out JToken token))
                {
                    var listStr = token.ToString();
                    items = JsonConvert.DeserializeObject<SearchResultList<TdAssetItem>>(listStr);
                }
            
            }, (jo) => { this.ErrorMessage = jo["resultMsg"].ToString(); });
            items.TotalCount = total;
            return items;
        }
        #endregion
        #endregion

        #region 设备相关
        /// <summary>
        /// 获取资产信息
        /// </summary>
        /// <param name="projectSetting"></param>
        /// <param name="limit"></param>
        /// <param name="filter"></param>
        /// <param name="criteria"></param>
        /// <returns>如果返回值为null;则查询发生错误</returns>
        public SearchResultList<TdAssetItem> GetEquipmentItems(ProjectSetting projectSetting, SearchLimit limit, SearchFilter filter, SearchCriteria criteria)
        {
            //返回null,表示查询失败
            //projectSetting.Secret = "saga123456";
            string tempUrlExtension = BllHttpSetting.Instance.EquipmentUri + string.Format(@"/equipment/complex_query?projectId={0}&secret={1}", projectSetting.ProjectId, projectSetting.Secret);
            JObject jObject = new JObject();
            jObject.Add("limit", limit.ToJObject());
           // jObject.Add("filter", filter.ToJObject());
            jObject.Add("criteria", criteria.ToJObject());
            var result = PostJsonAsync(new Uri(tempUrlExtension, UriKind.RelativeOrAbsolute), jObject);

            SearchResultList<TdAssetItem> items = new SearchResultList<TdAssetItem>();
            int total = 0;
            HandlerResult(result, (jo) =>
            {
                total = Convert.ToInt32(jo["TotalCount"]?.ToString() ?? "0");
                var listStr = jo["Content"].ToString();
                items = JsonConvert.DeserializeObject<SearchResultList<TdAssetItem>>(listStr);
            }, (jo) => { this.ErrorMessage = jo["ResultMsg"].ToString(); });
            items.TotalCount = total;
            return items;
        }
        /// <summary>
        /// 更新制定项目的设备信息
        /// </summary>
        /// <param name="projectSetting"></param>
        /// <param name="items"></param>
        public bool UpdateEquipmentItems(ProjectSetting projectSetting, List<TdAssetItem> items)
        {
            //此时TdAssetItem Infos中的信息和，查询创建不一样，更改的是value的数组形式存值
            bool resultFlag = false;
            string tempUrlExtension = BllHttpSetting.Instance.EquipmentUri + string.Format(@"/object/batch_update?projectId={0}&secret={1}", projectSetting.ProjectId, projectSetting.Secret);
            List<JObject> jobjects = new List<JObject>();
            items.ForEach(ci => jobjects.Add(ci.ToJObject()));
            var jarray = JArray.FromObject(jobjects);
            JObject jObject = new JObject();
            jObject.Add("criterias", jarray);
            var result = PostJsonAsync(new Uri(tempUrlExtension, UriKind.RelativeOrAbsolute), jObject);
            HandlerResult(result, (jo) =>
            {
                resultFlag = true;
            }, (jo) => { this.ErrorMessage = jo["ResultMsg"].ToString(); });

            return resultFlag;
        }
        #endregion
    }


   
}
