
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmProductType.cs
//文件描述: 产品类型信息
//创 建 者: xls
//创建日期: 2018/5/23 23:29:57
//版 本 号：1.0.0.0
////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Manufacturer.Model;
using FWindSoft.Data;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Wpf;

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

        private void Init()
        {
            Product = new NameValueItem();
            Brand = new NameValueItem();
        }


        public void Init(LoadParameter parameter)
        {
            //加载类型定义信息
            ProductShowItem product = parameter.Parameter as ProductShowItem;
            if (product == null)
                throw new ArgumentNullException(nameof(parameter));

            ProcutItem=LoadProductItem(product.BrandId, product.ProductId);
            Brand.Name = GetBrandName(product.VenderId,product.BrandId);
            Brand.Value = product.BrandId;
            Product.Value = product.ProductId;
            Product.Name = ProcutItem.Name;

            LoadInfoPointDefinitions(ProcutItem.FamilyCode);//加载设备点定义
            LoadItems(product.ProductId);
        }
        #region 属性相关
        /// <summary>
        /// 产品信息
        /// </summary>
        public ProductItem ProcutItem { get; private set; }
        /// <summary>
        /// 产品信息
        /// </summary>
        public NameValueItem Product { get; private set; }
        /// <summary>
        /// 品牌信息
        /// </summary>
        public NameValueItem Brand { get; private set; }
        /// <summary>
        /// 族信息点定义值
        /// </summary>
        public List<PropertyDefinition> RefDefinitions { get; private set; }
     


        private ObservableCollection<TypeShowItem> m_TypeItems;
        /// <summary>
        /// 类型列表
        /// </summary>
        public ObservableCollection<TypeShowItem> TypeItems
        {
            get { return this.m_TypeItems; }
            set
            {
                this.m_TypeItems = value;
                RaisePropertyChanged(() => this.TypeItems);
            }
        }
        private TypeShowItem m_CurrentTypeItem;
        /// <summary>
        /// 当前类型信息
        /// </summary>
        public TypeShowItem CurrentTypeItem
        {
            get { return this.m_CurrentTypeItem; }
            set
            {
                this.m_CurrentTypeItem = value;
                RaisePropertyChanged(() => this.CurrentTypeItem);
            }
        }
        #endregion

        #region 命令相关
        /// <summary>
        /// 添加产品类型
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddTypeCommand(object parameter)
        {

            try
            {
                var tempItem = new TypeShowItem();
                tempItem.TypeName = "";
                tempItem.Parameters = PropertyCollection.CreateCollection(RefDefinitions ?? new List<PropertyDefinition>());
                foreach (var tempItemParameter in tempItem.Parameters)
                {
                    tempItemParameter.Value = "";
                }
                TypeItems.Add(tempItem);
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanAddTypeCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 删除产品类型
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void DeleteCommand(object parameter)
        {

            try
            {
                var item = parameter as TypeShowItem;
                if (item == null)
                    return;
                var result = MessageTip.Show(this.GetWindow(), "是否要删除", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    if (!string.IsNullOrEmpty(item.ProductTypeId))
                    {
                        DeleteItem(item.ProductTypeId);
                    }
                    //todo 刷新窗体
                    //LoadItems();
                    TypeItems.Remove(item);
                }
            }
            catch (Exception e)
            {
                MessageTip.Show(this.GetWindow(), "删除失败");
            }
           
        }
        public bool CanDeleteCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 保存功能
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SaveCommand(object parameter)
        {

            try
            {
                foreach (var item in TypeItems)
                {
                    string message = string.Empty;
                    if (CheckInputError(item, out message))
                    {
                        CurrentTypeItem = item;
                        MessageTip.Show(this.GetWindow(), message);

                        return;
                    }
                }

                var result = CreateProductTypes();
                if (result)
                {
                    MessageTip.Show(this.GetWindow(), "保存成功");
                }
                else
                {
                    MessageTip.Show(this.GetWindow(), $"保存失败,【{result}】");
                }
            }
            catch (Exception e)
            {

                MessageTipEx.Show(this.GetWindow(), e);
            }
           
        }

     

        public bool CanSaveCommand(object parameter)
        {
            return true;
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 根据产品id加载产品类型
        /// </summary>
        /// <param name="productId"></param>
        private void LoadItems(string productId)
        {
            var types = ProductTypeManager.GetProdcutTypeInfoItems(productId, RefDefinitions);
            TypeItems = new ObservableCollection<TypeShowItem>(types);       
            if (!TypeItems.Any())
            {
                AddTypeCommand(null);
            }
        }

        /// <summary>
        /// 获取产品信息
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="productId"></param>
        /// <returns></returns>
        private ProductItem LoadProductItem(string brandId, string productId)
        {

            var productItems = BllFactory<ProductBll>.Instance.GetAllItems(brandId);
            return productItems.FirstOrDefault(c => c.Id == productId);

        }
        /// <summary>
        /// 获取品牌名称
        /// </summary>
        /// <param name="venderId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private string GetBrandName(string venderId,string id)
        {
            var brandItem = BllFactory<BrandBll>.Instance.GetItem(venderId, id);
            if (brandItem == null)
                return string.Empty;
            return brandItem.Name;
        }
        private bool CheckInputError(TypeShowItem showItem,out string message)
        {
            string resutMessage = string.Empty;
            bool result = true;
            do
            {
                if (string.IsNullOrEmpty(showItem.TypeName))
                {
                    resutMessage = "型号名称不能为空";
                    break;
                }
                #region 其他验证
                //if (showItem.Parameters.Count > 1)
                //{
                //    if (showItem.Parameters[0].Value == null || string.IsNullOrEmpty(showItem.Parameters[0].Value.ToString()))
                //    {
                //        resutMessage = "保养周期不能为空";
                //        break;
                //    }
                //    if (showItem.Parameters[1].Value == null || string.IsNullOrEmpty(showItem.Parameters[1].Value.ToString()))
                //    {
                //        resutMessage = "使用寿命不能为空";
                //        break;
                //    }
                //} 
                #endregion

                int count = TypeItems.Count;
                bool haseError = false;
                for (int i = 0; i < count; i++)
                {
                    var baseItem = TypeItems[i];
                    if (baseItem == showItem)
                        continue;
                    if (baseItem.TypeName == showItem.TypeName)
                    {
                       
                        resutMessage = "型号名称不能重复";
                        haseError = true;
                        break;
                    }

                }
                if (haseError)
                    break;
                 result = false;
            } while (false);
            message = resutMessage;
            return result;
        }
        /// <summary>
        /// 保存类型信息，存在则修改，不存在则添加
        /// </summary>
        /// <returns></returns>
        private TResult CreateProductTypes()
        {

            List<bool> results = new List<bool>();
            TResult result = null;
            foreach (var item in TypeItems)
            {
                bool flag = false;
                ProductTypeItem dataItem = ConvertDataItem(item);
                if (string.IsNullOrWhiteSpace(item.ProductTypeId))
                {
                    //添加
                    dataItem.ProductId = Product.Value.ToString();
                    flag=BllFactory<ProductTypeBll>.Instance.Add(dataItem);
                    if (flag)
                    {
                        item.ProductTypeId = dataItem.Id;
                    }
                }
                else
                {
                    //修改
                    flag = BllFactory<ProductTypeBll>.Instance.Update(dataItem);
                }

                if (!flag)
                {
                    result = new TResult(flag, BllFactory<ProductTypeBll>.Instance.ErrorMessage);
                    break;
                }
            }
            return result??true;
        }

        private ProductTypeItem ConvertDataItem(TypeShowItem showItem)
        {
            ProductTypeItem product = new ProductTypeItem();
            product.Id = showItem.ProductTypeId;
            product.Name = showItem.TypeName;
            product.Parameters = new List<ParameterItem>();
            foreach (var item in showItem.Parameters)
            {
                var paramItem = new ParameterItem()
                {
                    Code = item.Property.Id
                };
                if (item.Value != null)
                {
                    paramItem.Value = item.Value.ToString();
                }
                else
                {
                    paramItem.Value = string.Empty;
                }
                product.Parameters.Add(paramItem);
            }
            return product;
        }
        /// <summary>
        /// 删除类型信息
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        private bool DeleteItem(string typeId)
        {
            var result = BllFactory<ProductTypeBll>.Instance.Delete(new ProductTypeItem() { Id = typeId });
            if (!result)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<ProductTypeBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        }
        /// <summary>
        /// 加载信息点定义信息
        /// </summary>
        private void LoadInfoPointDefinitions(string code)
        {         
            RefDefinitions = ProductTypeManager.GetInfoPointDefinitions(code);
        }
        #endregion
    }
}
