You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

536 lines
19 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Media;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevComponents.DotNetBar.Metro;
using NPoco;
using POSV.Component;
using POSV.Entity;
using POSV.Language;
using POSV.MessageEvent;
using POSV.Utils;
using System.Diagnostics;
using POSV.Chinaums;
using POSV.ShoppingCart;
using POSV.Helper;
using POSV.HttpApi;
namespace POSV
{
public partial class LoginForm : BaseForm
{
/// <summary>
/// 注册控件
/// </summary>
private RegisterControl _registerControl = null;
/// <summary>
/// 登录控件
/// </summary>
private LoginControl _loginControl = null;
/// <summary>
/// 是否需要注册
/// </summary>
private bool isRegisted = true;
/// <summary>
/// 门店计费信息
/// </summary>
Tuple<bool, string, PosAuth> response = null;
PosAuth posAuth = null;
public LoginForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (this.DesignMode) return;
this.Text = LangUtils.Instance.GetString("Application.Title");
//登陆工作区自动居中
this.mainPanel.Location = new Point((this.Width - this.mainPanel.Width) / 2 , (this.Height - this.mainPanel.Height - this.controlBox.Height) / 2);
//网络状态
this.controlBox.NetworkStatus = Global.Instance.Online;
//当前未登录状态
Global.Instance.IsLogin = false;
Task.Factory.StartNew(() =>
{
try
{
var status = ServiceHelper.CheckServiceStatus();
LOGGER.Info("服务中心运行状态:" + status.ToString());
ServiceHelper.StartService();
}
catch
{
}
//var client = MqttClientUtils.Instance;
}).ContinueWith(task =>
{
CheckFreeDiskSpace();
});
lock (Global.Instance.SyncLock)
{
//获取数据库存储的注冊数据
using (var db = Global.Instance.OpenDataBase)
{
Global.Instance.Authc = db.FirstOrDefault<Authc>(SqlConstant.AuthcQueryAll);
}
}
this.RefreshUi();
this.EditErrorWorker();
}
/// <summary>
/// 修复程序数据错误
/// </summary>
private void EditErrorWorker()
{
Task.Factory.StartNew(() =>
{
var lists = new List<OrderItem>();
lock (Global.Instance.SyncLock)
{
using (var db = Global.Instance.OpenDataBase)
{
using (var trans = db.GetTransaction())
{
//2018-06-03 解决饿了么数据不上传问题
//lists = db.Query<OrderItem>("where orderId in (select id from pos_order where syncStatus = 0 and orderType = 5)").ToList();
//foreach (OrderItem orderItem in lists)
//{
// orderItem.ProductId = string.Format("{0}", System.Math.Abs(StringUtils.GetInt(orderItem.ProductId)));
// orderItem.ProductNo = string.Format("{0}", System.Math.Abs(StringUtils.GetInt(orderItem.ProductNo)));
// orderItem.SpecId = string.Format("{0}", System.Math.Abs(StringUtils.GetInt(orderItem.SpecId)));
// db.Save<OrderItem>(orderItem);
//}
//2018-08-27 解决上传失败的单子重新上传
string sql = "update pos_order set syncStatus = 0 where uploadStatus = 2";
db.Execute(sql);
//检查索引
string sqlCheck = "PRAGMA integrity_check";
var checkStatus = db.ExecuteScalar<string>(sqlCheck);
//2019-01-31 解决索引损坏无法进行数据上传的问题,重置索引
if (!"ok".Equals(checkStatus))
{
LOGGER.Info("数据索引校验异常,等待修复");
var sw = new Stopwatch();
sw.Start();
string sqlindex = "REINDEX";
db.Execute(sqlindex);
sw.Stop();
LOGGER.Info("重置索引,耗时<{0}>", sw.ElapsedMilliseconds);
}
else {
LOGGER.Info("数据索引校验OK");
}
trans.Complete();
}
}
}
});
}
protected override void NetworkEventNotify(object sender , MsgEventArgs args)
{
base.NetworkEventNotify(sender , args);
if (IsDisposed || !this.IsHandleCreated) return;
//呈现联机更新状态
this.BeginInvoke(new MethodInvoker(() => {
this.controlBox.NetworkStatus = Global.Instance.Online;
}));
//string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , string.Format(@"template\wav\{0}.wav" , "meituan"));
//System.Media.SoundPlayer player = new System.Media.SoundPlayer(path);
//player.PlaySync();//另起线程播放
}
/// <summary>
/// 检查磁盘空间提醒
/// </summary>
private void CheckFreeDiskSpace()
{
try
{
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string diskName = baseDir.Substring(0, 1).ToUpper();//取首字母并转为大写
var space = HttpClientUtils.GetHardDiskFreeSpace(diskName);
if (space < 200)
{
if (this.IsDisposed || !this.IsHandleCreated) return;
this.Invoke(new Action(() =>
{
var msg = string.Format("当前磁盘可用空间{0}M磁盘空间已不足200M请尽快清理否则收银系统将无法运行", space);
MessageBox.Show(msg, "警告提醒");
Task.Factory.StartNew(() =>
{
Global.Instance.BugReport(new Exception(msg), "剩余磁盘空间不足200M");
});
}));
}
}
catch(Exception ex)
{
LOGGER.Error(ex, "登录获取门店剩余磁盘空间异常");
Global.Instance.BugReport(ex, "登录获取门店剩余磁盘空间异常");
}
}
private void RefreshUi()
{
//校验注册信息
this.isRegisted = Global.Instance.IsRegisted();
//没有注册
if (!this.isRegisted)
{
if (this._registerControl == null)
{
this._registerControl = new RegisterControl();
}
//注册成功通知事件
this._registerControl.Registed -= OnRegisted;
this._registerControl.Registed += OnRegisted;
this.mainPanel.Controls.Clear();
this.mainPanel.Controls.Add(this._registerControl);
this.mainPanel.AutoSize = true;
this._registerControl.Focus();
}
else
{
Task.Factory.StartNew(() =>
{
CheckNewVersion();
//var client = MqttClientUtils.Instance;
});
if (this._loginControl == null)
{
this._loginControl = new LoginControl();
}
//登录成功通知事件
this._loginControl.Succeed -= OnSucceed;
this._loginControl.Succeed += OnSucceed;
this.mainPanel.Controls.Clear();
this.mainPanel.Controls.Add(this._loginControl);
this.mainPanel.AutoSize = true;
this._loginControl.Focus();
//检测计费信息
CheckPosAuth();
}
if (this._registerControl != null)
{
this._registerControl.Visible = !isRegisted;
}
if (this._loginControl != null)
{
this._loginControl.Visible = isRegisted;
}
}
private void CheckPosAuth()
{
if (Global.Instance.Online)
{
//调用业务系统开放平台
response = LoginApi.PosAuth(Global.Instance.Authc.StoreId, Global.Instance.Authc.PosNo);
if (response.Item1) {
posAuth = response.Item3;
if (posAuth.CostMode ==0) {
try
{
lock (Global.Instance.SyncLock)
{
using (var db = Global.Instance.OpenDataBase)
{
using (var transaction = db.GetTransaction())
{
string sql = "update pos_store_info set dueDate ='{0}'";
sql = string.Format(sql, posAuth.DueDate);
db.Execute(sql, null);
transaction.Complete();
}
}
}
}
catch (Exception ex)
{
LOGGER.Error(ex);
}
//租赁模式剩余时间小于0天,禁止登陆系统
if (posAuth.AuthDays<0) {
Global.Instance.AuthLogin = false;
DialogForm.ShowAlert(this, "特别提示", "您的POS使用权限已过期,请联系代理商续费!");
}
else if (posAuth.AuthDays==30 || posAuth.AuthDays <= 7) {
//租赁模式(剩余时间小于30天或者剩余天数小于7天)弹出提醒
DialogForm.ShowAlert(this, "温馨提示", string.Format("您的POS剩余使用天数{0}天,过期将无法使用,请联系代理商续费!", posAuth.AuthDays));
}
}
}
}
else
{
StoreInfo storeInfo = null;
using (var db = Global.Instance.OpenDataBase)
{
storeInfo = db.FirstOrDefault<StoreInfo>("where id = @0", Global.Instance.Authc.StoreId);
}
if (storeInfo!=null && storeInfo.CostMode == 0)
{
int authDays = DateTimeUtils.DifferentDaysByMillisecond( storeInfo.DueDate, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
//租赁模式剩余时间小于0天,禁止登陆系统
if (authDays < 0)
{
Global.Instance.AuthLogin = false;
DialogForm.ShowAlert(this, "特别提示", "您的POS使用权限已过期,请联系代理商续费!");
}
else if (authDays == 30 || authDays <= 7)
{
//租赁模式(剩余时间小于30天或者剩余天数小于7天)弹出提醒
DialogForm.ShowAlert(this, "温馨提示", string.Format("您的POS剩余使用天数{0}天,过期将无法使用,请联系代理商续费", authDays));
}
}
}
}
private void CheckNewVersion()
{
try
{
//联机模式下,下载数据
if (Global.Instance.Online)
{
string autoUpdateFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , @"AutoUpdater.exe");
bool isNewAutoUpdate = false;
//当前内嵌自动更新的版本
string newAutoUpdateVersion = Properties.Resources.AutoUpdateVersion;
if (!File.Exists(autoUpdateFilePath))
{
isNewAutoUpdate = true;
}
else
{
LOGGER.Info("AutoUpdate Version:{0}", newAutoUpdateVersion);
FileVersionInfo info = FileVersionInfo.GetVersionInfo(autoUpdateFilePath);
//检测版本
Version oldVersion = new Version(info.ProductVersion);
Version newVersion = new Version(newAutoUpdateVersion);
if(newVersion > oldVersion)
{
File.Delete(autoUpdateFilePath);
isNewAutoUpdate = true;
}
}
if (isNewAutoUpdate)
{
string installerPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "AutoUpdater.exe");
File.WriteAllBytes(installerPath , Properties.Resources.AutoUpdater);
}
//有自动更新程序
if (File.Exists(autoUpdateFilePath) && Global.Instance.Authc != null)
{
//args = new string[] { "373001" , "00008" , "cy2" , "1", "x86" , "1.0.0" , "POSV.exe" };
//判断是否有新版本发布
string tenantId = Global.Instance.Authc.TenantId;
string storeNo = Global.Instance.Authc.StoreNo;
string posNo = Global.Instance.Authc.PosNo;
string appSign = Constant.APP_SIGN;
string versionType = "1";
string terminalType = Constant.TERMINAL_TYPE;
string versionNum = Application.ProductVersion;
string starter = Application.ProductName + ".exe";
string tenantType = Convert.ToString((int)Global.tenantVersionType);
string arguments = (tenantId + " " + storeNo + " " + posNo + " " + appSign + " " + versionType + " " + terminalType + " " + versionNum + " " + starter + " " + tenantType);
System.Diagnostics.Process.Start("AutoUpdater.exe" , arguments);
}
}
}
catch (Exception ex)
{
LOGGER.Error(ex , "检测新版本出现异常.....");
}
}
private void OnSucceed(object sender , SucceedEventArgs e)
{
Global.Instance.Worker = e.Worker;
//最后登陆日期
Global.Instance.Worker.LastDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
this.DialogResult = DialogResult.OK;
this.Close();
}
/// <summary>
/// POS注册成功通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnRegisted(object sender , RegistedEventArgs e)
{
try
{
Global.Instance.Authc = e.Authc;
}
catch (Exception ex)
{
LOGGER.Error(ex , "POS注册异常");
}
finally
{
this.RefreshUi();
}
}
private void OnMinimizedClick(object sender , EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void OnCloseClick(object sender , EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void OnSettingsClick(object sender , EventArgs e)
{
//校验注册信息,如果未注册,不允许响应初始化事件
this.isRegisted = Global.Instance.IsRegisted();
if (!isRegisted)
{
return;
}
bool isException = false;
Authc authc = null;
try
{
lock (Global.Instance.SyncLock)
{
using (var db = Global.Instance.OpenDataBase)
{
var lists = db.Query<Authc>().ToList();
if (lists != null && lists.Count > 0)
{
authc = lists.First();
}
}
}
}
catch (Exception ex)
{
LOGGER.Error(ex , "打开系统初始化异常");
isException = true;
}
finally
{
if(authc != null && !isException)
{
var confirm = new PasswdConfirm(authc);
confirm.AcceptButtonClick += (o , args) =>
{
if (args.Data is Tuple<bool , Authc>)
{
//执行成功
var result = args.Data as Tuple<bool , Authc>;
if (result.Item1)
{
var _authc = result.Item2;
_authc.CpuSerialNumber = string.Empty;
_authc.DiskSerialNumber = string.Empty;
_authc.MacAddress = string.Empty;
_authc.CompterName = string.Empty;
using (var db = Global.Instance.OpenDataBase)
{
using (var t = db.GetTransaction())
{
db.Update(_authc);
t.Complete();
}
}
//重置本地认证信息
Global.Instance.Authc = _authc;
this.RefreshUi();
}
}
};
var trans = new TransparentForm(this , 0.5 , confirm);
trans.Show();
}
}
}
}
}