
///////////////////////////////////////////////////////////////////////////////
//文件名称: VmBrandEditor.cs
//文件描述: 品牌编辑
//创 建 者: xls
//创建日期: 2018/5/23 23:18:32
//版 本 号：1.0.0.0
////////////////////////////////////////////////////////////////////////////////

using System;
using System.IO;
using System.Linq;
using System.Net.Cache;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Com.FirmLib.Bll;
using Com.FirmLib.Entity;
using Com.FirmLib.UI.Manufacturer.Model;
using FirmHttpDao;
using FWindSoft.DataFramework;
using FWindSoft.MVVM;
using FWindSoft.Wpf;
using Microsoft.Win32;
using SAGA.DotNetUtils.Data;

namespace Com.FirmLib.UI.Manufacturer
{
    public class VmBrandEditor : BaseViewModel
    {
        private int m_MaxSize = 1024 * 1024 * 2;
        public VmBrandEditor()
        {
            Init();
        }
        private void Init()
        {
            InputFile = new InputFile<UrlFile>();
            //为空可能引发遮罩异常
            ImageBrush = new ImageBrush();
        }
        public void Init(LoadParameter parameter)
        {
            if (parameter == null)
                return;
            var para = parameter.Parameter as BrandShowItem;
            if (para != null)
            {
                ManufacturerId = para.ManufacturerId;
                BrandId = para.Id;
                BranchName = para.Name;
            }
            LoadBrandItem(ManufacturerId, BrandId);
        }
        #region 属性相关
        public string ManufacturerId { get; set; }

        private string m_BranchName;
        /// <summary>
        /// 品牌名称
        /// </summary>
        public string BranchName
        {
            get { return this.m_BranchName; }
            set
            {
                this.m_BranchName = value;
                RaisePropertyChanged(() => this.BranchName);
            }
        }
        /// <summary>
        /// 上传文件输入
        /// </summary>
        public InputFile<UrlFile> InputFile { get;private set; }

        private ImageBrush m_ImageBrush;
        /// <summary>
        /// 图片画刷
        /// </summary>
        public ImageBrush ImageBrush
        {
            get { return this.m_ImageBrush; }
            set
            {
                this.m_ImageBrush = value;
                RaisePropertyChanged(() => this.ImageBrush);
            }
        }
        #endregion
        /// <summary>
        /// 是否使用Delete命令【使用布尔值，只是因为这个状态是高度抽象的，比枚举耦合性要小一些】
        /// </summary>
        public bool UseDelete { get; private set; }
        /// <summary>
        /// 添加产品
        /// </summary>
        public bool AddProduct { get; private set; }
        /// <summary>
        /// 添加新品牌Id
        /// </summary>
        public string BrandId { get; private set; }
        #region 命令相关
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void UploadCommand(object parameter)
        {

            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                //过滤上传图片的类型  
                ofd.Filter = "jpg图片|*.jpg|png图片|*.png|jpeg图片|*.jpeg|bmp图片|*.bmp";
                if (ofd.ShowDialog() == true)
                {
                    string fileName = ofd.FileName;
                    ImageSourceConverter isConverter = new ImageSourceConverter();
                    var bytes = File.ReadAllBytes(fileName);
                    if (bytes.Length > m_MaxSize)
                    {
                        MessageTip.Show("logo不能大于2M,如需要请重新选择");
                        return;
                    }
                    BitmapSource imageSource = (BitmapSource)isConverter.ConvertFrom(bytes);
                    ImageBrush = null;
                    ImageBrush = new ImageBrush(ImageUtil.GetCenterCropped(imageSource));
                    InputFile.Path = fileName;
                    InputFile.Content = bytes;
                    InputFile.AcceptContent();
                }
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanUploadCommand(object parameter)
        {
            return true;
        }
        /// <summary>
        /// 添加品牌完成
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddCommand(object parameter)
        {

            try
            {
                if (!AddBrand())
                    return;
                Window window = parameter as Window;
                if (window != null)
                    window.DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanAddCommand(object parameter)
        {
            return IsValidated;
        }


        /// <summary>
        /// 添加品牌，并添加产品
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void AddProductCommand(object parameter)
        {
            try
            {
                if (!AddBrand())
                    return;
                AddProduct = true;
                Window window = parameter as Window;
                if (window != null)
                    window.DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanAddProductCommand(object parameter)
        {
            return IsValidated;
        }
        /// <summary>
        /// 删除命令
        /// </summary>
        /// <param name="parameter"></param>
        [Command]
        public void DeleteCommand(object parameter)
        {
            try
            {
                if (!DeleteBrand())
                    return;
                UseDelete = true;
                Window window = parameter as Window;
                if (window != null)
                    window.DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageTipEx.Show(ex);
            }
        }
        public bool CanDeleteCommand(object parameter)
        {
            return true;
        }
        #endregion
        #region 私有方法
        /// <summary>
        /// 删除品牌
        /// </summary>
        /// <returns></returns>
        private bool DeleteBrand()
        {
            var result = MessageTip.Show(this.GetWindow(), "是否要删除", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                bool flag=BllFactory<BrandBll>.Instance.Delete(new BrandItem() { Id = BrandId });
                if (!flag)
                {
                    MessageTip.Show(this.GetWindow(), "删除失败");
                }

                return flag;
            }
            return false;
        }

        /// <summary>
        /// 增加/修改品牌
        /// </summary>
        /// <returns></returns>
        private bool AddBrand()
        {
            BrandItem item = new BrandItem();
            item.Id = BrandId ?? string.Empty;
            item.Name = this.BranchName;
            item.ManufacturerId = ManufacturerId;
            item.LogoKey = GetLogoKey();
            var result = false;
            if (string.IsNullOrEmpty(BrandId))
            {
                result=BllFactory<BrandBll>.Instance.Add(item);

                BrandId = item.Id;
            }
            else
            {
                result= BllFactory<BrandBll>.Instance.Update(item);
            }
            if (result)
            {
                BrandId = item.Id;
            }
            else
            {
                MessageTip.Show(this.GetWindow(), BllFactory<BrandBll>.Instance.ErrorMessage ?? string.Empty);
            }
            return result;
        } 

        //管理图片信息
        public void LoadBrandItem(string venderId,string brandId)
        {
            if (string.IsNullOrEmpty(brandId))
                return;
            var brandItem=BllFactory<BrandBll>.Instance.GetItem(venderId, brandId);
            if (brandItem == null)
                return;
            InputFile.Key=brandItem.LogoKey;
            if (!string.IsNullOrWhiteSpace(brandItem.LogoKey))
            {
                var urlFile = UrlFileKeyParse.ParseKey(InputFile.Key);
                InputFile.KeyEntity = urlFile;
                string imageUrl = BllFactory<FileBll>.Instance.CreateImageUrl(FileUrlValidateFactory.Create(urlFile.SystemId),urlFile.Key);
                BitmapSource bitmap = null;
                try
                {
                    byte[] bytes = BllFactory<FileBll>.Instance.DownLoadFile(imageUrl);                  
                    if (bytes != null)
                    {
                        ImageSourceConverter isConverter = new ImageSourceConverter();
                        bitmap = (BitmapSource)isConverter.ConvertFrom(bytes);
                        bitmap = (BitmapSource)ImageUtil.GetCenterCropped(bitmap);
                    }
                    else
                    {
                        bitmap = new BitmapImage(new Uri(imageUrl), new RequestCachePolicy(RequestCacheLevel.Reload));
                    }
                }
                catch (Exception e)
                {
                     bitmap = new BitmapImage(new Uri(imageUrl), new RequestCachePolicy(RequestCacheLevel.Reload));
                }
                ImageBrush = null;
                ImageBrush = new ImageBrush(bitmap);
            }

        }

        public string GetLogoKey()
        {
            if (InputFile.UpdateStatus == 0)
            {
                return InputFile.Key ?? string.Empty;
            }
            string fileKey = InputFile.KeyEntity?.Key;         
            if (InputFile.Content != null)
            {
                if (string.IsNullOrWhiteSpace(fileKey))
                {
                    fileKey = new TimeKeyBuilder().CreateKey();
                    #region 扩展名处理
                    if (!string.IsNullOrEmpty(InputFile.Path))
                    {
                        try
                        {
                            fileKey += Path.GetExtension(InputFile.Path);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    #endregion
                }

                var urlFile = UrlFileKeyParse.CreateImageUrlFile(fileKey);
                var flag = BllFactory<FileBll>.Instance.UploadImage(FileUrlValidateFactory.Create(urlFile.SystemId), urlFile.Key, InputFile.Content);
                if (!flag)
                {
                    MessageTip.Show(this.GetWindow(), BllFactory<FileBll>.Instance.ErrorMessage ?? string.Empty);
                }
                else
                {
                    InputFile.KeyEntity = urlFile;
                }
                
            }           
            return UrlFileKeyParse.CreatKey(InputFile.KeyEntity);
        }

        #endregion
    }
}
