
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmInsurancePolicyEditor.cs
//文件描述: 保险单编辑
//创 建 者: xls
//创建日期: 2018/5/24 22:01:48
//版 本 号：1.0.0.0
////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
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.Insuer.Model;
using FirmHttpDao;
using FWindSoft.Data;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Wpf;
using FWindSoft.Wpf.Common;
using FWindSoft.Wpf.Controls;
using Microsoft.Win32;

namespace Com.FirmLib.UI.Insuer
{
    /*
     * 两种入口
     * 1、没有项目信息的，直接创建
     * 2、带有项目信息的，项目信息不能改变
     */
    public class VmInsurancePolicyEditor : BaseViewModel
    {
        #region 初始化
        public VmInsurancePolicyEditor()
        {
            Init();
        }
        private void Init()
        {
            AssetItems = new ObservableCollection<AssetShowItem>();
            PolicyFile = new FileItem();
            ContactItem = new ContactInformationItem();
            PolicyEndDate = DateTimeManager.ConvertDateTime(DateTime.Now);
        }
        public void Init(LoadParameter parameter)
        {
            var param = parameter.Parameter as InsuerParameter;
            if (param == null)
                return;
            InsuerId = param.Insuer.Id;
            #region 控制条件初始化
            ProjectFixed = !string.IsNullOrEmpty(param.Project.Id);
            if (ProjectFixed)
            {
                ProjectNo =ProjectIdManager.GetForeSystemProjectId(param.Project.Id); ;
            }
            PolicyFixed = !string.IsNullOrEmpty(param.Policy.Id);
            if (PolicyFixed)
            {
                PolicyNo = param.Policy.Id;
                if (!string.IsNullOrEmpty(PolicyEndDate))
                {
                    var now=DateTimeManager.ConvertDateTime(DateTime.Now);
                    if (now.CompareTo(PolicyEndDate)>0)
                    {
                        IsEpire = true;
                    }
                }
            }
            #endregion   
            //如果上面的值有自然会加载资产信息
            //LoadAssetItems();
        } 
        #endregion
        #region 属性相关     
        /// <summary>
        /// 保险商Id
        /// </summary>
        public string InsuerId { get; private set; }

        #region 入口控制信息
        private bool m_ProjectFixed;
        /// <summary>
        /// 项目是否固定【编辑进入入口】
        /// </summary>
        public bool ProjectFixed
        {
            get { return this.m_ProjectFixed; }
            set
            {
                this.m_ProjectFixed = value;

                RaisePropertyChanged(nameof(this.ProjectFixed));
            }
        }


        private bool m_PolicyFixed;
        /// <summary>
        /// 保单是否固定
        /// </summary>
        public bool PolicyFixed
        {
            get { return this.m_PolicyFixed; }
            set
            {
                this.m_PolicyFixed = value;
                RaisePropertyChanged(nameof(this.PolicyFixed));
            }
        }

        private bool m_IsEpire;
        /// <summary>
        /// 保单是否过期
        /// </summary>
        public bool IsEpire
        {
            get { return this.m_IsEpire; }
            set
            {
                this.m_IsEpire = value;
                RaisePropertyChanged(() => this.IsEpire);
            }
        }
        #endregion

        #region 保单信息
        /// <summary>
        /// 是否是可用的ValidatePolicy
        /// </summary>
        public bool ValidatePolicy { get; set; }
        private string m_PolicyNo;
        /// <summary>
        /// 保单编号
        /// </summary>
        public string PolicyNo
        {
            get { return this.m_PolicyNo; }
            set
            {
                this.m_PolicyNo = value;
                if (!IsInEditing)
                {
                    LoadPolicyByNo(SystemProjectId, value);
                    LoadAssetItems();
                }
             
                RaisePropertyChanged(() => this.PolicyNo);
            }
        }
        private string m_PolicyEndDate;
        /// <summary>
        /// 保单截止日期
        /// </summary>
        public string PolicyEndDate
        {
            get { return this.m_PolicyEndDate; }
            set
            {
                this.m_PolicyEndDate = value;
                RaisePropertyChanged(() => this.PolicyEndDate);
            }
        }
        private FileItem m_PolicyFile;
        /// <summary>
        /// 保险文件
        /// </summary>
        public FileItem PolicyFile
        {
            get { return this.m_PolicyFile; }
            set
            {
                this.m_PolicyFile = value;
                RaisePropertyChanged(() => this.PolicyFile);
            }
        }
        /// <summary>
        /// 有效的项目编号
        /// </summary>
        public bool ValidateProject { get; set; }
        #endregion

        #region 项目相关信息
        private string m_ProjectNo;
        /// <summary>
        /// 项目编号
        /// </summary>
        public string ProjectNo
        {
            get { return this.m_ProjectNo; }
            set
            {
                this.m_ProjectNo = value;
                if (!IsInEditing)
                {
                    LoadProjectById(SystemProjectId);
                    LoadPolicyByNo(SystemProjectId, PolicyNo);
                    LoadAssetItems();
                }
             
                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);
            }
        }
        #endregion

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

        #region 资产信息
        private ObservableCollection<AssetShowItem> m_AssetItems;
        /// <summary>
        /// 保单资产信息
        /// </summary>
        public ObservableCollection<AssetShowItem> AssetItems
        {
            get { return this.m_AssetItems; }
            set
            {
                this.m_AssetItems = value;
                RaisePropertyChanged(() => this.AssetItems);
            }
        } 
        #endregion

        #endregion

        #region 命令相关
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void UploadCommand(object parameter)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "pdf文件|*.pdf";
                if (ofd.ShowDialog() == true)
                {
                    string fileName = ofd.FileName;
                    PolicyFile.Name = Path.GetFileName(fileName);
                    PolicyFile.Path = fileName;
                }
            }
            catch (Exception e)
            {
               MessageTipEx.Show(this.GetWindow(), e);
            }
        }
        public bool CanUploadCommand(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 查看资产详情
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void ScanAsset(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;
                string url = BllFactory<AssetBll>.Instance.GetAssetUrl(parItem);
                WinBrowser.Instance.Show(url, "资产信息");
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanScanAsset(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SaveCommand(object parameter)
        {
            //CreatePolicyAsset();
            //return;
            try
            {
                if (CreatePolicyInfo() && CreateLinkInfo()&&CreatePolicyAsset())
                {
                    AfterSuccessSave();
                    MessageTip.Show(this.GetWindow(), "保存成功");
                }
                else
                {
                    MessageTip.Show(this.GetWindow(), "保存失败");
                }
            }
            catch (Exception e)
            {

                MessageTipEx.Show(this.GetWindow(), e);
            }
        }
        public bool CanSaveCommand(object parameter)
        {
            return IsValidated&&ValidateProject;
        }
        /// <summary>
        /// 选择保单号
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SelectPolicyCommand(object parameter)
        {
            //传入当前输入的保单号，为显示默认值
            //如果项目为空，可以不弹窗

            try
            {
                WinPolicySelector win = new WinPolicySelector();
                InsuerParameter insuerParameter = new InsuerParameter();
                insuerParameter.Insuer.Id = InsuerId;
                insuerParameter.Project.Id = SystemProjectId;
                insuerParameter.Policy.Id = PolicyNo;
                LoadParameter.StartParameter(win, new LoadParameter(insuerParameter));
                win.Owner = this.GetWindow();
                if (win.ShowDialog() == true)
                {
                    var tempPolicyNo = win.GetRealResult<string>();
                    if (!string.IsNullOrEmpty(tempPolicyNo))
                    {
                        this.PolicyNo = tempPolicyNo;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanSelectPolicyCommand(object parameter)
        {
            return ValidateProject;
        }
        /// <summary>
        /// 选择资产信息
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void SelectAssetCommand(object parameter)
        {

            try
            {
                WinInsuerAssetSelector win = new WinInsuerAssetSelector();
                win.Owner = this.GetWindow();
                SelectAssetContext context = new SelectAssetContext();
                context.ProjectId = SystemProjectId;
                context.VenderId = InsuerId;

                context.ContainIds = new List<string>(AssetItems.Select(p => p.Id));
                LoadParameter.StartParameter(win, new LoadParameter(context));
                if (win.ShowDialog() == true)
                {
                    if (AssetItems == null)
                    {
                        AssetItems = new ObservableCollection<AssetShowItem>();
                    }
                    var addRelations = context.AddedItems;
                    foreach (var item in addRelations)
                    {
                        if (AssetItems.Any(c => c.Id == item.Id))
                            return;
                        AssetItems.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;
                //todo 删除资产关联关系，是直接删除，不需要保存确定
                var result = MessageTip.Show(this.GetWindow(), "是否要删除", "提示", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    bool flag = false;
                    if (showItem.InsuerId == InsuerId && showItem.InsurancePolicyNo == PolicyNo)
                    {
                        flag = AssetManager.DeleteInsuerAssets(SystemProjectId, new List<string>() { showItem.Id });
                    }
                    else
                    {
                        flag = true;
                    }
                    if (flag)
                    {
                        this.AssetItems.Remove(showItem);
                    }
                    else
                    {
                        MessageTip.Show(this.GetWindow(), "删除失败");
                    }

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

        #region 私有方法
        /// <summary>
        /// 加载资产信息
        /// </summary>
        private void LoadAssetItems()
        {
            AssetItems = new ObservableCollection<AssetShowItem>();
            if (!ValidateProject ||!ValidatePolicy)
                return;
            LoadAssetItems(InsuerId, SystemProjectId, PolicyNo);         
        }
        /// <summary>
        /// 加载资产信息
        /// </summary>
        /// <param name="venderId"></param>
        /// <param name="projectId"></param>
        /// <param name="policyId"></param>
        private void LoadAssetItems(string venderId,string projectId,string policyId)
        {
            var dataItems = BllFactory<InsuerBll>.Instance.GetPolicyAssetItems(venderId, projectId, policyId);
            List<AssetShowItem> showItems = new List<AssetShowItem>();
            foreach (var dataItem in dataItems)
            {
                var showItem = new AssetShowItem();
                showItem.Id = dataItem.Id;
                showItem.ProjectId = SystemProjectId;
                showItem.FamilyCode = dataItem.Family;
                showItem.LocalName = dataItem.Asset.EquipLocalName;
                showItem.LocalCode = dataItem.Asset.EquipLocalId;
                showItem.Brand = dataItem.Asset.Brand;
                showItem.Product = dataItem.Asset.Product;
                showItem.Type = dataItem.Asset.Specification;
                showItems.Add(showItem);
            }

            AssetItems = new ObservableCollection<AssetShowItem>(showItems);
        }

        /// <summary>
        /// 创建联系人信息
        /// </summary>
        /// <returns></returns>
        private bool CreateLinkInfo()
        {
            LinkerItem item = new LinkerItem();
            item.VenderId = InsuerId;
            item.ProjectId = SystemProjectId;
            item.Name = ContactItem.People;
            item.Phone = ContactItem.Telephone;
            item.Fax = ContactItem.Fax;
            item.Email = ContactItem.Email;
            var result = BllFactory<InsuerBll>.Instance.UpdateLinker(item);
            if (!result)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<InsuerBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        }

        /// <summary>
        /// 创建保单信息
        /// </summary>
        /// <returns></returns>
        private bool CreatePolicyInfo()
        {
            InsuerContractItem item = new InsuerContractItem();
            item.ProjectId = SystemProjectId;
            item.VenderId = InsuerId;

            item.ExpireDate =DateTimeManager.ConvertDateTime(PolicyEndDate).ToString("yyyy-MM-dd");
            item.InsuranceNo = PolicyNo;
            item.InsuranceFile = GetFileKey();//获取相关编码
            bool result = false;
            var refVenderId = BllFactory<InsuerBll>.Instance.CheckInsuranceNo(PolicyNo);
            bool isExist = !string.IsNullOrEmpty(refVenderId);
            if (!isExist)
            {
                result = BllFactory<InsuerBll>.Instance.AddPolicy(item);
            }
            else
            {
                if (refVenderId != InsuerId)
                {
                    MessageTip.Show(this.GetWindow(), $"该保单已被其他项目关联");
                    return result;
                }
                result = BllFactory<InsuerBll>.Instance.UpdatePolicy(item);
            }
            if (!result)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<InsuerBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        }
        #region 相关信息加载
        /// <summary>
        /// 获取项目，通过项目编号
        /// </summary>
        /// <param name="projectId"></param>
        private void LoadProjectById(string projectId)
        {
            ProjectItem item = null;
            try
            {
                ValidateProject = false;
                if (string.IsNullOrEmpty(projectId))
                    return;
                item = BllFactory<ProjectBll>.Instance.GetProjectItem(projectId);               
                ValidateProject = item != null;
            }
            finally
            {
                #region 修改
                if (ValidateProject)
                {
                    LocalProjectName = item.Name;
                    LoadLinkerItem(projectId, InsuerId);
                }
                else
                {
                    LocalProjectName = string.Empty;
                } 
                #endregion
            }
        }

        /// <summary>
        /// 通过保单编号加载保单信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="policyNo"></param>
        private void LoadPolicyByNo(string projectId,string policyNo)
        {
            InsuerContractItem item = null;
            string fileKey = string.Empty;
            try
            {
                ValidatePolicy = false;
                if (!ValidateProject|| string.IsNullOrEmpty(policyNo))
                    return;
                item = BllFactory<InsuerBll>.Instance.GetPolicyItem(InsuerId, projectId, policyNo);
                ValidatePolicy = item != null;
            }
            finally
            {
                if (ValidatePolicy)
                {
                    string timeStr=item.ExpireDate ?? string.Empty;

                    this.PolicyEndDate = DateTimeManager.ConvertDateTimeH(timeStr).ToString("yyyyMMdd");
                    fileKey = item.InsuranceFile;
                    PolicyFile = FileUtils.ParseFileKey(fileKey);
                }
                else
                {
                    PolicyFile = new FileItem();
                }
            }          
        }
        #endregion

        #region 文件操作  
        /// <summary>
        /// 获取文件键值
        /// </summary>
        /// <returns></returns>
        public string GetFileKey()
        {
            #region 上传文件
            string fileKey =FileUtils.GetUseKey(PolicyFile, InsuerId);
            if (string.IsNullOrEmpty(fileKey))
            {
                return fileKey;
            }
            if (!File.Exists(PolicyFile.Path))
            {
                return fileKey;
            }
            var bytes = File.ReadAllBytes(PolicyFile.Path);
            var flag = BllFactory<FileBll>.Instance.UploadFile(BllHttpSetting.Instance.Default, fileKey, bytes);
            if (!flag)
            {
                MessageTip.Show(this.GetWindow(), BllFactory<FileBll>.Instance.ErrorMessage ?? string.Empty);
            } 
            #endregion
            return fileKey;
        }
        #endregion
        #endregion
        #region 联系人相关
        /// <summary>
        /// 查询联系人信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="venderId"></param>
        private void LoadLinkerItem(string projectId, string venderId)
        {
            if (string.IsNullOrEmpty(projectId) || string.IsNullOrEmpty(venderId))
                return;
            var linkerItem = BllFactory<InsuerBll>.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;
            }

        }
        #endregion

        #region 保存资产相关
        private bool CreatePolicyAsset()
        {
            if (this.AssetItems == null || !this.AssetItems.Any())
                return true;
            //保单或保险商任意发生变化，都修改
            //判断当前保险单号，和item中的保险单号
            List<AssetShowItem> changedItems = new List<AssetShowItem>();
            foreach (var item in this.AssetItems)
            {
                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;
                WinPolicySaveEnsure win = new WinPolicySaveEnsure();
                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 修改厂商，保单号发生变化的资产
            
            AssetItems.ToList().ForEach(assetItem =>
            {
                assetItem.InsuerId = InsuerId;
                assetItem.InsurancePolicyNo = PolicyNo;
                assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.DPInsuerID)));
                 assetItem.CacheParameters.CheckAdd((new WatchParameter(MBIBuiltInParameter.InsuranceNum)));
            });
            bool flag = AssetManager.UpdateAssetItems(SystemProjectId, AssetItems.ToList());
            #endregion
            return flag;
            
        }
        /// <summary>
        /// 初始化变化参数
        /// </summary>
        /// <param name="item"></param>
        private WatchParameters GetChangeParameters(AssetShowItem item)
        {
            WatchParameters parameters = new WatchParameters();
            if (!string.IsNullOrEmpty(item.InsuerId)&&item.InsuerId!=InsuerId)
            {
                parameters.Add(new WatchParameter(MBIBuiltInParameter.DPInsuerID));
            }
            if (!string.IsNullOrEmpty(item.InsurancePolicyNo)&&item.InsurancePolicyNo!=PolicyNo)
            {
                parameters.Add(new WatchParameter(MBIBuiltInParameter.InsuranceNum));
            }
            return parameters;
        }
        #endregion

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