
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmManufactureInfo.cs
//文件描述: 生产厂商信息维护
//创 建 者: xls
//创建日期: 2018/5/23 23:22:04
//版 本 号：1.0.0.0
////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Com.FirmLib.Bll;
using Com.FirmLib.Entity;
using Com.FirmLib.UI.BllCommon;
using Com.FirmLib.UI.Manufacturer.Model;
using FWindSoft.Data;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Tools;
using FWindSoft.Wpf;

namespace Com.FirmLib.UI.Manufacturer
{
    public class VmManufactureInfo : BaseViewModel
    {
        public VmManufactureInfo()
        {
            Init();
        }

        private void Init()
        {
        }
        public void Init(LoadParameter parameter)
        {
            var id = parameter.Parameter as string;
            Id = id;
            if (string.IsNullOrEmpty(Id))
                return;
            LoadManufactureItem(id);
            LoadBrandItems();
            LoadProjectAssetItems(id);
            //LoadSellerItems(id);
            //LoadMaintainerItems(id);
            LoadVenderItems(id);
        }
        #region 属性相关
        public string Id { get; private set; }

        private string m_ManufactureName;
        /// <summary>
        /// 生产厂家名称
        /// </summary>
        public string ManufactureName
        {
            get { return this.m_ManufactureName; }
            set
            {
                this.m_ManufactureName = value;
                RaisePropertyChanged(() => this.ManufactureName);
            }
        }
        private ObservableCollection<BrandShowItem> m_Brands;
        /// <summary>
        /// 关联品牌
        /// </summary>
        public ObservableCollection<BrandShowItem> Brands
        {
            get { return this.m_Brands; }
            set
            {
                this.m_Brands = value;
                RaisePropertyChanged(() => this.Brands);
            }
        }



        private BrandShowItem m_CurrentSelectedBrand;
        /// <summary>
        /// 当前选中品牌
        /// </summary>
        public BrandShowItem CurrentSelectedBrand
        {
            get { return this.m_CurrentSelectedBrand; }
            set
            {
                this.m_CurrentSelectedBrand = value;
                GetProductsByBranch(value);
                RaisePropertyChanged(() => this.CurrentSelectedBrand);
            }
        }

        private ObservableCollection<ProductShowItem> m_ProductItems;
        /// <summary>
        /// 产品信息集合
        /// </summary>
        public ObservableCollection<ProductShowItem> ProductItems
        {
            get { return this.m_ProductItems; }
            set
            {
                this.m_ProductItems = value;
                RaisePropertyChanged(() => this.ProductItems);
            }
        }



        private ObservableCollection<ProjectAssetShowItem> m_ProjectAssetItems;
        /// <summary>
        /// 项目资产条目
        /// </summary>
        public ObservableCollection<ProjectAssetShowItem> ProjectAssetItems
        {
            get { return this.m_ProjectAssetItems; }
            set
            {
                this.m_ProjectAssetItems = value;
                RaisePropertyChanged(() => this.ProjectAssetItems);
            }
        }



        private ObservableCollection<RefVenderShowItem> m_SellerItems;
        /// <summary>
        /// 关联供应商信息
        /// </summary>
        public ObservableCollection<RefVenderShowItem> SellerItems
        {
            get { return this.m_SellerItems; }
            set
            {
                this.m_SellerItems = value;
                RaisePropertyChanged(nameof(this.SellerItems));
            }
        }


        private ObservableCollection<RefVenderShowItem> m_MaintainerItems;
        /// <summary>
        /// 关联维修商信息
        /// </summary>
        public ObservableCollection<RefVenderShowItem> MaintainerItems
        {
            get { return this.m_MaintainerItems; }
            set
            {
                this.m_MaintainerItems = value;
                RaisePropertyChanged(nameof(this.MaintainerItems));
            }
        }
        #endregion

        #region 命令相关

        /// <summary>
        /// 添加品牌
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddBranchCommand(object parameter)
        {

            try
            {
                WinBrandEditor win = new WinBrandEditor();
                BrandShowItem item = new BrandShowItem() { ManufacturerId = Id };
                LoadParameter.StartParameter(win, new LoadParameter(item));
                win.Owner = this.GetWindow();
                if (win.ShowDialog() == true)
                {
                    //刷新品牌列表,切换到当前品牌视图
                    LoadBrandItems();
                    if (!win.AddProduct)
                        return;
                    #region 继续添加产品
                    //todo 进行产品添加，存在默认的品牌初始值
                    var brandId = win.BrandId;
                    WinProductEditor winProduct = new WinProductEditor();
                    ManufactureParameter startParameter = new ManufactureParameter();
                    startParameter.Manufacture.Id = Id;
                    startParameter.Branch.Id = brandId;
                    LoadParameter.StartParameter(winProduct, new LoadParameter(startParameter));
                    winProduct.Owner = this.GetWindow();
                    if (winProduct.ShowDialog() == true)
                    {
                        //todo 刷新产品列表
                        if (CurrentSelectedBrand != null && CurrentSelectedBrand.Id == brandId)
                        {
                            LoadProdutItems(brandId);//这个可能无效刷新，因为当前
                        }

                        if (winProduct.ManageType)
                        {
                            WinProductType winType = new WinProductType();
                            //todo 初始化参数信息
                            ProductShowItem showItem = new ProductShowItem();
                            showItem.VenderId = Id;
                            showItem.BrandId = brandId;

                            showItem.ProductId = winProduct.ProductId;


                            LoadParameter.StartParameter(winType, new LoadParameter(showItem));
                            winType.Show(this.GetNavigationBar());
                        }
                    }
                    #endregion

                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanAddBranchCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 添加产品
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddProductCommand(object parameter)
        {

            try
            {
                ManufactureParameter startParameter = new ManufactureParameter();
                startParameter.Manufacture.Id = Id;
                WinProductEditor win = new WinProductEditor();
                LoadParameter.StartParameter(win, new LoadParameter(startParameter));
                win.Owner = this.GetWindow();
                if (win.ShowDialog() == true)
                {
                    if (CurrentSelectedBrand != null)
                    {
                        //理论上添加了该品牌的产品，才去更新
                        LoadProdutItems(CurrentSelectedBrand.Id);
                    }

                    if (win.ManageType)
                    {
                        WinProductType winType = new WinProductType();
                        ProductShowItem showItem = new ProductShowItem();
                        showItem.VenderId = Id;
                        showItem.BrandId = win.BrandId;
                        showItem.ProductId = win.ProductId;
                        //showItem.ProductName = "新产品名";//todo通过id获取产品名称

                        LoadParameter.StartParameter(winType, new LoadParameter(showItem));
                        winType.Show(this.GetNavigationBar());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanAddProductCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 删除产品
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void DeleteCommand(object parameter)
        {
            try
            {
                ProductShowItem item = parameter as ProductShowItem;
                if (item == null)
                    return;
                var result = MessageTip.Show(this.GetWindow(), "是否要删除", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    var flag=BllFactory<ProductBll>.Instance.Delete(new ProductItem() { Id = item.ProductId });
                    if (!flag)
                    {
                        MessageTip.Show(this.GetWindow(), "删除失败");
                    }

                    LoadProdutItems(CurrentSelectedBrand.Id);//或者用下面的方式
                   // ProductItems.Remove(item);
                }
            }
            catch (Exception ex)
            {
              MessageTipEx.Show(this.GetWindow(), ex);
            }
        }
        public bool CanDeleteCommand(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 更新品牌命令
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void UpdateBranchCommand(object parameter)
        {

            try
            {
                BrandShowItem item = parameter as BrandShowItem;
                WinBrandEditor win = new WinBrandEditor();
                LoadParameter.StartParameter(win, new LoadParameter(item));
                win.Owner = this.GetWindow();
                if (win.ShowDialog() == true)
                {
                    //如果是修改完成，根据Id去更新名称。如果是删除完成，则重新加载品牌信息
                    if (win.UseDelete)
                    {
                        //更新品牌信息
                        LoadBrandItems();
                    }
                    else
                    {
                        //更新BranchItem名称
                        item.Name = GetBrandName(item.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanUpdateBranchCommand(object parameter)
        {
            return true;
        }


        /// <summary>
        /// 调用资源清单命令
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void GoAssetCommand(object parameter)
        {

            try
            {
                ProjectAssetShowItem item = parameter as ProjectAssetShowItem;
                if (item == null)
                    return;
                WinProjectAssetList win = new WinProjectAssetList();
                LoadParameter.StartParameter(win, new LoadParameter(item));
                win.Show(this.GetNavigationBar());
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanGoAssetCommand(object parameter)
        {
            return true;
        }


        /// <summary>
        /// 管理类型
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void ManageTypeCommand(object parameter)
        {

            try
            {
                ProductShowItem showItem = parameter as ProductShowItem;
                if (showItem == null)
                    return;
                WinProductType win = new WinProductType();
                LoadParameter.StartParameter(win, new LoadParameter(showItem));
                win.Show(this.GetNavigationBar());
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanManageTypeCommand(object parameter)
        {
            return true;
        }


        /// <summary>
        /// 保存功能
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SaveCommand(object parameter)
        {

            try
            {
                if (UpdateProduct())
                {
                    MessageTip.Show(this.GetWindow(), "保存成功");
                }
                else
                {
                    MessageTip.Show(this.GetWindow(), "保存失败");
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanSaveCommand(object parameter)
        {
            return true;
        }


        /// <summary>
        /// 查看产品名录命令
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void ScanRefTypesCommand  (object parameter)
        {

            try
            {
                var showItem = parameter as RefVenderShowItem;
                if (showItem == null)
                {
                    return;
                }
                WinProductList win = new WinProductList();
                bool isSeller = false;
                if (this.SellerItems != null)
                {
                    isSeller = this.SellerItems.Contains(showItem);
                }

                win.Title = isSeller ? "供应产品名录" : "维修产品名录";
                win.Owner = this.GetWindow();
                LoadParameter.StartParameter(win, new LoadParameter(showItem));
                if (win.ShowDialog() == true)
                {
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanScanRefTypesCommand  (object parameter)
        {
            return true;
        }


        /// <summary>
        /// 刷新动画
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void RefreshCommand(object parameter)
        {

            try
            {
                var item = parameter as ProjectAssetShowItem;
                if (item != null)
                {
                    item.IsLoading = true;
                    TaskUtil.StartSTATask((obj) =>
                    {
                        var useItem = obj as ProjectAssetShowItem;
                        if (useItem == null)
                            return;
                        try
                        {
                            BllFactory<ProjectBll>.Instance.ProjectSync(useItem.ProjectId);
                            Thread.Sleep(3000);//立即执行偶尔导致连接取消
                        var projectAssetItems = BllFactory<ManufacturerBll>.Instance.GetProjectItems(Id);
                            foreach (var dataItem in projectAssetItems)
                            {
                                if (dataItem.Id == useItem.ProjectId)
                                {
                                    useItem.AssetCount = dataItem.TotalCount.ToString();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageTipEx.Show(ex);
                        }

                        finally
                        {

                            useItem.IsLoading = false;
                        }
                    }, item);

                }

            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
           
        }
        public bool CanRefreshCommand(object parameter)
        {
            return true;
        }

        #endregion
        #region 单条修改模块
        public bool UpdateManufacture()
        {

            ManufacturerItem item = new ManufacturerItem();
            item.Id = this.Id;
            item.Name = this.ManufactureName;
            var result = BllFactory<ManufacturerBll>.Instance.Update(item);
            if (!result)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<ManufacturerBll>.Instance.ErrorMessage ?? string.Empty);
            }     
            return result;
        }
        #endregion
        #region 私有方法
        /// <summary>
        /// 加载厂商信息
        /// </summary>
        /// <param name="manufactureId">生产厂商Id</param>
        private void LoadManufactureItem(string manufactureId)
        {
            #region 加载厂商信息
            var manufactureItem = BllFactory<ManufacturerBll>.Instance.GetAllItems().FirstOrDefault(c => c.Id == manufactureId);
            ManufactureName = manufactureItem?.Name;
            #endregion
        }
        /// <summary>
        /// 通过品牌获取产品信息
        /// </summary>
        /// <param name="item"></param>
        private void GetProductsByBranch(BrandShowItem item)
        {
            if (item == null)
                return;
            LoadProdutItems(item.Id);
        }

        /// <summary>
        /// 加载品牌信息
        /// </summary>
        private void LoadBrandItems()
        {
            var brands= BllFactory<BrandBll>.Instance.GetAllItems(Id);
            string oldId = string.Empty;
            if (CurrentSelectedBrand != null)
            {
                oldId = CurrentSelectedBrand.Id;
            }
            Brands = new ObservableCollection<BrandShowItem>();
            foreach (var brandItem in brands)
            {
                Brands.Add(new BrandShowItem() { ManufacturerId= Id, Id = brandItem.Id, Name = brandItem.Name});
            }
            if (string.IsNullOrEmpty(oldId))
            {
                this.CurrentSelectedBrand = Brands.FirstOrDefault();
            }
            else
            {
                this.CurrentSelectedBrand= Brands.FirstOrDefault(b=>b.Id== oldId) ?? Brands.FirstOrDefault();
            }

        }

        /// <summary>
        /// 加载项目资产信息
        /// </summary>
        /// <param name="manufactureId"></param>
        private void LoadProjectAssetItems(string manufactureId)
        {
            #region 资产信息加载
            var projectAssetItems = BllFactory<ManufacturerBll>.Instance.GetProjectItems(manufactureId);
            ProjectAssetItems = new ObservableCollection<ProjectAssetShowItem>();
            foreach (var dataItem in projectAssetItems)
            {
                ProjectAssetItems.Add(new ProjectAssetShowItem() {ProjectId=dataItem.Id, ManufactureId=manufactureId, ProjectLocalName = dataItem.Name, AssetCount = dataItem.TotalCount.ToString()});
            }

            #endregion
        }

        /// <summary>
        /// 获取品牌名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string GetBrandName(string id)
        {
            var brandItem = BllFactory<BrandBll>.Instance.GetItem(Id,id);
            if (brandItem == null)
                return string.Empty;
            return brandItem.Name;
        }

        /// <summary>
        /// 通过品牌获取产品列表
        /// </summary>
        /// <param name="brandId"></param>

        private void LoadProdutItems(string brandId)
        {
            var productItems = BllFactory<ProductBll>.Instance.GetAllItems(brandId);
            List<ProductShowItem> items = new List<ProductShowItem>();
            foreach (var product in productItems)
            {
                ProductShowItem tempItem = new ProductShowItem();
                tempItem.VenderId = Id;
                tempItem.BrandId = brandId;
                tempItem.ProductId = product.Id;
                tempItem.ProductName = product.Name;
                tempItem.ComonError = string.Empty;
                tempItem.OwnerFamily = EquipmentFamilyManager.GetFamilyName(product.FamilyCode);
                tempItem.ContainTypes = product.ProductTypes.Select(p=>p.Name).ToList();
                items.Add(tempItem);
            }
            ProductItems = new ObservableCollection<ProductShowItem>(items);
        }

        /// <summary>
        /// 修改产品信息
        /// </summary>
        /// <returns></returns>

        private bool UpdateProduct()
        {
            var modifyItems = ProductItems.Where(c=>c.IsEdited).ToList();
            bool flag = true;
            foreach (var productShowItem in modifyItems)
            {
                ProductItem item = new ProductItem();
                item.Id = productShowItem.ProductId;
                item.Name = productShowItem.ProductName;
                BllFactory<ProductBll>.Instance.Update(item);
            }
          
            return true;
        }
        /// <summary>
        /// 加载厂商统计信息
        /// </summary>
        /// <param name="venderId"></param>
        private void LoadVenderItems(string venderId)
        {
             var tupleItem=BllFactory<ManufacturerBll>.Instance.GetRefVenderItems(venderId);
            LoadSellerItems(tupleItem.Item1, venderId);
            LoadMaintainerItems(tupleItem.Item2, venderId);
        }

        /// <summary>
        /// 加载供应商商关联信息
        /// </summary>
        /// <param name="items"></param>
        /// <param name="manufacturerId"></param>
        private void LoadSellerItems( List<RefVenderItem> items,string manufacturerId)
        {
            //todo 调用后台api查找相关关联项目
           // List<RefVenderItem> items = new List<RefVenderItem>();
            List<RefVenderShowItem> showItems = new List<RefVenderShowItem>();
            foreach (var refVenderItem in items)
            {
                var showItem = ConvertToShowItem(refVenderItem);
                showItem.ManufacturerId = manufacturerId;
                showItems.Add(showItem);
            }

            SellerItems = new ObservableCollection<RefVenderShowItem>(showItems);
        }
        /// <summary>
        /// 加载维修商关联信息
        /// </summary>
        /// <param name="items"></param>
        /// <param name="venderId"></param>
        public void LoadMaintainerItems(List<RefVenderItem> items,string manufacturerId)
        {
               //todo 调用后台api查找相关关联项目
            //List<RefVenderItem> items = new List<RefVenderItem>();
            List<RefVenderShowItem> showItems = new List<RefVenderShowItem>();
            foreach (var refVenderItem in items)
            {
                var showItem = ConvertToShowItem(refVenderItem);
                showItem.ManufacturerId = manufacturerId;
                showItems.Add(showItem);
            }

            MaintainerItems = new ObservableCollection<RefVenderShowItem>(showItems);
        }


        private RefVenderShowItem ConvertToShowItem(RefVenderItem item)
        {
            RefVenderShowItem showItem = new RefVenderShowItem();
            showItem.RefVenderId = item.Id;
            showItem.VenderName = item.Name;
            showItem.WebSite = item.WebSite;
            showItem.ProductCount = item.RefProductCount;
            showItem.BrandCount = item.RefBrandCount;
            showItem.ProductTypes = item.RefProductTypeIds ?? new List<string>();
            return showItem;
        }

        #endregion
    }

    /// <summary>
    /// 项目显示信息类
    /// </summary>
    public class ProjectAssetShowItem :BasePropertyChanged
    {
        /// <summary>
        /// 关联生产厂商Id
        /// </summary>
        public string ManufactureId { get; set; }

        private string m_ProjectId;
        /// <summary>
        /// 项目Id
        /// </summary>
        public string ProjectId
        {
            get { return this.m_ProjectId; }
            set
            {
                this.m_ProjectId = value;
                RaisePropertyChanged(() => this.ProjectId);
            }
        }

        private string m_ProjectLocalName;
        /// <summary>
        /// 项目本地名称
        /// </summary>
        public string ProjectLocalName
        {
            get { return this.m_ProjectLocalName; }
            set
            {
                this.m_ProjectLocalName = value;
                RaisePropertyChanged(() => this.ProjectLocalName);
            }
        }


        private string m_AssetCount;
        /// <summary>
        /// 资产数量[只是显示，字符串就行了，没必要写成数字]
        /// </summary>
        public string AssetCount
        {
            get { return this.m_AssetCount; }
            set
            {
                this.m_AssetCount = value;
                RaisePropertyChanged(() => this.AssetCount);
            }
        }


        private bool m_IsLoading;
        /// <summary>
        /// 是否在加载
        /// </summary>
        public bool IsLoading
        {
            get { return this.m_IsLoading; }
            set
            {
                this.m_IsLoading = value;
                RaisePropertyChanged(nameof(this.IsLoading));
            }
        }
    }
}
