
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmSupplyAssetSelecter.cs
//文件描述: VmSupplyAssetSelecter.cs
//创 建 者: xls
//创建日期: 2018/9/12 22:33:38
//版 本 号：1.0.0.0
////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Com.FirmLib.Bll;
using Com.FirmLib.UI.BllCommon;
using Com.FirmLib.UI.Common.Model;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Wpf;

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

        private void Init()
        {
            SelectedAssetItems = new List<AssetShowItem>();
            ExistAssets = new List<string>();
            //InitSelector();
        }
        public void Init(LoadParameter parameter)
        {
            SelectAssetContext context = parameter.Parameter as SelectAssetContext;
            if (context == null)
                return;          
            Context = context;
            ProjectId = context.ProjectId;
            VenderId = context.VenderId;
            VenderName = BllFactory<SellerBll>.Instance.GetItem(context.VenderId)?.Name ?? string.Empty;
            ExistAssets = new List<string>(context.ContainIds);
            InitSelector();
            CalcCheckedCount();
        }
        #region 属性相关  
        private string VenderName { get; set; }
        /// <summary>
        /// 厂商id
        /// </summary>
        public string VenderId { get; set; }
        /// <summary>
        /// 项目Id
        /// </summary>
        private string ProjectId { get; set; }
        /// <summary>
        /// 存在资产信息
        /// </summary>
        private List<string> ExistAssets { get; set; }
        private SelectAssetContext Context { get; set; }
        /// <summary>
        /// 当前保单中选中资产
        /// </summary>
        public List<AssetShowItem> SelectedAssetItems { get; set; }

        private ObservableCollection<AssetShowItem> m_RecommendAssetItems;
        /// <summary>
        /// 推荐资产
        /// </summary>
        public ObservableCollection<AssetShowItem> RecommendAssetItems
        {
            get { return this.m_RecommendAssetItems; }
            set
            {
                this.m_RecommendAssetItems = value;
                RaisePropertyChanged(nameof(this.RecommendAssetItems));
            }
        }


        private ObservableCollection<AssetShowItem> m_AllAssetItems;
        /// <summary>
        /// 全部资产
        /// </summary>
        public ObservableCollection<AssetShowItem> AllAssetItems
        {
            get { return this.m_AllAssetItems; }
            set
            {
                this.m_AllAssetItems = value;
                RaisePropertyChanged(nameof(this.AllAssetItems));
            }
        }


        private string m_SelectedAssetCount;
        /// <summary>
        /// 选中资产数量
        /// </summary>
        public string SelectedAssetCount
        {
            get { return this.m_SelectedAssetCount; }
            set
            {
                this.m_SelectedAssetCount = value;
                RaisePropertyChanged(nameof(this.SelectedAssetCount));
            }
        }

        #endregion

        #region 命令相关

        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void EnsureCommand(object parameter)
        {
            try
            {
                if (Context != null)
                {
                    Context.AddedItems.AddRange(SelectedAssetItems);
                }
                Window win = parameter as Window;
                if (win != null)
                {
                    win.DialogResult = true;
                }

            }
            catch (Exception ex)
            {

               MessageTipEx.Show(ex);
            }
        }
        public bool CanEnsureCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 选择资产变化
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SelectedAssetChanged(object parameter)
        {
            try
            {
                AssetShowItem item = parameter as AssetShowItem;
                if (item == null)
                    return;
                var currentItem = this.SelectedAssetItems.FirstOrDefault(c => c.Id == item.Id);
                bool isChecked = item.IsChecked;
                if (isChecked && currentItem == null)
                {
                    this.SelectedAssetItems.Add(item);
                }
                else if (!isChecked && currentItem != null)
                {
                    //this.SelectedAssetItems.RemoveAll(c => c.AssetNo == currentItem.AssetNo);
                    this.SelectedAssetItems.Remove(currentItem);
                }
                CalcCheckedCount();
            }
            catch (Exception ex)
            {

               MessageTipEx.Show(ex);
            }

        }
        public bool CanSelectedAssetChanged(object parameter)
        {
            AssetShowItem item = parameter as AssetShowItem;
            if (item == null)
                return false;
            return item.IsEnabled;
        }


        /// <summary>
        /// tab切换按钮【联动两边选中项】
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void TabChangedCommand(object parameter)
        {
            try
            {
                //子控件，包含相同的事件也会触发
                int index = Convert.ToInt32(parameter);
                var useCollection = index == 0 ? RecommendAssetItems : AllAssetItems;
                if (useCollection == null)
                    return;
                foreach (var item in useCollection)
                {
                    item.IsChecked = ExistAssetId(item.Id);
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanTabChangedCommand(object parameter)
        {
            return true;
        }

        #endregion

        #region 私有方法
        private void CalcCheckedCount()
        {
            this.SelectedAssetCount = (ExistAssets.Count + this.SelectedAssetItems.Count).ToString();
        }
        private bool ExistAssetId(string id)
        {
            return this.SelectedAssetItems.Any(asset => asset.Id == id);
        }
        private bool ExistInOrigin(string id)
        {
            return this.ExistAssets.Any(originId => originId == id);
        }
        private void InitSelector()
        {
            RecommendAssetSelecter = new AssetSelector();
            AllAssetSelecter = new AssetSelector();
            RecommendAssetSelecter.Refresh = (selector) =>
            {
                LoadRecommendAssets(selector, ProjectId, VenderId);
            };
            AllAssetSelecter.Refresh = (selector) =>
            {
                LoadAllAssets(selector, ProjectId, string.Empty);
            };
            RecommendAssetSelecter.FilterControl.Refresh();
            AllAssetSelecter.FilterControl.Refresh();
        }
        private void LoadRecommendAssets(AssetSelector selector, string projectId, string venderId)
        {
            string prefix = selector.FilterControl.FilterSetting["LocalName"].ToString();
            int startIndex = Math.Max((selector.CurrentPageIndex - 1), 0) * AssetManager.PerPageCount;
            var venderItem = VenderItem.CreateSupplierItem(VenderName);
            venderItem.Id = venderId;
            SearchResultList<AssetShowItem> items = AssetManager.GetRecommendShowItems(projectId, prefix, startIndex,venderItem); ;
            foreach (var item in items)
            {
                item.IsChecked = ExistInOrigin(item.Id);
                if (item.IsChecked)
                {
                    item.IsEnabled = false;
                }
                else
                {
                    item.IsChecked = ExistAssetId(item.Id);
                }
            }

            selector.PageCount = CommomUtils.CalcPageCount(items.TotalCount, AssetManager.PerPageCount);
            RecommendAssetItems = new ObservableCollection<AssetShowItem>(items);
        }
        private void LoadAllAssets(AssetSelector selector, string projectId, string venderId)
        {
            string prefix = selector.FilterControl.FilterSetting["LocalName"].ToString();

            int startIndex = Math.Max((selector.CurrentPageIndex - 1), 0) * AssetManager.PerPageCount;
            SearchResultList<AssetShowItem> items = AssetManager.GetShowItems(projectId, prefix, startIndex); ;
            foreach (var item in items)
            {
                item.IsChecked = ExistInOrigin(item.Id);
                if (item.IsChecked)
                {
                    item.IsEnabled = false;
                }
                else
                {
                    item.IsChecked = ExistAssetId(item.Id);
                }
            }
            selector.PageCount =CommomUtils.CalcPageCount(items.TotalCount,AssetManager.PerPageCount) ;        
            AllAssetItems = new ObservableCollection<AssetShowItem>(items);
        }
        #endregion

        #region 推荐资产 列表相关
        private AssetSelector m_RecommendAssetSelecter;
        /// <summary>
        /// 推荐资产
        /// </summary>
        public AssetSelector RecommendAssetSelecter
        {
            get { return this.m_RecommendAssetSelecter; }
            private set
            {
                this.m_RecommendAssetSelecter = value;
                RaisePropertyChanged(nameof(this.RecommendAssetSelecter));
            }
        }
        #endregion

        #region 全部资产列表相关
        private AssetSelector m_AllAssetSelecterr;
        /// <summary>
        /// 全部资产选择器
        /// </summary>
        public AssetSelector AllAssetSelecter
        {
            get { return this.m_AllAssetSelecterr; }
            private set
            {
                this.m_AllAssetSelecterr = value;
                RaisePropertyChanged(nameof(this.AllAssetSelecter));
            }
        }
        #endregion
    }
}
