using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Microsoft.Win32;
using Siger.Middlelayer.License.Models;
using Siger.Middlelayer.License.Utilities;

namespace Siger.Middlelayer.License.ViewModels
{
    public class GenrateViewModel: BaseViewModel
    {
        public ICommand ExecuteCommand { get; set; }

        public GenrateViewModel()
        {
            ExecuteCommand = new ButtonCommand(OnExecuteExecute);
        }

        #region 属性


        public string _companyId;

        public string CompanyId
        {
            get { return _companyId; }
            set
            {
                _companyId = value;
                OnPropertyChanged(CompanyId);
            }
        }

        public string _projectId;

        public string ProjectId
        {
            get { return _projectId; }
            set
            {
                _projectId = value;
                OnPropertyChanged(ProjectId);
            }
        }

        public string _startTime;

        public string StartTime
        {
            get { return _startTime; }
            set
            {
                _startTime = value;
                OnPropertyChanged(StartTime);
            }
        }

        public string _endTime;

        public string EndTime
        {
            get { return _endTime; }
            set
            {
                _endTime = value;
                OnPropertyChanged(EndTime);
            }
        }

        private string _machineCount;
        public string MachineCount
        {
            get
            {
                return _machineCount;
            }
            set
            {
                _machineCount = value;
                OnPropertyChanged(MachineCount);
            }
        }

        private string _userCount;
        public string UserCount
        {
            get
            {
                return _userCount;
            } 
            set
            {
                _userCount = value;
                OnPropertyChanged(UserCount);
            }
        }

        #endregion

        public void OnExecuteExecute(object o)
        {
            if (!CheckForm())
            {
                return;
            }
            try
            {
                var license = GenrateLicense();
                if (string.IsNullOrEmpty(license))
                {
                    ShowMessage("生成License失败！");
                    return;
                }
                //save to file and open folder for save
                SaveFilePathName(license);
            }
            catch (Exception e)
            {
                ShowMessage(e.Message);
            }
            finally
            {

            }
        }

        public void SaveFilePathName(string license)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "All files(*.*)|*.*",
                FileName = "License",
                DefaultExt = "license",
                AddExtension = true,
                FilterIndex = 2,
                RestoreDirectory = true
            };

            var result = saveFileDialog.ShowDialog();
            if (result != true) return;

            var localFilePath = saveFileDialog.FileName;
            var fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\", StringComparison.Ordinal) + 1);
            var filePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\", StringComparison.Ordinal));
            var newFileName = filePath + "\\" + fileNameExt;

            File.WriteAllText(newFileName, license);
            ShowMessage("生成成功！", MessageBoxImage.Information);
        }

        private bool CheckForm()
        {
            if (string.IsNullOrWhiteSpace(CompanyId))
            {
                ShowMessage("请输入企业Id！");
                return false;
            }
            if (string.IsNullOrWhiteSpace(ProjectId))
            {
                ShowMessage("请输入项目Id！");
                return false;
            }
            if (string.IsNullOrWhiteSpace(StartTime))
            {
                ShowMessage("请输入有效期开始日期！");
                return false;
            }
            if (string.IsNullOrWhiteSpace(EndTime))
            {
                ShowMessage("请输入有效期结束日期！");
                return false;
            }
            if(DateTime.Parse(StartTime) > DateTime.Parse(EndTime))
            {
                ShowMessage("有效期开始日期不能大于结束日期！");
                return false;
            }
            if (string.IsNullOrWhiteSpace(MachineCount))
            {
                ShowMessage("请输入最大设备数量！");
                return false;
            }

            if (!int.TryParse(MachineCount, out var machinecount))
            {
                ShowMessage("机台数量只能为整数！");
                return false;
            }

            if (machinecount <= 0)
            {
                ShowMessage("设备数量必须大于0！");
                return false;
            }
            if (string.IsNullOrWhiteSpace(UserCount))
            {
                ShowMessage("请输入最大用户数量！");
                return false;
            }

            if (!int.TryParse(UserCount, out var usercount))
            {
                ShowMessage("用户数量只能为整数！");
                return false;
            }

            if (usercount <= 0)
            {
                ShowMessage("用户数量必须大于0！");
                return false;
            }

            return true;
        }

        private string GenrateLicense()
        {
            var sb = new StringBuilder(1000);
            sb.Append("c|");
            sb.Append(_companyId);
            sb.Append("#p|");
            sb.Append(_projectId);
            sb.Append("#m|");
            sb.Append(_machineCount);
            sb.Append("#u|");
            sb.Append(_userCount);
            sb.Append("#t|");
            sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sb.Append("#start|");
            sb.Append(DateTime.Parse(_startTime).ToString("yyyy-MM-dd HH:mm:ss"));
            sb.Append("#end|");
            sb.Append(DateTime.Parse(_endTime).AddDays(1).AddMilliseconds(-1).ToString("yyyy-MM-dd HH:mm:ss"));
            var unEncryptStr = sb.ToString();
            var encryptStr = DesBuilder.Encrypt(unEncryptStr);
            return encryptStr == unEncryptStr ? string.Empty : encryptStr;
        }

        private void ShowMessage(string message, MessageBoxImage image = MessageBoxImage.Warning)
        {
            MessageBox.Show(message, "西格数据", MessageBoxButton.OK, image);
        }
    }
}
