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

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

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

        private void Init()
        {
            AssetItems = new ObservableCollection<AssetShowItem>() {  };
            this.AssetCount = 1;
            this.Price = 1000;
            this.MaintenancePeriod = 3;

        }
        public void Init(LoadParameter parameter)
        {
            SelectAssetContext context = parameter.Parameter as SelectAssetContext;
            if (context == null)
                return;
            Context = context;
        }
        SelectAssetContext Context { get; set; }
        #region 属性相关

        private int m_AssetCount;
        /// <summary>
        /// 资产数量
        /// </summary>
        public int AssetCount
        {
            get { return this.m_AssetCount; }
            set
            {
                this.m_AssetCount = value;
                RaisePropertyChanged(nameof(this.AssetCount));
                //更新资产
                UpdateAssetItems();
            }
        }

        private double m_Price;
        /// <summary>
        /// 采购价格
        /// </summary>
        public double Price
        {
            get { return this.m_Price; }
            set
            {
                this.m_Price = value;
                RaisePropertyChanged(nameof(this.Price));
            }
        }


        private double m_MaintenancePeriod;
        /// <summary>
        /// 保修期
        /// </summary>
        public double MaintenancePeriod
        {
            get { return this.m_MaintenancePeriod; }
            set
            {
                this.m_MaintenancePeriod = value;
                RaisePropertyChanged(nameof(this.MaintenancePeriod));
            }
        }


        private ProductTypeShowItem m_CurrentProductType;
        /// <summary>
        /// 当前选中类型
        /// </summary>
        public ProductTypeShowItem CurrentProductType
        {
            get { return this.m_CurrentProductType; }
            set
            {
                this.m_CurrentProductType = value;
                AttachLocalName(value);
                RaisePropertyChanged(nameof(this.CurrentProductType));
            }
        }



        private ObservableCollection<AssetShowItem> m_AssetItems;
        /// <summary>
        /// 创建资产
        /// </summary>
        public ObservableCollection<AssetShowItem> AssetItems
        {
            get { return this.m_AssetItems; }
            set
            {
                this.m_AssetItems = value;
                RaisePropertyChanged(nameof(this.AssetItems));
            }
        }
        #endregion

        #region 命令相关
        /// <summary>
        /// 选择型号
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SelectProductType(object parameter)
        {
            try
            {
                WinSingleProductTypeSelector win = new WinSingleProductTypeSelector();
                win.Owner = this.GetWindow();
                LoadParameter.StartParameter(win, new LoadParameter(CurrentProductType?.Clone()));
                if (win.ShowDialog() == true)
                {
                    ProductTypeShowItem item = win.GetRealResult<ProductTypeShowItem>();
                    this.CurrentProductType = item;
                }
            }
            catch (Exception ex)
            {

                MessageTipEx.Show(ex);
            }
        }
        public bool CanSelectProductType(object parameter)
        {
            return true;
        }


        /// <summary>
        /// 生成资产项目
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void CreateAssetItem(object parameter)
        {
            try
            {
                CreateAssetItems(parameter as Window);
            }
            catch (Exception ex)
            {

              MessageTipEx.Show(ex);
            }
        }
        public bool CanCreateAssetItem(object parameter)
        {
            return true;
        }

        #endregion

        #region 内部方法
        /// <summary>
        /// 控制资产数据设置
        /// </summary>
        private void UpdateAssetItems()
        {
            var currentCount = this.AssetItems.Count;
            //控件绑定的Value值，与控件显示不同步的情况；
            //不使用ValueChange事件，只能这样去处理
            var uiCount = Math.Min(Math.Max(1, this.AssetCount), 100);
            if (currentCount == uiCount)
                return;
            if (currentCount > uiCount)
            {
                for (int i = currentCount - 1; i >= uiCount; i--)
                {
                    this.AssetItems.RemoveAt(i);
                }
            }
            else
            {
                string localName = GetLocalName(CurrentProductType);            
                for (int i = 0; i < currentCount; i++)
                {
                    var dataItem = this.AssetItems[i];
                    if (dataItem != null && string.IsNullOrWhiteSpace(dataItem.LocalName))
                    {
                        dataItem.LocalName = localName ?? string.Empty;
                    }
                }
                for (int i = currentCount; i < uiCount; i++)
                {                    
                    this.AssetItems.Add(new AssetShowItem() { LocalName =localName,ProductionDate=DateTime.Today.ToString("yyyyMMdd") });
                }
            }
        }

        private void AttachLocalName(ProductTypeShowItem product)
        {
            if (product == null)
                return;
             string localName = GetLocalName(product);       
            for (int i = 0; i < this.AssetItems.Count; i++)
            {
                var dataItem = this.AssetItems[i];
                if (dataItem != null && string.IsNullOrWhiteSpace(dataItem.LocalName))
                {
                    dataItem.LocalName = localName ?? string.Empty;
                }
            }
        }

        private string GetLocalName(ProductTypeShowItem product)
        {
            string localName = string.Empty;
            if (product != null)
            {
                StringBuilder builder = new StringBuilder();
                string famiy = EquipmentFamilyManager.GetFamilyName(CurrentProductType.FamilyCode);
                builder.Append($"{CurrentProductType.ProductName}({famiy}){CurrentProductType.ProductTypeName}");
                localName = builder.ToString();
            }
            return localName;
        }

        /// <summary>
        /// 整理显示对象数据
        /// </summary>
        /// <returns></returns>
        private List<AssetShowItem> GetShowItems()
        {
            foreach (var asset in this.AssetItems)
            {
                asset.CacheParameters.Clear();
                asset.ProjectId = Context.ProjectId;
                if (this.CurrentProductType != null)
                {
                    asset.Brand = this.CurrentProductType.BrandName;
                    asset.Product = this.CurrentProductType.ProductName;
                    asset.Type = this.CurrentProductType.ProductTypeName;
                    asset.TypeId = this.CurrentProductType.ProductTypeId;
                    asset.FamilyCode = this.CurrentProductType.FamilyCode;
                }                          
                asset.ProcurementPrice = this.Price;
                asset.Warranty = this.MaintenancePeriod;
                #region 增加修改参数

                asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.AssetID));
                 asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.DPSpecificationID));
                 asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.ProductDate));
                 asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.EquipLocalName));
                 asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.EquipLocalID));
                 asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.SerialNum));
                 asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.PurchasePrice));
                   asset.CacheParameters.Add(new WatchParameter(MBIBuiltInParameter.Warranty));
                #endregion
            }
            return new List<AssetShowItem>(this.AssetItems);
        }
        /// <summary>
        /// 在项目中创建资产
        /// </summary>
        private void CreateAssetItems(Window window)
        {
            if (Context == null | string.IsNullOrEmpty(Context.ProjectId))
            {
                MessageTip.Show("项目id,不能为空");
            }
            var items = GetShowItems();
            var createItems = items.Select(c => ConcertTdItem(c)).ToList();
            BatchResult<List<string>> result=BllFactory<PlatformBll>.Instance.CreateAssetItems(new ProjectSetting(Context.ProjectId), createItems);
            if (result.Result == BatchResultType.Successed)
            {
                MessageTip.Show(this.GetWindow(), "创建资产成功");
                var ids = result.AttachInfo ?? new List<string>();
                for (int i = 0; i < ids.Count; i++)
                {
                    if (items.Count > i)
                    {
                        items[i].Id = ids[i];
                    }
                }
                if (Context != null)
                {
                    Context.AddedItems.AddRange(items);
                }
             
                window.DialogResult = true;
            }
            else if(result.Result==BatchResultType.PartSuccessed)
            {
                MessageTip.Show(this.GetWindow(),"创建资产部分失败，不能直接将新资产关联到相关列表,请去选择列表选择");
                window.DialogResult = true;
            }
            else
            {
                MessageTip.Show(this.GetWindow(),"创建资产全部失败");
                window.DialogResult = false;
            }
        }
        #endregion
        #region 创建值转换信息
        /// <summary>
        /// 显示数据转换成操作数据
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private TdAssetItem ConcertTdItem(AssetShowItem item)
        {
            TdAssetItem tdItem = AssetManager.ConvertToAssetItem(item); ;
            //tdItem.FamilyCode = item.FamilyCode;
            return tdItem;
        }
        #endregion

    }
}
