
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmSellerProjectContract.cs
//文件描述: 供应商项目合同
//创 建 者: xls
//创建日期: 2018/5/24 21:31:49
//版 本 号：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.Entity;
using Com.FirmLib.UI.BllCommon;
using Com.FirmLib.UI.Common;
using Com.FirmLib.UI.Common.Model;
using Com.FirmLib.UI.Seller.Model;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Wpf;
using FWindSoft.Wpf.Common;
using FWindSoft.Wpf.Controls;

namespace Com.FirmLib.UI.Seller
{
    /*
     * 两种入口，一种是在现有的项目中进入；
     * 一种是直接新建；项目进入不允许修改联系人？这个限定有意义吗，带论证
     */
     /// <summary>
     /// 供应合同维护
     /// </summary>
    public class VmSellerProjectContract : BaseViewModel
    {
        public VmSellerProjectContract()
        {
            Init();
        }
        private void Init()
        {
            ContactItem = new ContactInformationItem();
        }
        public void Init(LoadParameter parameter)
        {
            VenderProjectParameter contractParameter = parameter.Parameter as VenderProjectParameter;
            if (contractParameter == null)
                return;
            SellerId = contractParameter.VenderId;
            if (contractParameter.ProjectValid)
            {
                ProjectNo =ProjectIdManager.GetForeSystemProjectId(contractParameter.ProjectId);
                ProjectFixed = true;
            }
        }
        #region 属性相关
        /// <summary>
        /// 供应商id
        /// </summary>
        public string SellerId { get; private set; }

        
        private bool m_ProjectFixed;
        /// <summary>
        /// 项目是否固定【编辑进入入口】
        /// </summary>
        public bool ProjectFixed
        {
            get { return this.m_ProjectFixed; }
            set
            {
                this.m_ProjectFixed = value;
                RaisePropertyChanged(nameof(this.ProjectFixed));
            }
        }

        private string m_ContractNo;
        /// <summary>
        /// 供应商编号
        /// </summary>
        public string ContractNo
        {
            get { return this.m_ContractNo; }
            set
            {
                this.m_ContractNo = value;
                RaisePropertyChanged(() => this.ContractNo);
            }
        }

        /// <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);
                    LoadLinkerItem(SellerId, SystemProjectId);
                }             
                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 ScanAssetInfo(object parameter)
        {

            try
            {
                AssetShowItem item = parameter as AssetShowItem;
                if (item == null)
                    return;
                AssetShowItemUtils.ShowAssetDetail(item);
            }
            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
            {
                if (CreateProjectInfo() && CreateAsset())
                {
                    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 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.SellerId == SellerId && showItem.SellerContractNo == ContractNo)
                    {
                        flag = AssetManager.DeleteSellerAssets(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 CreateAssetCommand(object parameter)
        {

            try
            {
                WinSupplyAssetCreater win = new WinSupplyAssetCreater();
                SelectAssetContext context = new SelectAssetContext();
                context.ProjectId = SystemProjectId;
                context.VenderId = SellerId;
                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 CanCreateAssetCommand(object parameter)
        {
            //项目可用才能弹出窗体
            return ValidateProject;
        }

        /// <summary>
        /// 选择资产
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SelectAssetCommand(object parameter)
        {

            try
            {
                WinSupplyAssetSelector win = new WinSupplyAssetSelector();
                win.Owner = this.GetWindow();
                SelectAssetContext context = new SelectAssetContext();
                context.ProjectId = SystemProjectId;
                context.VenderId = SellerId;
                if (RefAssetItems == null)
                {
                    RefAssetItems = new ObservableCollection<AssetShowItem>();
                }

                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 SelectContractNo(object parameter)
        {
            try
            {
                if (string.IsNullOrEmpty(SystemProjectId))
                {
                    MessageTip.Show(this.GetWindow(),"请先确定项目编号");
                    return;
                }
                WinSupplyContractNoSelector win = new WinSupplyContractNoSelector();
                win.Owner = this.GetWindow();
                ContractSelectorParameter par = new ContractSelectorParameter();
                par.ProjectId =SystemProjectId;
                par.VenderId = SellerId;
                par.ContractNo = this.ContractNo;
                LoadParameter.StartParameter(win, new LoadParameter(par));
                if (win.ShowDialog() == true)
                {
                    this.ContractNo = win.GetRealResult<string>() ?? string.Empty;
                    //加载资产项目
                    LoadAssetItem(SellerId,SystemProjectId, ContractNo);
                }
            }
            catch (Exception ex)
            {

                MessageTipEx.Show(ex);
            }
        }
        public bool CanSelectContractNo(object parameter)
        {
            return ValidateProject;
        }

        
        #endregion

        #region 私有方法
        /// <summary>
        /// 创建项目信息
        /// </summary>
        /// <returns></returns>
        private bool CreateProjectInfo()
        {
            LinkerItem item = new LinkerItem();
            item.VenderId = SellerId;
            item.ProjectId =SystemProjectId;

            item.Name = ContactItem.People;
            item.Phone = ContactItem.Telephone;
            item.Fax = ContactItem.Fax;
            item.Email = ContactItem.Email;
            var result = BllFactory<SellerBll>.Instance.UpdateLinker(item);
            if (!result)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<SellerBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        }


        /// <summary>
        /// 通过项目编号加载项目信息
        /// </summary>
        /// <param name="projectId"></param>
        private void LoadProjectItem(string projectId)
        {
            projectId = ProjectIdManager.GetSystemProjectId(projectId);
            if (IsInEditing)
                return;
            ProjectItem item = null;
            try
            {
                ValidateProject = false;
                if (string.IsNullOrEmpty(projectId))
                    return;
                item = BllFactory<ProjectBll>.Instance.GetProjectItem(projectId);
                ValidateProject = item != null;
            }
            finally
            {
                if (ValidateProject)
                {
                    LocalProjectName = item?.Name;
                }
                else
                {
                    LocalProjectName = "";
                }
            }
        }

        /// <summary>
        /// 加载联系人信息
        /// </summary>
        /// <param name="venderId">厂商库id</param>
        /// <param name="projectId">项目Id</param>
        private void LoadLinkerItem(string venderId, string projectId)
        {
            var linkerItem = BllFactory<SellerBll>.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;
            }
        }

    
        #region 保存资产相关
        private bool CreateAsset()
        {
            if (this.RefAssetItems == null || !this.RefAssetItems.Any())
                return true;
            #region 漏填的产品确认
            List<ProductTypeShowItem> typeItems = GetLossTypes();
            if (typeItems.Any())
            {
                WinAddLossProductType win = new WinAddLossProductType();
                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(SellerId, new List<string>(useIds));
                        }

                    }
                }
            }
            #endregion


            #region 修改资产信息
            RefAssetItems.ToList().ForEach(assetItem =>
            {
                assetItem.CacheParameters.Clear();
                assetItem.SellerId = SellerId;
                assetItem.SellerContractNo = this.ContractNo;
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.DPSellerID)));
                 assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.SupplierContractID)));
                 assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.DPSpecificationID)));
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.PurchasePrice)));
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.Warranty)));
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.ProductDate)));
            });
            return AssetManager.UpdateAssetItems(SystemProjectId, RefAssetItems.ToList());
            #endregion

        }
        

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

        #region 加载相关资产
        private void LoadAssetItem(string venderId, string projectId,string contractNo)
        {
            var showItems = new List<AssetShowItem>();
            var dataItems = BllFactory<SellerBll>.Instance.GetProjectAssetItems(venderId, projectId);
            foreach (var dataItem in dataItems)
            {
                if (string.IsNullOrEmpty(dataItem.Asset.SupplierContractID))
                {
                    continue;
                }

                if (dataItem.Asset.SupplierContractID != contractNo)
                {
                        continue;
                }            
                var showItem = SellerDataConverter.ConvertShowItem(dataItem);
                showItem.ProjectId = projectId;
                showItems.Add(showItem);
            }
            RefAssetItems = new ObservableCollection<AssetShowItem>(showItems);
        }
        #endregion
        #endregion

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

    }
}
