
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmManitainerProjectInfo.cs
//文件描述: 维修商项目信息
//创 建 者: xls
//创建日期: 2018/5/24 22:08:12
//版 本 号：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 System.Windows.Data;
using CEFSharpWpf;
using Com.FirmLib.Bll;
using Com.FirmLib.Entity;
using Com.FirmLib.UI.BllCommon;
using Com.FirmLib.UI.Common.Model;
using Com.FirmLib.UI.Maintainer.Mode;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.SystemExtensions;
using FWindSoft.Wpf;
using FWindSoft.Wpf.Common;

namespace Com.FirmLib.UI.Maintainer
{
    public class VmManitainerProjectInfo : BaseViewModel
    {
        public VmManitainerProjectInfo()
        {
            Init();
        }

        private void Init()
        {
            ContactItem = new ContactInformationItem();
        }
        public void Init(LoadParameter parameter)
        {
            MaintainerParameter para = parameter.Parameter as MaintainerParameter;
            MaintainerId = para.Maintainer.Id;
            ProjectId = para.Project.Id;
            //加载数据
            LoadProjectItem(ProjectId);
            LoadMaintainerItem(MaintainerId);
            LoadLinkerItem(MaintainerId, ProjectId);
            LoadAssetItems(MaintainerId, ProjectId);
        }
        #region 属性相关
        /// <summary>
        /// 维修商id
        /// </summary>
        private string MaintainerId { get; set; }
        /// <summary>
        /// 项目Id
        /// </summary>
        public string ProjectId { get; private set; }
        public string ProjectName { get; private set; }
        private string m_MaintainerName;
        /// <summary>
        /// 维修商名称
        /// </summary>
        public string MaintainerName
        {
            get { return this.m_MaintainerName; }
            set
            {
                this.m_MaintainerName = value;
                RaisePropertyChanged(() => this.MaintainerName);
            }
        }


        private string m_MaintainerUrl;
        /// <summary>
        /// 维修商网址
        /// </summary>
        public string MaintainerUrl
        {
            get { return this.m_MaintainerUrl; }
            set
            {
                this.m_MaintainerUrl = value;
                RaisePropertyChanged(() => this.MaintainerUrl);
            }
        }


        private ContactInformationItem m_ContactItem;
        /// <summary>
        /// 联系信息
        /// </summary>
        public ContactInformationItem ContactItem
        {
            get { return this.m_ContactItem; }
            set
            {
                this.m_ContactItem = value;
                RaisePropertyChanged(() => this.ContactItem);
            }
        }


        private ObservableCollection<AssetShowItem> m_CurrentAssets;
        /// <summary>
        /// 当前资产
        /// </summary>
        public ObservableCollection<AssetShowItem> CurrentAssets
        {
            get { return this.m_CurrentAssets; }
            set
            {
                this.m_CurrentAssets = value;
                RaisePropertyChanged(() => this.CurrentAssets);
            }
        }
        private ObservableCollection<AssetShowItem> m_HistotyAssets;
        /// <summary>
        /// 历史资产
        /// </summary>
        public ObservableCollection<AssetShowItem> HistotyAssets
        {
            get { return this.m_HistotyAssets; }
            set
            {
                this.m_HistotyAssets = value;
                RaisePropertyChanged(() => this.HistotyAssets);
            }
        }


        private bool m_IsFilter;
        /// <summary>
        /// 是否过滤
        /// </summary>
        public bool IsFilter
        {
            get { return this.m_IsFilter; }
            set
            {
                this.m_IsFilter = value;
                RaisePropertyChanged(nameof(this.IsFilter));
            }
        }
        #endregion

        #region 命令相关
        /// <summary>
        /// 浏览资产信息
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void ScanAssetInfo(object parameter)
        {

            try
            {
                AssetShowItem item = parameter as AssetShowItem;
                if (item == null)
                    return;
                AssetItem parItem = new AssetItem();
                parItem.Id = item.Id;
                parItem.ProjectId = item.ProjectId;
                //获取三位编码
                parItem.FamilyCode = item.FamilyCode.Substring(2);// EquipmentFamilyManager.GetaTopCode(item.Category.Substring(2)); //item.Category.Substring(0,3);
                string url = BllFactory<AssetBll>.Instance.GetEquipmentUrl(parItem);
                WinBrowser.Instance.Show(url, "设备信息");
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanScanAssetInfo(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SaveCommand(object parameter)
        {

            try
            {
                var flag = CreateAssets();
                if (flag)
                {
                    AfterSuccessSave();
                    MessageTip.Show(this.GetWindow(), "保存成功");
                }
                else
                {
                    MessageTip.Show(this.GetWindow(), "保存失败");

                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }

        }
        public bool CanSaveCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 选择设备
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SelectAssetCommand(object parameter)
        {

            try
            {
                WinMaintainerAssetSelector win = new WinMaintainerAssetSelector();
                win.Owner = this.GetWindow();
                SelectAssetContext context = new SelectAssetContext();
                context.ProjectId = ProjectId;
                context.VenderId = MaintainerId;
                context.ContainIds = new List<string>(CurrentAssets.Select(p => p.Id));
                LoadParameter.StartParameter(win, new LoadParameter(context));
                if (win.ShowDialog() == true)
                {
                    if (CurrentAssets == null)
                    {
                        CurrentAssets = new ObservableCollection<AssetShowItem>();
                    }
                    var addRelations = context.AddedItems;
                    foreach (var item in addRelations)
                    {
                        if (CurrentAssets.Any(c => c.Id == item.Id))
                            return;
                        CurrentAssets.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanSelectAssetCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 删除维护设备
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void DeleteCommand(object parameter)
        {

            try
            {
                AssetShowItem showItem = parameter as AssetShowItem;
                if (showItem == null)
                    return;
                var result = MessageTip.Show(this.GetWindow(), "是否要删除", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    bool flag = false;
                    if (showItem.MaintainerId == MaintainerId)
                    {
                        flag = AssetManager.DeleteMaintainerEquipments(ProjectId, new List<string>() { showItem.Id });
                    }
                    else
                    {
                        flag = true;
                    }
                    if (flag)
                    {
                        this.CurrentAssets.Remove(showItem);
                    }
                    else
                    {
                        MessageTip.Show(this.GetWindow(), "删除失败");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }

        public bool CanDeleteCommand(object parameter)
        {
         
            return true;
        }

        /// <summary>
        /// 过滤相关设备
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void FilterNearCommand(object parameter)
        {

            try
            {
                this.IsFilter = !IsFilter;
                if (this.CurrentAssets != null)
                {
                    var view = CollectionViewSource.GetDefaultView(this.CurrentAssets);

                    if (IsFilter)
                    {
                        view.Filter = DatetimeFilter;
                    }
                    else
                    {
                        view.Filter = null;
                    }

                    view.Refresh();

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

        private bool DatetimeFilter(object o)
        {
            AssetShowItem item = o as AssetShowItem;
            if (item == null)
                return false;
            var now = DateTime.Now.Date.AddMonths(6).ToString("yyyyMMdd");
            var time = item.MaintainerEndDate;
            if (string.IsNullOrEmpty(time))
            {
                return true;
            }
            return time.CompareTo(now)<=0;
        }

        /// <summary>
        /// 更新指定字段信息
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public bool SingleUpdateLinkerItem(string field)
        {

            LinkerItem item = new LinkerItem();
            item.VenderId = this.MaintainerId;
            item.ProjectId = this.ProjectId;
            SetFieldValue(item, field);
            var result = BllFactory<MaintainerBll>.Instance.UpdateLinker(item);
            if (!result)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<MaintainerBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        }
        private void SetFieldValue(LinkerItem item, string field)
        {
            item.Name = ContactItem.People;
            item.Phone = this.ContactItem.Telephone;
            item.Email = this.ContactItem.Email;
            item.Fax = this.ContactItem.Fax;
            #region 修改相关
            //if (field == "People")
            //{
            //    item.Name = ContactItem.People;
            //    return;
            //}
            //if (field == "Telephone")
            //{
            //    item.Phone = this.ContactItem.Telephone;
            //    return;
            //}
            //if (field == "Email")
            //{
            //    item.Email = this.ContactItem.Email;
            //    return;
            //}
            //if (field == "Fax")
            //{
            //    item.Fax = this.ContactItem.Fax;
            //    return;
            //} 
            #endregion
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 加载供应商信息
        /// </summary>
        /// <param name="venderId">厂商id</param>
        private void LoadMaintainerItem(string venderId)
        {
            var seller = BllFactory<MaintainerBll>.Instance.GetAllItems().FirstOrDefault(c => c.Id == venderId);
            if (seller != null)
            {
                this.MaintainerName = seller.Name;
                this.MaintainerUrl = seller.Website;
            }

        }
        /// <summary>
        /// 加载联系人信息
        /// </summary>
        /// <param name="venderId">厂商库id</param>
        /// <param name="projectId">项目Id</param>
        private void LoadLinkerItem(string venderId, string projectId)
        {
            var linkerItem = BllFactory<MaintainerBll>.Instance.GetLinker(venderId, projectId);
            if (linkerItem != null)
            {
                this.ContactItem.Telephone = linkerItem.Phone;
                this.ContactItem.People = linkerItem.Name;
                this.ContactItem.Fax = linkerItem.Fax;
                this.ContactItem.Email = linkerItem.Email;
            }
        }
        /// <summary>
        /// 获取相关设备信息
        /// </summary>
        /// <param name="venderId"></param>
        /// <param name="projectId"></param>
        private void LoadAssetItems(string venderId, string projectId)
        {
            CurrentAssets = new ObservableCollection<AssetShowItem>();
            HistotyAssets = new ObservableCollection<AssetShowItem>();
            var dataItems = BllFactory<MaintainerBll>.Instance.GetCurrentProjectAssetItems(venderId, projectId);
            foreach (var dataItem in dataItems)
            {
                var tempItem = MaintainerDataConverter.ConvertShowItem(dataItem);
                tempItem.ProjectId = projectId;
                CurrentAssets.Add(tempItem);
            }
            dataItems = BllFactory<MaintainerBll>.Instance.GetHistoryProjectAssetItems(venderId, projectId);
            foreach (var dataItem in dataItems)
            {
                var tempItem = MaintainerDataConverter.ConvertShowItem(dataItem);
                tempItem.ChangeMaintainer = dataItem.ChnageMaintainer;
                tempItem.ProjectId = projectId;
                HistotyAssets.Add(tempItem);
            }
        }

   

        private void LoadProjectItem(string projectId)
        {
            var projectItem = BllFactory<ProjectBll>.Instance.GetProjectItem(projectId);
            if (projectItem != null)
            {
                this.ProjectName = projectItem.Name;
            }
           
        }
        #endregion

        #region 保存设备
        private bool CreateAssets()
        {
            if (this.CurrentAssets == null || !this.CurrentAssets.Any())
                return true;
            //维修商变化设备
            List<AssetShowItem> changedItems = new List<AssetShowItem>();
            foreach (var item in this.CurrentAssets)
            {
                item.CacheParameters.Clear();
                var parameters = GetChangeParameters(item);
                if (!parameters.IsEmpty)
                {
                    item.CacheParameters.Merge(parameters);
                    changedItems.Add(item);
                }
            }
            if (changedItems.Any())
            {
                AssetSaveContext context = new AssetSaveContext();
                context.ChangedItems = changedItems;
                WinMaintainerSaveEnsure win = new WinMaintainerSaveEnsure();
                win.Owner = this.GetWindow();
                LoadParameter.StartParameter(win, new LoadParameter(context));
                if (win.ShowDialog() == true)
                {
                    context = win.GetRealResult<AssetSaveContext>();
                    if (context != null)
                    {
                        var items = context.ChangedItems ?? new List<AssetShowItem>();
                        foreach (var item in items)
                        {
                            if (context.EditType == EditType.Correct)
                            {
                                item.CacheParameters.SetAllParameterTime(context.EffectiveTime);
                            }
                        }
                    }
                }
            }

            #region 数据整理
            CurrentAssets.ToList().ForEach(assetItem =>
            {
               
                //变化的才修改，不变的不修改
                if (string.IsNullOrEmpty(assetItem.MaintainerId))
                {
                      assetItem.CacheParameters.Add((new WatchParameter(MBIBuiltInParameter.DPMaintainerID)));
                }    
                assetItem.MaintainerId = MaintainerId;
                assetItem.CacheParameters.Add((new WatchParameter(MBIBuiltInParameter.MaintainDeadline)));
                assetItem.CacheParameters.Add((new WatchParameter(MBIBuiltInParameter.MaintainPeriod)));
            });
        
            #endregion

            #region 历史资产保存

            var historyItems =new  List<AssetShowItem>();
            if(HistotyAssets!=null)
            {
                foreach (var assetShowItem in HistotyAssets)
                {
                    assetShowItem.CacheParameters.Clear();
                    if (!assetShowItem.ChangeMaintainer)
                    {
                        assetShowItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.MaintainDeadline)));
                        historyItems.Add(assetShowItem);
                    }
                }
            }     
            #endregion

            historyItems.AddRange(CurrentAssets.ToList());
             bool flag = AssetManager.UpdateEqItems(ProjectId,historyItems);
            return flag;

        }
        /// <summary>
        /// 初始化变化参数
        /// </summary>
        /// <param name="item"></param>
        private WatchParameters GetChangeParameters(AssetShowItem item)
        {
            WatchParameters parameters = new WatchParameters();
            if (!string.IsNullOrEmpty(item.MaintainerId) && item.MaintainerId != MaintainerId)
            {
                parameters.Add(new WatchParameter(MBIBuiltInParameter.DPMaintainerID));
            }
            return parameters;
        }
        #endregion

        /// <summary>
        /// 成功保存后处理
        /// </summary>
        private void AfterSuccessSave()
        {
            LoadLinkerItem(MaintainerId, ProjectId);
            LoadAssetItems(MaintainerId, ProjectId);
        }
    }
}
