using Com.FirmLib.Entity;
using FWindSoft.SystemExtensions;
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
{
    /// <summary>
    /// 综合查询
    /// </summary>
    public class GeneralBll : BaseHttpBll
    {
        private GeneralBll() : base(@"")
        {

        }
        /// <summary>
        /// 获取产品目录信息
        /// </summary>
        /// <returns></returns>
        public List<BrandTreeItem> GetProductTypeItems()
        {
            List<ManufactureTreeItem> items = new List<ManufactureTreeItem>();
            string tempUrlExtension = @"/auxiliary/query/all";
            var uri = new Uri(GetEndUri() + tempUrlExtension, UriKind.RelativeOrAbsolute);
            JObject jObject = new JObject();
            jObject.Add("type", JArray.FromObject(new List<string>() { "manufacturer" }));
            var result = PostJsonAsync(uri,jObject);
            HandlerResult(result, (jo) =>
            {
                var listStr = jo["content"]["manufacturer"].ToString();
                items = JsonConvert.DeserializeObject<List<ManufactureTreeItem>>(listStr);
            });
            return items.SelectMany(v=>v.Brands).ToList();
        }
        /// <summary>
        /// 获取指定族的产品型号目录
        /// </summary>
        /// <param name="items"></param>
        /// <param name="familyCode"></param>
        /// <returns></returns>
        public List<BrandTreeItem> GetProductTypeItems(List<BrandTreeItem> items,string familyCode)
        {
            List<BrandTreeItem> filterItems = new List<BrandTreeItem>();
            foreach (var brand in items)
            {
                List<ProductTreeItem> useProductItems = new List<ProductTreeItem>();
                foreach (var product in brand.Products)
                {
                    if (product.FamilyCode == familyCode)
                    {
                        useProductItems.Add(product);
                    }
                }
                if (useProductItems.Any())
                {
                    //防止引用类型可能互相感染
                    var newBrand = brand.Clone();
                    newBrand.Products = new List<ProductTreeItem>();
                    newBrand.Products.AddRange(useProductItems);
                    filterItems.Add(newBrand);
                }
            }

            return filterItems;
        }
    }
}
