
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmSeller.cs
//文件描述: 供应商相关信息
//创 建 者: xls
//创建日期: 2018/5/24 21:14:59
//版 本 号：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;
using Com.FirmLib.UI.Manufacturer.Model;
using Com.FirmLib.UI.Seller.Model;
using FWindSoft.Data;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Tools;
using FWindSoft.Wpf;

namespace Com.FirmLib.UI.Seller
{
    public class VmSellerInfo : BaseViewModel
    {
        public VmSellerInfo()
        {
            Init();
        }

        private void Init()
        {       
            Root = new TreeNavigation<BasePropertyChanged>();
        }

        public void Init(LoadParameter parameter)
        {
            Id = parameter.Parameter as string;
            LoadVenderItem(Id);
            LoadProjectRelationItems(Id);
            LoadBrandItems(Id);
        }
        #region 属性相关
        /// <summary>
        /// 供应商ID
        /// </summary>
        public string Id { get; private 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>
        /// 供应商网址
        /// </summary>
        public string Url
        {
            get { return this.m_Url; }
            set
            {
                this.m_Url = value;
                RaisePropertyChanged(() => this.Url);
            }
        }
        private ObservableCollection<ProjectRelationShowItem> m_ProjectItems;
        /// <summary>
        /// 关联项目信息
        /// </summary>
        public ObservableCollection<ProjectRelationShowItem> ProjectItems
        {
            get { return this.m_ProjectItems; }
            set
            {
                this.m_ProjectItems = value;
                RaisePropertyChanged(() => this.ProjectItems);
            }
        }

        #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 ShowDataItem CurrentBrand
        {
            get { return Root.CurrentItem.RefItem as ShowDataItem; }
        }
        /// <summary>
        /// 当前选中产品
        /// </summary>
        public ShowDataItem CurrentProduct
        {
            get { return Root.CurrentItem.CurrentItem.RefItem as ShowDataItem; }
        }
        /// <summary>
        /// 当前选中产品
        /// </summary>
        public TNodeCollection<TreeNavigationItem<BasePropertyChanged>> ProductTypes
        {
            get { return Root.CurrentItem.CurrentItem.Nodes; }
        }
        #endregion

        #region 命令相关
        /// <summary>
        /// 添加合同
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddContract(object parameter)
        {

            try
            {
                WinSellerProjectContract win = new WinSellerProjectContract();
                LoadParameter.StartParameter(win, new LoadParameter(new VenderProjectParameter(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
            {
                ProjectRelationShowItem item = parameter as ProjectRelationShowItem;
                if (item == null)
                    return;
                WinSellerProjectInfo win = new WinSellerProjectInfo();
                var p = new SellerParameter();
                p.Project.Id = item.ProjectId;
                p.Seller.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;
        }
        /// <summary>
        /// 添加供应型号
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddProductTypeCommand(object parameter)
        {

            try
            {
                //抽象成树形结构，去维护现在的层级数据
                WinMultiProductTypeSelector win = new WinMultiProductTypeSelector();
                win.Owner = this.GetWindow();
                LoadParameter.StartParameter(win, new LoadParameter(Id));
                if (win.ShowDialog() == true)
                {
                    ///todo 是不是要刷新，因为可能连续添加;
                    //局部刷新
                    LoadBrandItems(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;
                var result = MessageTip.Show(this.GetWindow(), "是否要删除", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    var typeShow = item.RefItem as TypeShowItem;
                    bool flag = false;
                    if (typeShow != null)
                    {
                        flag = DeleteItem(Id, typeShow.ProductTypeId);
                    }
                    if (flag && ProductTypes != null)
                    {
                        ProductTypes.Remove(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanDeleteCommand(object parameter)
        {
            return true;
        }

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

            try
            {
                var item = parameter as ProjectRelationShowItem;
                if (item != null)
                {
                    item.IsLoading = true;
                    TaskUtil.StartSTATask((obj) =>
                   {
                       var useItem = obj as ProjectRelationShowItem;
                       if (useItem == null)
                           return;
                       try
                       {
                           BllFactory<ProjectBll>.Instance.ProjectSync(useItem.ProjectId);
                           Thread.Sleep(3000);//立即执行偶尔导致连接取消
                       var projects = BllFactory<SellerBll>.Instance.GetProjectItems(Id);
                           foreach (var project in projects)
                           {
                               if (project.Id == useItem.ProjectId)
                               {
                                   useItem.ContractCount = project.ContractCount;
                                   useItem.AssetCount = project.TotalCount;
                               }
                           }
                       }
                       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)
        {

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

        private void SetFieldValue(SellerItem 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<SellerBll>.Instance.GetAllItems().FirstOrDefault(c => c.Id == venderId);
            Name = venderItem.Name;
            Url = venderItem.Website;
            #endregion
        }
        /// <summary>
        /// 加载项目信息
        /// </summary>
        /// <param name="venderId"></param>
        private void LoadProjectRelationItems(string venderId)
        {
            ProjectItems = new ObservableCollection<ProjectRelationShowItem>();
            var projects = BllFactory<SellerBll>.Instance.GetProjectItems(venderId);
            foreach (var project in projects)
            {
                var projectShowItem = new ProjectRelationShowItem();
                projectShowItem.ProjectId = project.Id;
                projectShowItem.ProjectLocalName = project.Name;
                projectShowItem.ContractCount = project.ContractCount;
                projectShowItem.AssetCount = project.TotalCount;
                ProjectItems.Add(projectShowItem);
            }
        }

        /// <summary>
        /// 加载品牌信息
        /// </summary>
        /// <param name="venderId"></param>
        private void LoadBrandItems(string venderId)
        {
            Root = new TreeNavigation<BasePropertyChanged>();
            Root.CurrentItemChanged = ChangeSelectedItem;
            Root.Items.AddRange(GetBrands(venderId));
            Root.CurrentItem = Root.Items.FirstOrDefault();
        }
        /// <summary>
        /// 删除厂商的类型
        /// </summary>
        /// <param name="venderId"></param>
        /// <param name="typeId"></param>
        private bool DeleteItem(string venderId, string typeId)
        {
            //调用api删除
            var flag= BllFactory<ProductDirectoryBll>.Instance.Delete(venderId, new List<string>() { typeId });
            if (!flag)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<ProductDirectoryBll>.Instance.ErrorMessage);
            }
            return flag;
        }
        /// <summary>
        /// 加载供应厂商的供应产品信息
        /// </summary>
        /// <param name="venderId"></param>
        private List<ProductTypeDetailItem> LoadProductTypeItems(string venderId)
        {
            List<ProductTypeDetailItem> results = new List<ProductTypeDetailItem>();
            results = BllFactory<ProductDirectoryBll>.Instance.GetAllItems(venderId);
            return results;
        }
        #endregion

        #region 关联型号相关
        private void ChangeSelectedItem(TreeNavigationItem<BasePropertyChanged> item)
        {
            if (item == null)
                return;
            if (item.Level > 2)
                return;
            item.Nodes.Clear();
            if (item.Level == 1)
            {
                item.Nodes.AddRange(GetProducts(item.RefItem));
            }
            else if (item.Level == 2)
            {
                item.Nodes.AddRange(GetProductTypes(item.RefItem));
            }
            item.CurrentItem = item.Nodes.FirstOrDefault();
        }
        /// <summary>
        /// 产品信息数据源
        /// </summary>
        private List<ProductTypeDetailItem> DataSource { get; set; }
        /// <summary>
        /// 获取品牌信息
        /// </summary>
        /// <param name="venderId"></param>
        /// <returns></returns>
        private List<TreeNavigationItem<BasePropertyChanged>> GetBrands(string venderId)
        {
            List<TreeNavigationItem<BasePropertyChanged>> results = new List<TreeNavigationItem<BasePropertyChanged>>();
            DataSource = LoadProductTypeItems(venderId) ?? new List<ProductTypeDetailItem>();
            var brands = ProductTypeManager.GetBrands(new ProdcutTypeCondition(DataSource));
            brands.ForEach(b => results.Add(new TreeNavigationItem<BasePropertyChanged>() { RefItem = b }));
            return results;
        }
        /// <summary>
        /// 获取产品信息
        /// </summary>
        /// <param name="brandShowData"></param>
        /// <returns></returns>
        private List<TreeNavigationItem<BasePropertyChanged>> GetProducts( BasePropertyChanged brandShowData)
        {
            List<TreeNavigationItem<BasePropertyChanged>> results = new List<TreeNavigationItem<BasePropertyChanged>>();
            if (DataSource == null)
                return results;
            var showData = brandShowData as ShowDataItem;
            if (showData == null)
                return results;
            var products = ProductTypeManager.GetProducts(new ProdcutTypeCondition(DataSource) { BrandId = showData.Id });
            products.ForEach(p => results.Add(new TreeNavigationItem<BasePropertyChanged>() { RefItem = p }));
            return results;
        }
        /// <summary>
        /// 获取商品信息
        /// </summary>
        /// <param name="prodcutShowData"></param>
        /// <returns></returns>
        private List<TreeNavigationItem<BasePropertyChanged>> GetProductTypes(BasePropertyChanged prodcutShowData)
        {
            List<TreeNavigationItem<BasePropertyChanged>> results = new List<TreeNavigationItem<BasePropertyChanged>>();
            if (DataSource == null)
                return results;
            var showData = prodcutShowData as ShowDataItem;
            if (showData == null)
                return results;
            //过滤掉不不是该厂家维护的信息
            var typeIds = DataSource.Select(p => p.ProductTypeId).ToList();
            var typeItems = ProductTypeManager.GetProdcutTypeInfoItems(new ProdcutTypeCondition() {ProductId = showData.Id, FamilyCode = showData.FamilyCode });
            typeItems.ForEach(p =>
           {
               if (typeIds.Contains(p.ProductTypeId))
               {
                   results.Add(new TreeNavigationItem<BasePropertyChanged>() { RefItem = p });
               }
           });
            return results;
        }
    }
    #endregion

    /// <summary>
    /// 项目关联信息
    /// </summary>
    public class ProjectRelationShowItem : BasePropertyChanged
    {
        /// <summary>
        /// 项目Id
        /// </summary>
        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_ContractCount;
        /// <summary>
        /// 涉及合同数量
        /// </summary>
        public int ContractCount
        {
            get { return this.m_ContractCount; }
            set
            {
                this.m_ContractCount = value;
                RaisePropertyChanged(() => this.ContractCount);
            }
        }

        private int m_AssetCount;
        /// <summary>
        /// 资产数量
        /// </summary>
        public int 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));
            }
        }
    }
}
