
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmMaintainerInfo.cs
//文件描述: 维修商信息
//创 建 者: xls
//创建日期: 2018/5/24 22:07:12
//版 本 号：1.0.0.0
////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Com.FirmLib.Bll;
using Com.FirmLib.Entity;
using Com.FirmLib.UI.Common;
using Com.FirmLib.UI.Maintainer.Mode;
using FWindSoft.Data;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Tools;
using FWindSoft.Wpf;

namespace Com.FirmLib.UI.Maintainer
{
    public class VmMaintainerInfo : BaseViewModel
    {
        #region 初始化
        public VmMaintainerInfo()
        {
            Init();
        }
        private void Init()
        {
        }
        public void Init(LoadParameter parameter)
        {
            //获取到了维修厂商Id
            Id = parameter.Parameter as string;
            LoadVenderItem(Id);
            LoadProjectAssetItems(Id);
            LoadProductTypeItems(Id);
        } 
        #endregion

        #region 属性相关

        public string Id { get; protected set; }

        private string m_Name;
        /// <summary>
        /// 厂家名称
        /// </summary>
        public string Name
        {
            get { return this.m_Name; }
            set
            {
                this.m_Name = value;
                RaisePropertyChanged(() => this.Name);
            }
        }

        private string m_Url;
        /// <summary>
        /// 厂家url
        /// </summary>
        public string Url
        {
            get { return this.m_Url; }
            set
            {
                this.m_Url = value;
                RaisePropertyChanged(() => this.Url);
            }
        }


        private ObservableCollection<ProjectMaintainerAssetItem> m_ProjectAssetItems;
        /// <summary>
        /// 项目资产条目
        /// </summary>
        public ObservableCollection<ProjectMaintainerAssetItem> ProjectAssetItems
        {
            get { return this.m_ProjectAssetItems; }
            set
            {
                this.m_ProjectAssetItems = value;
                RaisePropertyChanged(() => this.ProjectAssetItems);
            }
        }
        #endregion
        #region 维护产品组相关
        private TreeNavigation<BasePropertyChanged> m_Root;
        /// <summary>
        /// 根元素
        /// </summary>
        public TreeNavigation<BasePropertyChanged> Root
        {
            get { return this.m_Root; }
            set
            {
                this.m_Root = value;
                RaisePropertyChanged(nameof(this.Root));
            }
        }

        /// <summary>
        /// 当前显示品牌集合
        /// </summary>
        public TNodeCollection<TreeNavigationItem<BasePropertyChanged>> Brands
        {
            get { return Root.CurrentItem.Nodes; }
        }
        #endregion
        #region 命令相关

        /// <summary>
        /// 添加项目资产
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddProjectAsset(object parameter)
        {

            try
            {
                WinMaintainerProjectAsset win = new WinMaintainerProjectAsset();
                LoadParameter.StartParameter(win, new LoadParameter(Id));
                win.Show(this.GetNavigationBar());
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanAddContract(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 进入项目信息
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void GoToProject(object parameter)
        {

            try
            {
                var item = parameter as ProjectMaintainerAssetItem;
                WinManitainerProjectInfo win = new WinManitainerProjectInfo();
                var p = new MaintainerParameter();
                p.Project.Id = item.ProjectId;
                p.Maintainer.Id = Id;
                LoadParameter.StartParameter(win, new LoadParameter(p));
                win.Show(this.GetNavigationBar());
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanGoToProject(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 保存功能
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SaveCommand(object parameter)
        {
            MessageTip.Show(this.GetWindow(), "保存");
        }
        public bool CanSaveCommand(object parameter)
        {
            return true;
        }
        #endregion

        #region 维护设备族相关命令

        /// <summary>
        /// 增加维护型号
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddProductTypeCommand(object parameter)
        {

            try
            {
                WinAddProductType win = new WinAddProductType();
                win.Owner = this.GetWindow();
                LoadParameter.StartParameter(win, new LoadParameter(Id));
                if (win.ShowDialog() == true)
                {
                    ///todo 是不是要刷新，因为可能连续添加;
                    LoadProductTypeItems(Id);
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanAddProductTypeCommand(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 删除型号命令
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void DeleteCommand(object parameter)
        {

            try
            {
                TreeNavigationItem<BasePropertyChanged> item = parameter as TreeNavigationItem<BasePropertyChanged>;
                if (item == null)
                    return;
                BrandInfoShowItem showItem = item.RefItem as BrandInfoShowItem;
                if (showItem == null)
                    return;
                var result = MessageTip.Show(this.GetWindow(), "是否要删除", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    var flag = DeleteItem(Id, showItem.ProductTypes.Select(p => p.Id).ToList());
                    if (flag)
                    {
                        if (Brands != null)
                        {
                            if (DataSource != null)
                            {
                                DataSource.RemoveAll(p => showItem.ProductTypes.Any(s => s.Id == p.ProductTypeId));
                            }
                            Brands.Remove(item);
                        }
                    }
                    else
                    {
                        MessageTip.Show(this.GetWindow(), BllFactory<ProductDirectoryBll>.Instance.ErrorMessage, "失败");
                    }

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


        /// <summary>
        /// 查看型号
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void ScanProductTypeCommand(object parameter)
        {

            try
            {
                BrandInfoShowItem showItem = (parameter as TreeNavigationItem<BasePropertyChanged>)?.RefItem as BrandInfoShowItem;
                if (showItem == null)
                    return;
                WinUpdateProductType win = new WinUpdateProductType();
                win.Title = "查看维修型号";
                win.Owner = this.GetWindow();
                EditParameter pa = new EditParameter(Id, showItem.BrandId);
                LoadParameter.StartParameter(win, new LoadParameter(pa));
                if (win.ShowDialog() == true)
                {
                    LoadProductTypeItems(Id);
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanScanProductTypeCommand(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 编辑型号
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void EditProductTypeCommand(object parameter)
        {

            try
            {
                BrandInfoShowItem showItem = (parameter as TreeNavigationItem<BasePropertyChanged>)?.RefItem as BrandInfoShowItem;
                if (showItem == null)
                    return;
                WinUpdateProductType win = new WinUpdateProductType();
                win.Title = "编辑维修型号";
                win.Owner = this.GetWindow();
                EditParameter pa = new EditParameter(Id, showItem.BrandId) { IsEdit = true };
                LoadParameter.StartParameter(win, new LoadParameter(pa));
                if (win.ShowDialog() == true)
                {
                    LoadProductTypeItems(Id);
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }

        }
        public bool CanEditProductTypeCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 刷新动画
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void RefreshCommand(object parameter)
        {

            try
            {
                var item = parameter as ProjectMaintainerAssetItem;
                if (item != null)
                {
                    item.IsLoading = true;
                    TaskUtil.StartSTATask((obj) =>
                   {
                       var useItem = obj as ProjectMaintainerAssetItem;
                       if (useItem == null)
                           return;
                       try
                       {
                           BllFactory<ProjectBll>.Instance.ProjectSync(useItem.ProjectId);
                           Thread.Sleep(3000);//立即执行偶尔导致连接取消
                      var projects = BllFactory<MaintainerBll>.Instance.GetProjectItems(Id);
                           foreach (var project in projects)
                           {
                               if (project.Id == useItem.ProjectId)
                               {
                                   useItem.ValidityAssetCount = project.TotalCount;
                                   useItem.NearOutDateAssetCount = project.NearlyExpireCount;
                               }
                           }
                       }
                       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 公开方法
        /// <summary>
        /// 更新指定字段信息
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public bool SingleUpdateVenderItem(string field)
        {

            MaintainerItem item = new MaintainerItem();
            item.Id = this.Id;
            SetFieldValue(item, field);
            var result = BllFactory<MaintainerBll>.Instance.Update(item);
            if (!result)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<MaintainerBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        }

        private void SetFieldValue(MaintainerItem item, string field)
        {
            if (field == "Name")
            {
                item.Name = this.Name;
                return;
            }
            if (field == "Url")
            {
                item.Website = this.Url;
                return;
            }

        }
        #endregion
        #region 私有方法
        /// <summary>
        /// 加载厂商信息
        /// </summary>
        /// <param name="venderId">厂商Id</param>
        private void LoadVenderItem(string venderId)
        {
            #region 加载厂商信息
            var venderItem = BllFactory<MaintainerBll>.Instance.GetAllItems().FirstOrDefault(c => c.Id == venderId);
            Name = venderItem.Name;
            Url = venderItem.Website;
            #endregion
        }
        /// <summary>
        /// 加载项目数据
        /// </summary>
        /// <param name="venderId"></param>
        private void LoadProjectAssetItems(string venderId)
        {
            ProjectAssetItems = new ObservableCollection<ProjectMaintainerAssetItem>();
            var projects = BllFactory<MaintainerBll>.Instance.GetProjectItems(venderId);
            foreach (var project in projects)
            {
                var item=new  ProjectMaintainerAssetItem() {ProjectId = project.Id, ProjectLocalName = project.Name};
                item.ValidityAssetCount = project.TotalCount;
                item.NearOutDateAssetCount = project.NearlyExpireCount;
                ProjectAssetItems.Add(item);
            }
        }
        private void LoadProductTypeItems(string venderId)
        {
            Root = new TreeNavigation<BasePropertyChanged>();
            Root.CurrentItemChanged = ChangeSelectedItem;
            Root.Items.AddRange(GetFamilys(venderId, new ProdcutTypeCondition()));
            Root.CurrentItem = Root.Items.FirstOrDefault();
        }
        /// <summary>
        /// 删除指定厂商下的品牌信息
        /// </summary>
        /// <param name="venderId"></param>
        /// <param name="productTypeIds"></param>
        private bool DeleteItem(string venderId, List<string> productTypeIds)
        {
           return BllFactory<ProductDirectoryBll>.Instance.Delete(venderId, new List<string>(productTypeIds));
        }
        #endregion

        #region 关联型号相关
        private void ChangeSelectedItem(TreeNavigationItem<BasePropertyChanged> item)
        {
            if (item == null)
                return;
            if (item.Level > 1)
                return;
            item.Nodes.Clear();
            if (item.Level == 1)
            {
                ShowDataItem showItem = item.RefItem as ShowDataItem;
                ProdcutTypeCondition condition = new ProdcutTypeCondition();
                condition.FamilyCode = showItem?.Id;
                item.Nodes.AddRange(GetBrands(condition));
            }         
            item.CurrentItem = item.Nodes.FirstOrDefault();
        }
        /// <summary>
        /// 产品信息数据源
        /// </summary>
        private List<ProductTypeDetailItem> DataSource { get; set; }
        private List<TreeNavigationItem<BasePropertyChanged>> GetFamilys(string maintainerId,ProdcutTypeCondition condition)
        {
            List<TreeNavigationItem<BasePropertyChanged>> results = new List<TreeNavigationItem<BasePropertyChanged>>();
            DataSource = BllFactory<ProductDirectoryBll>.Instance.GetAllItems(maintainerId) ?? new List<ProductTypeDetailItem>();
            var familys = ProductTypeManager.GetFamilys(new ProdcutTypeCondition(DataSource));
            if (familys.Count > 1)
            {
                //当关联设备族大于一个时，才显示全部选项
                results.Add(new TreeNavigationItem<BasePropertyChanged>() { RefItem = new ShowDataItem() { Name = "全部", FamilyCode = "All", Id = "All" } });
            }
           
            familys.ForEach(f => results.Add(new TreeNavigationItem<BasePropertyChanged>() { RefItem = f }));
            return results;
        }
        private List<TreeNavigationItem<BasePropertyChanged>> GetBrands(ProdcutTypeCondition condition)
        {
            List<TreeNavigationItem<BasePropertyChanged>> results = new List<TreeNavigationItem<BasePropertyChanged>>();
            var useDataSource = DataSource;
            if (condition.FamilyCode != "All")
            {
                useDataSource = DataSource.Where(p => p.FamilyCode == condition.FamilyCode).ToList();
            }
            List<BrandInfoShowItem> brands = new List<BrandInfoShowItem>();
            var comparer = new TComparer<ShowDataItem>((s1, s2) => s1.Id == s2.Id);
            var group1 = useDataSource.GroupBy(c => new ShowDataItem() { Id = c.BrandId, Name = c.BrandName, FamilyCode = c.FamilyCode }, comparer);
            foreach (var groupItem1 in group1)
            {
                BrandInfoShowItem brand = new BrandInfoShowItem();
                brand.FamilyCode = groupItem1.Key.FamilyCode;
                brand.BrandId = groupItem1.Key.Id;
                brand.BrandName = groupItem1.Key.Name;
                var group2 = groupItem1.GroupBy(c => new ShowDataItem() { Id = c.ProductId, Name = c.ProductName, FamilyCode = c.FamilyCode }, comparer);
                foreach (var groupItem2 in group2)
                {
                    #region 增加产品
                    ShowDataItem showItem = new ShowDataItem();
                    showItem.Id = groupItem2.Key.Id;
                    showItem.Name = groupItem2.Key.Name;
                    brand.Products.Add(showItem);
                    #endregion
                    #region 增加产品型号
                    brand.ProductTypes.AddRange(groupItem2.Select(p => new ShowDataItem() { Id = p.ProductTypeId, Name = p.ProductTypeName }));
                    #endregion
                }
                brands.Add(brand);
            }
            brands.ForEach(b => results.Add(new TreeNavigationItem<BasePropertyChanged>() { RefItem = b }));
            return results;
        }
    
        #endregion
    }

    #region 前台显示类
    /// <summary>
    /// 项目维修资产
    /// </summary>
    public class ProjectMaintainerAssetItem : BasePropertyChanged
    {
        public string ProjectId { get; set; }

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


        private int m_ValidityAssetCount;
        /// <summary>
        /// 有效期内的资产
        /// </summary>
        public int ValidityAssetCount
        {
            get { return this.m_ValidityAssetCount; }
            set
            {
                this.m_ValidityAssetCount = value;
                RaisePropertyChanged(() => this.ValidityAssetCount);
            }
        }


        private int m_NearOutDateAssetCount;
        /// <summary>
        /// 即将超期资产
        /// </summary>
        public int NearOutDateAssetCount
        {
            get { return this.m_NearOutDateAssetCount; }
            set
            {
                this.m_NearOutDateAssetCount = value;
                RaisePropertyChanged(() => this.NearOutDateAssetCount);
            }
        }


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

    }

    /// <summary>
    /// 品牌信息显示
    /// </summary>
    public class BrandInfoShowItem : BasePropertyChanged
    {
        public BrandInfoShowItem()
        {
            Products = new List<ShowDataItem>();
            ProductTypes = new List<ShowDataItem>();
        }
        /// <summary>
        /// 种族名称
        /// </summary>
        public string FamilyName { get; set; }
        /// <summary>
        /// 种族编码
        /// </summary>
        public string FamilyCode { get; set; }
        /// <summary>
        /// 品牌Id
        /// </summary>
        public string BrandId { get; set; }
        private string m_BrandName;
        /// <summary>
        /// 品牌名称
        /// </summary>
        public string BrandName
        {
            get { return this.m_BrandName; }
            set
            {
                this.m_BrandName= value;
                RaisePropertyChanged(() => this.BrandName);
            }
        }

        private List<ShowDataItem> m_Products;
        /// <summary>
        /// 产品名称
        /// </summary>
        public List<ShowDataItem> Products
        {
            get { return this.m_Products; }
            set
            {
                this.m_Products = value;
                RaisePropertyChanged(() => this.Products);
            }
        }


        private List<ShowDataItem> m_ProductTypes;
        /// <summary>
        /// 产品类型名称
        /// </summary>
        public List<ShowDataItem> ProductTypes
        {
            get { return this.m_ProductTypes; }
            set
            {
                this.m_ProductTypes = value;
                RaisePropertyChanged(() => this.ProductTypes);
            }
        }
    }
    #endregion
}
