
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmSimplePolicyEditor.cs
//文件描述: VmSimplePolicyEditor.cs
//创 建 者: xls
//创建日期: 2018/9/17 23:19:01
//版 本 号：1.0.0.0
////////////////////////////////////////////////////////////////////////////////

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

namespace Com.FirmLib.UI.Insuer
{
    public class VmSimplePolicyEditor : BaseViewModel
    {
       
        public VmSimplePolicyEditor()
        {
            Init();
        }

        private void Init()
        {

        }
        public void Init(LoadParameter parameter)
        {
            PolicyUpdateContext context = parameter.Parameter as PolicyUpdateContext;
            if (context == null)
                return;
            Context = context;
            ProjectId = context.InsuerParameter.Project.Id;
            VenderId = context.InsuerParameter.Insuer.Id;
            this.OriginPolicyNo = context.PolicyNo;
            this.PolicyNo = context.PolicyNo ;
        }
        #region 相关历史记录
        private PolicyUpdateContext Context { get; set; }
        /// <summary>
        /// 项目Id
        /// </summary>
        public string ProjectId { get; set; }
        /// <summary>
        /// 厂商id
        /// </summary>
         public string VenderId { get; set; }
        /// <summary>
        /// 原始保险单号
        /// </summary>
        private string OriginPolicyNo { get; set; }
        #endregion

        #region 属性相关

        private string m_PolicyNo;
        /// <summary>
        /// 保单编号
        /// </summary>
        public string PolicyNo
        {
            get { return this.m_PolicyNo; }
            set
            {
                this.m_PolicyNo = value;
                if (!IsInEditing)
                {
                    LoadPolicyByNo(value);
                }               
                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 ValidatePolicy { get; private set; }
        #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;
                    this.PolicyFile.Name = Path.GetFileName(fileName);
                    this.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 SelectPolicyCommand(object parameter)
        {

            try
            {
                //传入当前输入的保单号，为显示默认值
                WinPolicySelector win = new WinPolicySelector();
                LoadParameter.StartParameter(win, new LoadParameter(Context.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 true;
        }


        /// <summary>
        /// 确定按钮
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void EnsureCommand(object parameter)
        {
            try
            {
                Window window = parameter as Window;
                if (window == null)
                    return;
                var flag = CreatePolicyInfo();
                if (!flag)
                {
                    return;
                }
                UpdateContetxt();
                window.SetRealResult<PolicyUpdateContext>(Context);
                window.DialogResult = true;
            }
            catch (Exception ex)
            {
               MessageTipEx.Show(ex);
            }
        }
        public bool CanEnsureCommand(object parameter)
        {
            return true;
        }

        #endregion
        #region 私有方法
        /// <summary>
        /// 加载保单信息
        /// </summary>
        /// <param name="policyNo"></param>
        private void LoadPolicyByNo(string policyNo)
        {
            InsuerContractItem item = null;
            string fileKey = string.Empty;
            try
            {
                ValidatePolicy = false;
                if (string.IsNullOrEmpty(policyNo))
                    return;
                item = BllFactory<InsuerBll>.Instance.GetPolicyItem(VenderId, 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();
                }
            }
        }

        /// <summary>
        /// 判断是否使用编辑方式控制
        /// </summary>
        /// <returns></returns>
        private bool UseEditTypeControl()
        {
            if(string.IsNullOrEmpty(this.OriginPolicyNo))
               return false;
            if (this.OriginPolicyNo == this.PolicyNo)
                return false;
            return true;
        }
        /// <summary>
        /// 更新信息
        /// </summary>
        private void UpdateContetxt()
        {
            if (Context == null)
                return;
            Context.PolicyNo = this.PolicyNo;
            Context.ExpiryDate = this.PolicyEndDate;
            Context.PolicyFile = this.PolicyFile?.FileKey;
            Context.UseEditType = UseEditTypeControl();
        }
        /// <summary>
        /// 创建保单信息
        /// </summary>
        /// <returns></returns>
        private bool CreatePolicyInfo()
        {
            InsuerContractItem item = new InsuerContractItem();
            item.ProjectId = ProjectId;
            item.VenderId = VenderId;

            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 != VenderId)
                {
                    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;
        }
        /// <summary>
        /// 获取文件键值
        /// </summary>
        /// <returns></returns>
        public string GetFileKey()
        {
            #region 上传文件
            string fileKey = FileUtils.GetUseKey(PolicyFile, VenderId);
            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
    }
}
