
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmMaintainerProjectAsset.cs
//文件描述: 维修商项目资产
//创 建 者: xls
//创建日期: 2018/5/24 22:10:36
//版 本 号：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 CEFSharpWpf;
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;
using FWindSoft.Wpf.Controls;

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

        private void Init()
        {
            ContactItem = new ContactInformationItem();
        }
        public void Init(LoadParameter parameter)
        {
             MaintainerId = parameter.Parameter as string;
        }
        #region 属性相关
        /// <summary>
        /// 维修商Id
        /// </summary>
        public string MaintainerId { get; private set; }

        private string m_EndDate;
        /// <summary>
        /// 截止日期
        /// </summary>
        public string EndDate
        {
            get { return this.m_EndDate; }
            set
            {
                this.m_EndDate = value;
                RaisePropertyChanged(() => this.EndDate);
            }
        }
        /// <summary>
        /// 有效的项目编号
        /// </summary>
        public bool ValidateProject { get; set; }
        private string m_ProjectNo;
        /// <summary>
        /// 项目编号
        /// </summary>
        public string ProjectNo
        {
            get { return this.m_ProjectNo; }
            set
            {
                this.m_ProjectNo = value;
                if (!IsInEditing)
                {
                    LoadProjectItem(SystemProjectId);
                    LoadEquipmentItems(SystemProjectId, MaintainerId);
                }
                
                RaisePropertyChanged(() => this.ProjectNo);
            }
        }
        /// <summary>
        /// 系统项目Id
        /// </summary>
        public string SystemProjectId
        {
            get { return ProjectIdManager.GetSystemProjectId(ProjectNo); }
        }

        private string m_LocalProjectName;
        /// <summary>
        /// 项目本地名称
        /// </summary>
        public string LocalProjectName
        {
            get { return this.m_LocalProjectName; }
            set
            {
                this.m_LocalProjectName = value;
                RaisePropertyChanged(() => this.LocalProjectName);
            }
        }
        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_RefAssetItems;
        /// <summary>
        /// 关联资产信息
        /// </summary>
        public ObservableCollection<AssetShowItem> RefAssetItems
        {
            get { return this.m_RefAssetItems; }
            set
            {
                this.m_RefAssetItems = value;
                RaisePropertyChanged(nameof(this.RefAssetItems));
            }
        }
        #endregion

        #region 命令相关
        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SaveCommand(object parameter)
        {

            try
            {
                if (CreateProjectInfo() && CreateRefEquipment())
                {

                    AfterSuccessSave();
                    MessageTip.Show(this.GetWindow(), "保存成功");
                }
                else
                {
                    MessageTip.Show(this.GetWindow(), "保存失败");
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanSaveCommand(object parameter)
        {
            return IsValidated&&ValidateProject;;
        }
        /// <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 = SystemProjectId;
                context.VenderId = MaintainerId;
                context.ContainIds = new List<string>(RefAssetItems.Select(p => p.Id));
                LoadParameter.StartParameter(win, new LoadParameter(context));
                if (win.ShowDialog() == true)
                {
                    if (RefAssetItems == null)
                    {
                        RefAssetItems = new ObservableCollection<AssetShowItem>();
                    }
                    var addRelations = context.AddedItems;
                    foreach (var item in addRelations)
                    {
                        if (RefAssetItems.Any(c => c.Id == item.Id))
                            return;
                        RefAssetItems.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanSelectAssetCommand(object parameter)
        {
            return ValidateProject;
        }


        /// <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(SystemProjectId, new List<string>() { showItem.Id });
                    }
                    else
                    {
                        flag = true;
                    }
                    if (flag)
                    {
                        this.RefAssetItems.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 ScanCommand(object parameter)
        {

            try
            {
                AssetShowItem showItem = parameter as AssetShowItem;
                if (showItem == null)
                {
                    return;
                }
                AssetItem parItem = new AssetItem();
                parItem.Id = showItem.Id;
                parItem.ProjectId = showItem.Id;
                //获取三位编码
                parItem.FamilyCode = showItem.FamilyCode.Substring(2);
                string url = BllFactory<AssetBll>.Instance.GetEquipmentUrl(parItem);
                WinBrowser.Instance.Show(url, "设备信息");
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanScanCommand(object parameter)
        {
            return true;
        }
        #endregion
        #region 私有方法
        /// <summary>
        /// 创建项目信息
        /// </summary>
        /// <returns></returns>
        private bool CreateProjectInfo()
        {
            LinkerItem item = new LinkerItem();
            item.VenderId = MaintainerId;
            item.ProjectId = SystemProjectId;

            item.Name = ContactItem.People;
            item.Phone = ContactItem.Telephone;
            item.Fax = ContactItem.Fax;
            item.Email = ContactItem.Email;
            var result = BllFactory<MaintainerBll>.Instance.UpdateLinker(item);
            if (!result)
            {
                MessageBox.Show(BllFactory<MaintainerBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        }
        /// <summary>
        /// 通过项目编号加载项目信息
        /// </summary>
        /// <param name="projectNo"></param>
        private void LoadProjectItem(string projectNo)
        {        
            ProjectItem item = null;
            try
            {
                ValidateProject = false;
                if (string.IsNullOrEmpty(projectNo))
                    return;
                item = BllFactory<ProjectBll>.Instance.GetProjectItem(projectNo);
                ValidateProject = item!=null;
            }
            finally
            {
                if (ValidateProject)
                {
                    LocalProjectName = item.Name;
                    LoadLinkerItem(MaintainerId, projectNo);
                }
                else
                {
                    LocalProjectName = string.Empty;
                }
            }
        }
        /// <summary>
        /// 加载联系人信息
        /// </summary>
        /// <param name="venderId">厂商库id</param>
        /// <param name="projectId">项目Id</param>
        private void LoadLinkerItem(string venderId, string projectId)
        {
            //    return;
            if (string.IsNullOrEmpty(projectId) || string.IsNullOrEmpty(venderId))
                return;
            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="projectId"></param>
        /// <param name="venderId"></param>
        private void LoadEquipmentItems(string projectId, string venderId)
        {
            RefAssetItems = new ObservableCollection<AssetShowItem>();          
            var dataItems = BllFactory<MaintainerBll>.Instance.GetCurrentProjectAssetItems(venderId, projectId);
            foreach (var dataItem in dataItems)
            {
                var tempItem =  MaintainerDataConverter.ConvertShowItem(dataItem);
                tempItem.ProjectId = projectId;
                RefAssetItems.Add(tempItem);
            }      
        }
        #endregion

        #region 保存资产相关
        private bool CreateRefEquipment()
        {
            if (this.RefAssetItems == null || !this.RefAssetItems.Any())
                return true;
            #region 漏填的产品确认
            List<ProductTypeShowItem> typeItems = GetLossTypes();
            if (typeItems.Any())
            {
                WinMaintainerSaveEnsure win = new WinMaintainerSaveEnsure();
                win.Owner = this.GetWindow();
                LoadParameter.StartParameter(win, new LoadParameter(new List<ProductTypeShowItem>(typeItems)));
                if (win.ShowDialog() == true)
                {
                    var checkedItems = win.GetRealResult<List<ProductTypeShowItem>>();
                    if (checkedItems != null)
                    {
                        var useIds = checkedItems.Select(c => c.ProductTypeId);
                        if(!useIds.Any())
                        {
                            var flag = BllFactory<ProductDirectoryBll>.Instance.Add(MaintainerId, new List<string>(useIds));
                        }
                      
                    }
                }
            }
            #endregion
            #region 资产变更信息点确认
            List<AssetShowItem> changedItems = new List<AssetShowItem>();
            foreach (var item in this.RefAssetItems)
            {
                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);
                            }
                        }
                    }
                }

            }
            #endregion
            #region 数据整理
            RefAssetItems.ToList().ForEach(assetItem =>
            {
              
                assetItem.MaintainerId = MaintainerId;
                assetItem.MaintainerEndDate = this.EndDate??string.Empty;
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.DPMaintainerID)));
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.MaintainDeadline)));
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.MaintainPeriod)));
            });
            return AssetManager.UpdateEqItems(SystemProjectId, RefAssetItems.ToList());
            #endregion

        }
        /// <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;
        }

        /// <summary>
        /// 获取漏掉的类型信息
        /// </summary>
        /// <returns></returns>
        private List<ProductTypeShowItem> GetLossTypes()
        {
            List<ProductTypeShowItem> items = new List<ProductTypeShowItem>();
            var containItems = BllFactory<ProductDirectoryBll>.Instance.GetAllItems(MaintainerId);
            var assets = new List<AssetShowItem>(this.RefAssetItems ?? new ObservableCollection<AssetShowItem>());
            items.AddRange(AssetShowItemUtils.GetLossTypes(assets, containItems.Select(c => c.ProductTypeId).ToList()));
            return items;
        }
        #endregion

        /// <summary>
        /// 成功保存后处理
        /// </summary>
        private void AfterSuccessSave()
        {
               ProjectManager.SyncMaintainerProject(SystemProjectId, MaintainerId);
              LoadEquipmentItems(SystemProjectId, MaintainerId);
            if (this.GetNavigationBar() is NavigationBar bar)
            {
                bar.RefreshPreWinddow();
            }
        }
    }
}
