using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using Muchinfo.MTPClient.Account.ViewModels;
using Muchinfo.MTPClient.Account.ViewModels.AllOrderViewModel;
using Muchinfo.MTPClient.Account.Views;
using Muchinfo.MTPClient.CustomException;
using Muchinfo.MTPClient.Data;
using Muchinfo.MTPClient.Data.DTO;
using Muchinfo.MTPClient.Data.Enums;
using Muchinfo.MTPClient.Data.Model;
using Muchinfo.MTPClient.Data.Model.Account;
using Muchinfo.MTPClient.Data.Model.GoodRules;
using Muchinfo.MTPClient.Data.Model.Message;
using Muchinfo.MTPClient.Infrastructure.Cache;
using Muchinfo.MTPClient.Infrastructure.Helpers;
using Muchinfo.MTPClient.Infrastructure.LinkProxy;
using Muchinfo.MTPClient.Infrastructure.MessageBox;
using Muchinfo.MTPClient.Infrastructure.Users;
using Muchinfo.MTPClient.Infrastructure.Utilities;
using Muchinfo.MTPClient.Infrastructure.Windows;
using Muchinfo.MTPClient.IService;
using Muchinfo.MTPClient.Resources;
using Muchinfo.MTPClient.Service.Utilities;
using Muchinfo.MTPClient.Trade.ViewModels;
using Muchinfo.MTPClient.UI.Utilities;
using Muchinfo.MTPClient.UI.Views;
using Muchinfo.PC.Common.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace Muchinfo.MTPClient.UI.ViewModels
{
///
/// HomePageViewModel类
///
public class HomeViewModel : ViewModelBase
{
#region Fields
private bool _isClosePower;//是否有平仓权限
private ObservableCollection _mainMenuItems;
private Visibility _statusBarVisibility;
private Visibility _toolBarVisibility;
private IAnnouncementService _announcementService;
private ILoginService _loginService;
private int _oldTabIndex;
private ISystemService _systemService;
private IDeliveryService _deliveryService;//交割服务-》查询交割关系列表
private Dictionary _resxVerInfos; ////服务端资源版本
private IOrderService _orderService;
private ICommonQueryService _commonQueryService;
#endregion Fields
#region Constructors
///
/// Initializes a new instance of the class.
///
/// 系统服务
public HomeViewModel(ISystemService service)
{
//初始化命令
InitializeCommands();
_toolBarVisibility = Visibility.Visible;
_statusBarVisibility = Visibility.Visible;
_announcementService = SimpleIoc.Default.GetInstance();
_loginService = SimpleIoc.Default.GetInstance();
SystemName = ApplicationParameter.TradeSystemName;
_deliveryService = SimpleIoc.Default.GetInstance();
_systemService = service;
_orderService = SimpleIoc.Default.GetInstance();
_commonQueryService = SimpleIoc.Default.GetInstance();
ApplicationParameter.MakePublishNetIp();
//消息注册
RegisterMessenger();
if (UserManager.IsAccountLogin) ////已交易登录
{
TradeDataInit();
}
else
{ ////游客没有交易菜单
CreateLoaclMenu(new List());
}
}
#endregion Constructors
#region Properties
#region Public Properties
private RelayCommand _ftenCommand;
///
/// Gets the FtenCommand.
///
public RelayCommand FtenCommand
{
get
{
return _ftenCommand
?? (_ftenCommand = new RelayCommand(
() =>
{
var FtenAddress = ApplicationParameter.FtenAddress;
if (!string.IsNullOrEmpty(FtenAddress))
{
MessengerHelper.DefaultSend(TabContetMode.QuoteGoodsInfo, MessengerTokens.ChangeGoodsInfo);
}
}));
}
}
///
/// 当前使用的样式
///
public Object CurrentStyle
{
get;
set;
}
public string TradeTypeDisplay
{
get
{
return string.Empty;
//var isConfigVersion = ConfigurationManager.AppSettings["IsMockTrade"];
//return isConfigVersion == "0" ? " - 模拟盘" : " - 实盘";
}
}
///
/// 系统名称
///
public string SystemName { get; set; }
///
/// 获取和设置the main menu items
///
public ObservableCollection MainMenuItems
{
get
{
return _mainMenuItems;
}
set
{
Set(() => MainMenuItems, ref _mainMenuItems, value);
}
}
///
/// 获取和设置the menu command
///
public RelayCommand MenuCommand
{
get;
private set;
}
///
/// Gets or sets the name of the user.
///
public Visibility StatusbarVisibility
{
get { return _statusBarVisibility; }
set
{
Set(() => StatusbarVisibility, ref _statusBarVisibility, value);
}
}
///
/// Gets or sets the name of the user.
///
public Visibility ToolbarVisibility
{
get { return _toolBarVisibility; }
set
{
Set(() => ToolbarVisibility, ref _toolBarVisibility, value);
}
}
///
/// 主窗体是否隐藏
///
private Visibility _mainPanelVisibility = Visibility.Collapsed;
public Visibility MainPanelVisibility
{
get { return _mainPanelVisibility; }
set
{
Set(() => MainPanelVisibility, ref _mainPanelVisibility, value);
}
}
#region 快速下单
public RelayCommand OrderTransactionCommand
{
get
{
return new RelayCommand((commandParameter) => Task.Factory.TryStartNew(() =>
{
}));
}
}
#endregion
///
/// 是否为已使用交易账号登录
///
public bool IsAccountLogin
{
get { return UserManager.IsAccountLogin; }
}
///
/// 是否顯示功能樹
///
public bool IsTreeVbs
{
get { return UserManager.IsAccountLogin && IsTradeVisible; }
}
private bool _isBusy;
///
/// 是否忙
///
public bool IsBusy
{
get { return _isBusy; }
set { Set(() => IsBusy, ref _isBusy, value); }
}
#endregion Public Properties
private bool _isTradeVisible = true;
///
/// 是否显示交易数据
///
public bool IsTradeVisible
{
get { return _isTradeVisible; }
set
{
Set(() => IsTradeVisible, ref _isTradeVisible, value);
var defaultLayout = UserManager.GetCurrentLayoutStyle();
MainLayoutUpdate(defaultLayout);
}
}
///
/// 是否保存布局
///
public bool IsSaveLayout
{
get;
set;
}
///
/// 是否显示期货组件
///
private Visibility _quoteVisibility = Visibility.Hidden;
public Visibility QuoteVisibility
{
get { return _quoteVisibility; }
set
{
Set(() => QuoteVisibility, ref _quoteVisibility, value);
}
}
///
/// 是否显示WEB浏览器组件
///
private Visibility _webBrowerVisibility = Visibility.Visible;
public Visibility WebBrowerVisibility
{
get { return _webBrowerVisibility; }
set
{
Set(() => WebBrowerVisibility, ref _webBrowerVisibility, value);
}
}
#endregion Properties
#region Methods
#region Private Methods
///
/// 构建本地菜单
///
/// 交易菜单
private void CreateLoaclMenu(List accessItems)
{
_systemService = SimpleIoc.Default.GetInstance();
_orderService = SimpleIoc.Default.GetInstance();
MainMenuItems = _systemService.GetSysMenuItems(accessItems, MenuCommand);
var toolMenu = _mainMenuItems.FirstOrDefault(z => z.Title == MenuNames.Tools);
if (toolMenu == null || toolMenu.Children == null || !toolMenu.Children.Any()) return;
var toolBarItem = toolMenu.Children.FirstOrDefault(z => z.SysCommandType == MenuCommandType.Toolbar);
if (toolBarItem != null) ToolbarVisibility = toolBarItem.IsChecked ? Visibility.Visible : Visibility.Collapsed;
var statusBarItem = toolMenu.Children.FirstOrDefault(z => z.SysCommandType == MenuCommandType.Statusbar);
if (statusBarItem != null) StatusbarVisibility = statusBarItem.IsChecked ? Visibility.Visible : Visibility.Collapsed;
}
///
/// 消息注册
///
private void RegisterMessenger()
{
MessengerHelper.DefaultRegister(this, MessengerTokens.MainPanelIsUnlock, MainPanelIsEnableMethod);
MessengerHelper.DefaultRegister(this, MessengerTokens.InitLockTimer, InitLockTimer);
MessengerHelper.DefaultRegister(this, MessengerTokens.SelectGoodsChange, SelectGoodsChange);
MessengerHelper.DefaultRegister(this, MessengerTokens.SelectGoodsOrderChange, SelectGoods);
MessengerHelper.DefaultRegister(this, MessengerTokens.SelectCommissionGoodsChange, SelectCommissionGoodsChange);
//注册快捷下单消息
MessengerHelper.DefaultRegister(this, MessengerTokens.ShowQueryContet, (view) =>
{
QueryView = view;
});
MessengerHelper.DefaultRegister(this, MessengerTokens.OrderRefresh, OrderViewRefresh);
MessengerHelper.DefaultRegister(this, MessengerTokens.SetHideExpandTradeToken, SetHideTradeMsg);
MessengerHelper.DefaultRegister(this, MessengerTokens.CancelOrderEnable, (isEnable) =>
{
//var tradeFunc = UserManager.TradeFuncMenus.FirstOrDefault((item) => item.FuncMenuCode == UserManager.GetMenuCommandValue(MenuCommandType.Cancel));
var tradeFunc = UserManager.TradeFuncMenus.FirstOrDefault((item) => item.FuncMenuCode == MenuCommandType.Cancel.ToString());
if (tradeFunc != null)
{
tradeFunc.IsEnabled = isEnable;
}
});
MessengerHelper.DefaultRegister(this, MessengerTokens.OrderMessage, SetOrderView);
}
///
/// 选择某个商品
///
///
private void SelectGoods(QuoteGoodsForSelectOrder goods)
{
if (goods == null)
{
return;
}
if (goods.IsSelect)
{
if (ApplicationParameter._LockType == LockType.Lock &&
UserManager.GetCurrentLayoutStyle() == LayoutStyle.Tradition)
{
return;
}
}
SelectedQuoteGoods = goods.QuoteGoods;
if (IsAccountLogin && (SelectedQuoteGoods.ContainsGoodsSrc & (int)GoodsFromScr.Trade) > 0) //交易商品可下单
{
////处理点击会卡的问题
Task.Factory.TryStartNew(() =>
{
var viewModel = new TradeOrderViewModel(SelectedQuoteGoods, Direction.Bid);
SetOrderView(viewModel);
});
}
}
///
/// 选择商品改变
///
/// The goods.
private void SelectGoodsChange(QuoteGoodsDTO goods)
{
var quoteGoods = CacheManager.CacheGoodsBaseInfos.FirstOrDefault((item) => item.Symbol == goods.Symbol);
// bool showChart;
if (quoteGoods != null)
{
//todo:
//if (goods.GoodsParameters.TradeMode == TradeModeType.BidGoods)
//{
// showChart = ApplicationParameter.ShowChart == 2; //设置竞价商品才显示图表
//}
QuoteGoodsForSelectOrder orderGoods = new QuoteGoodsForSelectOrder
{
IsSelect = true,
QuoteGoods = quoteGoods
};
SelectGoods(orderGoods);
}
//IsShowChart = ApplicationParameter.ShowChart == 1 || showChart;
}
///
/// 选择五档买卖商品改变
///
/// The goods.
private void SelectCommissionGoodsChange(QuoteGoodsDTO goods)
{
var quoteGoods = CacheManager.CacheGoodsBaseInfos.FirstOrDefault((item) => item.Symbol == goods.Symbol);
if (quoteGoods != null)
{
SelectedCommissionQuoteGoods = quoteGoods;
}
}
///
/// 设置是否展开交易信息
///
///
private void SetHideTradeMsg(bool result)
{
IsTradeVisible = result;
}
private FrameworkElement _queryView;
///
/// 查询面板显示的内容
///
public FrameworkElement QueryView
{
get { return _queryView; }
set
{
if (_queryView != null && value.Equals(_queryView))
{
return;
}
else
{
if (_queryView != null)
{
var queryPanel = _queryView.DataContext as QueryPanelModelBase;
if (queryPanel != null)
{
queryPanel.UnRegisterMessage();
}
}
}
Set(() => QueryView, ref _queryView, value);
var newQueryPanel = value.DataContext as QueryPanelModelBase;
if (newQueryPanel != null)
{
newQueryPanel.RegisterMessage();
}
}
}
private FrameworkElement _mainContent;
///
/// 布局内容显示
///
public FrameworkElement MainContent
{
get { return _mainContent; }
set { Set(() => MainContent, ref _mainContent, value); }
}
///
/// 选择的商品
///
public QuoteGoods SelectedQuoteGoods { get; set; }
///
/// 选择的商品
///
public QuoteGoods SelectedCommissionQuoteGoods { get; set; }
///
/// 更新单据窗口的内容
///
///
private void OrderViewRefresh(string update)
{
//下方查询界面显示方式修改后此方法无效,要刷新单据须在各自界面注册消息OrderViewRefresh去实现 --dyp
if (QueryView != null && QueryView.DataContext is IOrderRefresh)
{
(QueryView.DataContext as IOrderRefresh).Refresh();
}
///刷新后-重新查询交割关系列表--pending by dk
// _deliveryService.QueryRelationPAndXGoodsInfoList(QueryAllDeliveryRelationSuccess, null);
}
///
///
/// 设置撤单是否可用
///
///
private void SetCancelItemEable(bool isEnable)
{
var menuItem = _mainMenuItems.FirstOrDefault((item) => item.Title == MenuNames.Trading);
if (menuItem == null) return;
var canelItem = menuItem.Children.FirstOrDefault((cItem) => cItem.Title == MenuNames.OrderCancel);
if (canelItem == null) return;
//var accountManager = SimpleIoc.Default.GetInstance();
}
///
/// Executes the command.
///
/// The item.
private void ExecuteCommand(SysMenuItem item)
{
CacheManager.FromType = eOrderFormType.Commom; //顶部买卖按钮与挂牌无关
var goods = this.SelectedQuoteGoods;
switch (item.SysCommandType)
{
#region 系统
case MenuCommandType.Reconnect:
if (MessageBoxHelper.ShowQuestion(Muchinfo.MTPClient.Resources.Client_Resource.UI2014_IsOrNotReconnect,
Muchinfo.MTPClient.Resources.Client_Resource.UI2014_Tips) == MessageBoxResult.Yes)
{
if (UserManager.IsAccountLogin)
{
////保存布局及列表行情抬头
MessengerHelper.DefaultSend(string.Empty, MessengerTokens.SaveLayout);
//手动发送登出消息
var service = SimpleIoc.Default.GetInstance();
if (service != null) service.TradeAccountLogout(UserManager.CurrentTradeAccount);
}
WindowHelper.RerunApplication();
}
break;
case MenuCommandType.ChangeTradePassword:
//非强制修改密码
MessengerHelper.DefaultSend(true, MessengerTokens.ShowModifyPwd);
break;
case MenuCommandType.Horizontal:
SetInitializeCheck(item);
MainLayoutUpdate(LayoutStyle.Horizontal);
break;
case MenuCommandType.Vertical:
SetInitializeCheck(item);
MainLayoutUpdate(LayoutStyle.Vertical);
break;
case MenuCommandType.Tradition:
SetInitializeCheck(item);
MainLayoutUpdate(LayoutStyle.Tradition);
break;
case MenuCommandType.Logout:
OnClose();
break;
case MenuCommandType.CoolBlack:
SetInitializeCheck(item);
ThemesUpdate(ColorStyle.CoolBlack);
break;
//case MenuCommandType.White:
// break;
//case MenuCommandType.SkyBlue:
// SetInitializeCheck(item);
// ThemesUpdate(ColorStyle.SkyBlue);
// break;
//case MenuCommandType.DarkRed:
// SetInitializeCheck(item);
// ThemesUpdate(ColorStyle.DarkRed);
// break;
case MenuCommandType.DarkBlue:
SetInitializeCheck(item);
ThemesUpdate(ColorStyle.DarkBlue);
break;
case MenuCommandType.BlueWhite:
SetInitializeCheck(item);
ThemesUpdate(ColorStyle.BlueWhite);
break;
case MenuCommandType.LockScreen:
this.IsLockScreen = true;
break;
#endregion
#region 分析
case MenuCommandType.CandleChart:
if (goods == null) return;
// WindowHelper.OpenQuoteChartWindow(new OpenQuoteChartWindowArg(goods, CycleType.Minute));
break;
case MenuCommandType.TimeSharingChart:
if (goods == null) return;
// WindowHelper.OpenQuoteChartWindow(new OpenQuoteChartWindowArg(goods, CycleType.TimeSharing));
break;
case MenuCommandType.TikChart:
if (goods == null) return;
// WindowHelper.OpenQuoteChartWindow(new OpenQuoteChartWindowArg(goods, CycleType.Tik));
break;
case MenuCommandType.TradeDetails:
if (goods == null) return;
//PriceCardHelper.OpenSubPenDetail(goods);
break;
case MenuCommandType.TikDetails:
if (goods == null) return;
//PriceCardHelper.OpenSubPriceDetail(goods);
break;
case MenuCommandType.F10:
//todo:
break;
case MenuCommandType.MA:
//todo:
break;
case MenuCommandType.BOLL:
//todo:
break;
case MenuCommandType.MACD:
//todo:
break;
case MenuCommandType.DMI:
//todo:
break;
case MenuCommandType.OBV:
//todo:
break;
case MenuCommandType.VOL:
//todo:
break;
case MenuCommandType.RSI:
//todo:
break;
case MenuCommandType.KDJ:
//todo:
break;
case MenuCommandType.CCI:
//todo:
break;
case MenuCommandType.BIAS:
//todo:
break;
case MenuCommandType.PSY:
//todo:
break;
case MenuCommandType.MTM:
//todo:
break;
case MenuCommandType.WR:
//todo:
break;
case MenuCommandType.MultiCycles:
//todo:
break;
case MenuCommandType.MultiGoodses:
//todo:
break;
case MenuCommandType.ComparisonGoodes:
//todo:
break;
#endregion
#region 交易
case MenuCommandType.BuyIn:
//建仓
var openOrder = new OrderMessage() { Direction = Direction.Bid, OrderPriceMode = ePriceMode.PRICEMODE_MARKET };
MessengerHelper.DefaultSend(openOrder, MessengerTokens.OrderMessageToken);
break;
case MenuCommandType.Sellout:
//平仓
var order = new OrderMessage() { Direction = Direction.Ask, OrderPriceMode = ePriceMode.PRICEMODE_MARKET };
MessengerHelper.DefaultSend(order, MessengerTokens.OrderMessageToken);
break;
case MenuCommandType.Cancel:
//撤单
if (ViewModelLocator.MOrderDetails.CanCancelOrderDetial())
{
// ViewModelLocator.MOrderDetails.CancelAllHoldingCammand.Execute(null);
ViewModelLocator.MOrderDetails.CancelHoldingCammand.Execute(null);
}
else
{
MessageBoxHelper.ShowQuestion(Muchinfo.MTPClient.Resources.Client_Resource.UnSupportOrderTypes, Muchinfo.MTPClient.Resources.Client_Resource.Models_CancelBillTips);
}
break;
case MenuCommandType.SaleApply:
var sale = new OrderMessage() { Direction = Direction.Bid, OrderPriceMode = ePriceMode.PRICEMODE_MARKET };
MessengerHelper.DefaultSend(sale, MessengerTokens.OrderMessageToken);
break;
case MenuCommandType.DeliveryApply:
//交收申请
MessengerHelper.DefaultSend(UserManager.CurrentTradeAccount, MessengerTokens.DeliveryDeclare);
break;
case MenuCommandType.ReportQuery:
//报表查询
MessengerHelper.DefaultSend(UserManager.CurrentTradeAccount, MessengerTokens.AccountReport);
break;
case MenuCommandType.TradeLogin:
var login = new TradeLoginView()
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
ShowInTaskbar = false,
};
if (login.ShowDialog() == true)
{
TradeDataInit(); ////交易账号登录
}
break;
//case MenuCommandType.TradeSettings:
// MessengerHelper.DefaultSend(UserManager.CurrentTradeAccount, MessengerTokens.TraderingParamSet);
// break;
#endregion
#region 帮助
//case MenuCommandType.UserGuide:
// break;
case MenuCommandType.EscapeClause:
var v = new AboutView(1);
v.Owner = Application.Current.MainWindow;
v.WindowStartupLocation = WindowStartupLocation.CenterOwner;
v.ShowDialog();
break;
case MenuCommandType.OfficalWeb:
if (string.IsNullOrWhiteSpace(ApplicationParameter.WebSite))
{
MessageBoxHelper.ShowInfo(Muchinfo.MTPClient.Resources.Client_Resource.UI2014_NoOfficialWebsitePleaseConfigurationFile, Muchinfo.MTPClient.Resources.Client_Resource.UI2014_ConfigurationError);
}
else
{
var proc = new Process { StartInfo = { FileName = ApplicationParameter.WebSite } };
proc.Start();
}
break;
//case MenuCommandType.OnlineCS:
// break;
case MenuCommandType.AboutUs:
var t = new AboutView(2)
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
t.ShowDialog();
break;
#endregion
#region 风管云平台
case MenuCommandType.Manage:
// 现货
QuoteVisibility = Visibility.Hidden;
WebBrowerVisibility = Visibility.Visible;
break;
#endregion
case MenuCommandType.MarketQuote:
case MenuCommandType.SelectedGoodses:
MessengerHelper.DefaultSend(item, MessengerTokens.ChangeMarket);
// 期货
QuoteVisibility = Visibility.Visible;
WebBrowerVisibility = Visibility.Hidden;
break;
default:
if (item.Command != null) ////默认实现自带操作的命令
{
item.Command.Execute(null);
}
break;
}
}
///
/// Initializes the commands.
///
private void InitializeCommands()
{
MenuCommand = new RelayCommand((item) =>
{
if (item == null || (item.Children != null && item.Children.Any())) return;
ExecuteCommand(item);
});
}
#region 快捷键
private RelayCommand _keyCommand;
///
/// 初始化命令
///
public RelayCommand KeyCommand
{
get
{
if (_keyCommand != null)
{
return _keyCommand;
}
_keyCommand = new RelayCommand((command) =>
{
ExecuteKeyCommand(command);
});
return _keyCommand;
}
}
///
/// 执行命令
///
///
private void ExecuteKeyCommand(CommandFunc command)
{
if (this.IsLockScreen) ////锁屏时不执行命令
{
return;
}
var curMode = ViewModelLocator.MainContent.TabContetMode;
switch (command)
{
case CommandFunc.OpenOrder:
if (CanCommandEnable(MenuCommandType.BuyIn) &&
UserManager.QuotationWindowType == TabContetMode.QuoteList)
{
var order = new OrderMessage()
{
Direction = Direction.Bid,
OrderPriceMode = ePriceMode.PRICEMODE_MARKET
};
MessengerHelper.DefaultSend(order, MessengerTokens.OrderMessageToken);
}
break;
case CommandFunc.OpenChart:
MessengerHelper.DefaultSend(TabContetMode.QuoteChart, MessengerTokens.MainContentChange);
break;
case CommandFunc.BrowserBack: ////返回行情列表,在行情列表则提示是否退出
var mode = ViewModelLocator.MainContent.TabContetMode;
if (mode == TabContetMode.QuoteList)
{
OnClose();
}
else
{
MessengerHelper.DefaultSend(TabContetMode.QuoteList, MessengerTokens.MainContentChange);
}
break;
case CommandFunc.QuoteInsert:
if ((curMode == TabContetMode.QuoteList || curMode == TabContetMode.QuoteBoard) &&
SelectedQuoteGoods != null)
{
if (ApplicationParameter.ShowChart == 1 || !UserManager.IsAccountLogin) ////游客登录也可看图表
{
//如果是在内容行上双击, 打开分析图表窗口
//MessengerHelper.DefaultSend(new OpenQuoteChartWindowArg(QuoteListDataGrid.SelectedItem as QuoteGoods, CycleType.Minutes1),
// MessengerTokens.OpenQuoteChartWindow);
MessengerHelper.DefaultSend(TabContetMode.QuoteChart, MessengerTokens.MainContentChange);
}
}
break;
case CommandFunc.QuotePageDown:
case CommandFunc.QuotePageup:
if (curMode == TabContetMode.QuoteList || curMode == TabContetMode.QuoteChart)
{
MessengerHelper.DefaultSend(command, MessengerTokens.QuoteGoodsListToken);
}
break;
case CommandFunc.GoodsF10:
var FtenAddress = ApplicationParameter.FtenAddress;
if (!string.IsNullOrEmpty(FtenAddress))
{
MessengerHelper.DefaultSend(TabContetMode.QuoteGoodsInfo,
MessengerTokens.ChangeGoodsInfo);
}
break;
case CommandFunc.Tab:
if (UserManager.GetCurrentLayoutStyle() == LayoutStyle.Tradition)
{
MessengerHelper.DefaultSend(true, MessengerTokens.SetOrderFoucsToken);
}
break;
case CommandFunc.Amount:
MessengerHelper.DefaultSend(MenuCommandType.AccountInfo, MessengerTokens.MenuSelectChange);
break;
case CommandFunc.HoldDetail:
MessengerHelper.DefaultSend(MenuCommandType.Position, MessengerTokens.MenuSelectChange);
break;
case CommandFunc.CompleteOrder:
MessengerHelper.DefaultSend(MenuCommandType.TransactionOrder, MessengerTokens.MenuSelectChange);
break;
case CommandFunc.QuoteTik:
if (SelectedQuoteGoods != null &&
(SelectedQuoteGoods.TradeMode == eTradeMode.TRADEMODE_BIDDING ||
SelectedQuoteGoods.TradeMode == eTradeMode.TRADEMODE_MARKETMAKE ||
SelectedQuoteGoods.TradeMode == eTradeMode.TRADEMODE_BIDDINGMARKETMAKE))
{
MessengerHelper.DefaultSend(SelectedQuoteGoods, MessengerTokens.ShowTikDetail);
}
MessengerHelper.DefaultSend(MenuCommandType.AccountInfo, MessengerTokens.MenuSelectChange);
break;
case CommandFunc.Buy:
var tradeView = SimpleIoc.Default.GetInstance();
if (tradeView.CanCommandEnable(MenuCommandType.BuyIn))
{
tradeView.BuyCommand.Execute(null);
}
break;
case CommandFunc.Sell:
var tradeViewsell = SimpleIoc.Default.GetInstance();
if (tradeViewsell.CanCommandEnable(MenuCommandType.Sellout))
{
tradeViewsell.SellCommand.Execute(null);
}
break;
case CommandFunc.Cancel:
var orderView = SimpleIoc.Default.GetInstance();
orderView.SearchOrderStatus = SearchOrderStatus.OnMarket;
MessengerHelper.DefaultSend(MenuCommandType.EntrustOrder, MessengerTokens.MenuSelectChange);
break;
case CommandFunc.OpenTradeBoard:
IsTradeVisible = !IsTradeVisible;
break;
case CommandFunc.TranFloatOrder:
break;
default:
break;
}
}
///
/// 命令类型
///
///
///
public bool CanCommandEnable(MenuCommandType commandType)
{
if (UserManager.TradeFuncMenus != null && UserManager.TradeFuncMenus.Any())
{
var tradeFunc = UserManager.TradeFuncMenus.FirstOrDefault((item) => item.FuncMenuCode == commandType.ToString());
if (tradeFunc != null)
{
return tradeFunc.IsEnabled;
}
}
return false;
}
///
/// 初始化键命令
///
///
public List InitKeysCommand()
{
return _systemService.GetHomeKeyBindings(KeyCommand);
}
#endregion
///
/// 将菜单的同级结点选择状态设置为False
///
/// 设置选择状态的菜单
private void SetInitializeCheck(SysMenuItem item)
{
if (item.ParentItem != null)
{
foreach (var childItem in item.ParentItem.Children)
{
childItem.IsChecked = false;
}
}
item.IsChecked = true;
SaveUserConfig(item); //只有设置布局的方可使用该方法
}
///
/// 保存用户主题布局
///
/// 设置的菜单
private void SaveUserConfig(SysMenuItem item)
{
switch (item.SysCommandType)
{
case MenuCommandType.Vertical:
////保存配置
UserManager.SaveCurrentLayoutStyle(LayoutStyle.Vertical);
break;
case MenuCommandType.Horizontal:
////保存配置
UserManager.SaveCurrentLayoutStyle(LayoutStyle.Horizontal);
break;
case MenuCommandType.Tradition:
////保存配置
UserManager.SaveCurrentLayoutStyle(LayoutStyle.Tradition);
break;
case MenuCommandType.CoolBlack:
////保存配置
UserManager.SaveCurrentColorStyle(ColorStyle.CoolBlack);
break;
case MenuCommandType.BlueWhite:
////保存配置
UserManager.SaveCurrentColorStyle(ColorStyle.BlueWhite);
break;
case MenuCommandType.DarkBlue:
////保存配置
UserManager.SaveCurrentColorStyle(ColorStyle.DarkBlue);
break;
default:
break;
}
}
///
/// 设置系统主题
///
public void InitializeThemes()
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
var defaultLayout = UserManager.GetCurrentLayoutStyle();
MainLayoutUpdate(defaultLayout);
var defaultColor = UserManager.GetCurrentColorStyle();
ThemesUpdate(defaultColor);
}));
}
///
/// 切换主题加载资源
///
///
private void ThemesUpdate(ColorStyle colorStyle)
{
string themesType;
switch (colorStyle)
{
case ColorStyle.CoolBlack:
themesType = "CoolBlack";
break;
//case ColorStyle.SkyBlue:
// themesType = "SkyBlue";
// break;
//case ColorStyle.DarkRed:
// themesType = "DarkRed";
// break;
case ColorStyle.DarkBlue:
themesType = "DarkBlue";
break;
case ColorStyle.BlueWhite:
themesType = "BlueWhite";
break;
default:
themesType = "DarkBlue";
break;
}
string url = string.Format("/Client.Main;component/Themes/{0}/Style.xaml", themesType);
var resource = (ResourceDictionary)Application.LoadComponent(new Uri(url, UriKind.Relative));
if (CurrentStyle != null && Application.Current.Resources.MergedDictionaries.Contains(CurrentStyle))
{
Application.Current.Resources.MergedDictionaries.Remove(CurrentStyle as ResourceDictionary);
}
else
{
for (int i = 0; i < Application.Current.Resources.MergedDictionaries.Count; i++)
{
var resourceDic = Application.Current.Resources.MergedDictionaries[i];
if (resourceDic != null)
{
resourceDic.Clear();
}
}
// Application.Current.Resources.MergedDictionaries.Clear();
}
//if (ApplicationParameter.DataGridColor == "0") //显示纯色
//{
// resource.Add("MuchinfoBrush35", System.Windows.Media.Brushes.Transparent);
// resource.Add("MuchinfoBrush36", System.Windows.Media.Brushes.Transparent);
//}
Application.Current.Resources.MergedDictionaries.Add(resource);
CurrentStyle = resource;
MessengerHelper.DefaultSend(themesType, MessengerTokens.RegisterResourceChange);
////主題变化时强制通知商品颜色改变
MessengerHelper.DefaultSend(true, MessengerTokens.NotifyQuoteGoodsColorChanged);
}
private void MainLayoutUpdate(LayoutStyle layout)
{
LogInfoHelper.WriteInfo("Starting MainLayoutUpdate......");
try
{
switch (layout)
{
case LayoutStyle.Horizontal:
MainContent = new HorizontalLayout();
break;
case LayoutStyle.Vertical:
MainContent = new VerticalLayout();
break;
case LayoutStyle.Tradition:
MainContent = new TraditionLayout();
break;
default:
MainContent = new HorizontalLayout();
break;
}
LogInfoHelper.WriteInfo("end MainLayoutUpdate,begin send Message MessengerTokens.UpdateLayoutChange");
MessengerHelper.DefaultSend(layout, MessengerTokens.UpdateLayoutChange);
}
catch (Exception ex)
{
LogInfoHelper.WriteInfo("布局异常..." + ex.ToString());
}
}
///
/// Called when [close].
///
private void OnClose()
{
if (MessageBoxHelper.ShowQuestion(Muchinfo.MTPClient.Resources.Client_Resource.UI2014_IsOrNotExit,
Muchinfo.MTPClient.Resources.Client_Resource.UI2014_Tips) == MessageBoxResult.Yes)
{
if (UserManager.IsAccountLogin)
{
////保存布局及列表行情抬头
MessengerHelper.DefaultSend(string.Empty, MessengerTokens.SaveLayout);
//手动发送登出消息
var service = SimpleIoc.Default.GetInstance();
if (service != null) service.TradeAccountLogout(UserManager.CurrentTradeAccount);
}
WindowHelper.RerunApplication(false);
}
}
private void MainPanelIsEnableMethod(bool mainPanelIsUnlock)
{
if (mainPanelIsUnlock == true)
{
WindowCollection list = Application.Current.Windows;
foreach (Window w in list)
{
if (w.Owner == null)
{
MainPanelVisibility = Visibility.Collapsed;
}
else
{
w.WindowState = WindowState.Normal;
w.Opacity = 1;
}
}
}
else
{
MainPanelVisibility = Visibility.Visible;
}
}
#endregion Private Methods
#region 公告处理
///
/// 查询是否有未读公告
///
/// 数据列表
protected void NoticeCountSuccess(List itemList)
{
if (itemList != null && itemList.Any())
{
var notice = itemList.FirstOrDefault((item) => item.MsgType == MsgTypeEnum.Bulletin && item.MsgCount > 0);
if (notice != null) //弹出公告
{
MessengerHelper.DefaultSend(notice.MsgType, MessengerTokens.AnnouncementMessage);
return; //不用两个都弹出来
}
var notify = itemList.FirstOrDefault((item) => item.MsgType == MsgTypeEnum.NTF && item.MsgCount > 0);
if (notify != null) //弹出消息
{
MessengerHelper.DefaultSend(notify.MsgType, MessengerTokens.AnnouncementMessage);
}
}
}
protected void QueryErrorCallback(ErrorEntity errorEntity)
{
//IsBusy = false;
//Application.Current.Dispatcher.BeginInvoke(new Action(() =>
//{
// ErrorManager.ShowReturnError(errorEntity, Muchinfo.MTPClient.Resources.Client_Resource.APP_Tips, false);
//}));
}
#endregion
#region 下单
///
/// 下单类型
///
/// 下单模型
private void SetOrderView(TradeOrderViewModel tradeViewModel)
{
IsOrderVisible = true;
TradeViewModel = tradeViewModel;
}
//ViewLoadedCommand = new RelayCommand((MainPage) =>
//{
// view.MainPanel.Children.Clear();
// UserManager.UserManagerCurrentMarketType = MenuCommandType.CustomQuote;
// UserManager.QuotationWindowType = QuotationWindowType.Board;
// _oldTabIndex = 9;
// WindowHelper.OpenDefaultQuoteListView(false);
//});
private bool _isOrderVisible;
///
/// 是否显示下单
///
public bool IsOrderVisible
{
get { return _isOrderVisible; }
set { Set(() => IsOrderVisible, ref _isOrderVisible, value); }
}
private TradeOrderViewModel _tradeViewModel;
///
/// 下单逻辑
///
public TradeOrderViewModel TradeViewModel
{
get { return _tradeViewModel; }
set { Set(() => TradeViewModel, ref _tradeViewModel, value); }
}
#endregion
#region 交易登录初始化
///
/// 交易数据初始化
///
private void TradeDataInit()
{
IsBusy = true;
////初始化我的自选
FavoriteManager.InitializeFavorite(MenuNames.QuotationFavorite);
//先查询市场信息,再查询商品信息
ulong lastUpdateTimeUTC = CacheManager.GetLastUpdateTimeBy(Muchinfo.MTPClient.Data.Enums.LastUpdateTimeType.MarketsUTime);
if (MarketResxManager.MarketResx.ResourceHashtable == null || MarketResxManager.MarketResx.Version != lastUpdateTimeUTC)
{
_loginService.MarketsQuerySearch(lastUpdateTimeUTC, MarketsInfoCallBack, ErrorEntityCallBack);
}
else
{
MarketsInfoModel[] marketsArr = Newtonsoft.Json.JsonConvert.DeserializeObject(Newtonsoft.Json.JsonConvert.SerializeObject(MarketResxManager.MarketResx.ResourceHashtable.Values));
List marketLst = marketsArr.ToList();
CacheManager.LoadMarketInfoList(marketLst);
MarketsInfoCallBack(marketLst, 0, false);
}
SearchDeliveryGoods();
}
///
/// ///查询交割关系列表-成功返回
///
private void QueryAllDeliveryRelationSuccess(List itemList)
{
Muchinfo.MTPClient.Infrastructure.Cache.CacheManager.AllDeliveryRelationList = itemList;
}
private void SearchAllGoodsUnitCallBack(List goodUnit)
{
Muchinfo.MTPClient.Infrastructure.Cache.CacheManager.TradeGoodsUnit = goodUnit;
foreach (var quoteGoods in CacheManager.CacheGoodsBaseInfos)
{
quoteGoods.AgreeUnitDisplay = quoteGoods.GoodsParameters.AgreeUnit.ToString() + CacheManager.TradeGoodsUnit.Where(x => x.UNITID == quoteGoods.GoodsParameters.AgreeUnitType).Select(x => x.GOODSUNITNAME).FirstOrDefault();
}
}
///
/// 查询失败
///
///
private void ErrorEntityCallBack(ErrorEntity error)
{
LogInfoHelper.WriteInfo("MarketsQuerySearch or GoodsQuerySearch or GoodsGroup callback Failed");
IsBusy = false;
InitComplete();
FuncMenusErrorFunc(error);
}
private void AccountBaseInfoInitError(ErrorEntity error)
{
var format = "查询账号基本信息:" + string.Format(ErrorManager.FormatErrorMsg(error));
LogInfoHelper.WriteInfo(format);
////清除链路
// LinkManager.Instance.Dispose();
}
///
/// 市场成功查询MTP2.0
///
///
public void MarketsInfoCallBack(List MarketsInfoList, ulong marketStamp = 0, bool bUpdate = true)
{
//登陆后基本数据查询
_loginService.LoginQuerySearch(UserManager.CurrentTradeAccount.LoginID, LoginQueryType.All, LoadAccountBaseInfoCallback, AccountBaseInfoInitError);
if (bUpdate)
{
//如果是调用接口更新的系统参数,需要更新对应的本地文件
var hashtable = new Hashtable();
foreach (var market in MarketsInfoList)
{
hashtable.Add(market.MarketID, market);
}
MarketResxManager.SaveMarketResx(hashtable, marketStamp, UserManager.UserDataFolder);
}
}
///
/// 商品成功查询MTP2.0
///
/// The goods information list.
/// The goods stamp.
/// if set to true [b update].
/// The mid parameter.
public void GoodsInfoCallBack(List GoodsInfoList, ulong goodsStamp = 0, bool bUpdate = true, List midParam = null)
{
if (bUpdate)
{
//如果是调用接口更新的系统参数,需要更新对应的本地文件
var hashtable = new Hashtable();
foreach (var goods in GoodsInfoList)
{
hashtable.Add(goods.GoodsCode, goods);
}
GoodsResxManager.SaveGoodsResx(hashtable, goodsStamp, UserManager.UserDataFolder);
}
////创建行情链路, 链路成功后订阅商品
//LinkManager.Instance.CreateQuoteTcpLink();
//查询交易端配置的菜单--菜单权限从服务端不使用缓存
ulong menuUTime = CacheManager.GetLastUpdateTimeBy(Muchinfo.MTPClient.Data.Enums.LastUpdateTimeType.MenuUTime);
_loginService.QueryAccountFuncMenu(menuUTime, midParam, FuncMenusSuccess, FuncMenusErrorFunc);
//改成串行下载数据
/*
////查询商品组信息
//_loginService.QueryGoodsGroup(null, ErrorEntityCallBack);
////外部交易所查询
//_loginService.QueryExternalExchange(ExternalExchangeCallBack, ErrorEntityCallBack);
////查询持仓汇总
//var queryList = new List
//{
// new QueryCommonParam() {ParamKey = "accountId", ParamValue = UserManager.CurrentTradeAccount.FundsAccountId + string.Empty}
//};
//_orderService.QueryHoldingPosistion(QueryStatement.TradePositionDetail, queryList, QuerySuccessCallBack, QueryErrorCallback);
//_commonQueryService.QueryMarketRun(0, MarketRunQuerySuccessCallBack, QueryErrorCallback);
*/
}
///
/// Markets the run query success call back.
///
/// The models.
private void MarketRunQuerySuccessCallBack(List models)
{
// 这里需要把所属母账户也带上 <- 又不用带了……
var fundsAccountIDs = string.Join(",", UserManager.CurrentTradeAccount.FundsAccountIds);
//if (UserManager.CurrentTradeAccount.FundsAccounts.Count > 0 && UserManager.CurrentTradeAccount.FundsAccounts[0].ParentAccountID != 0)
//{
// fundsAccountIDs += string.Format(",{0}", UserManager.CurrentTradeAccount.FundsAccounts[0].ParentAccountID);
//}
// 查询账户汇率模板
_commonQueryService.QueryTradeRateTmpConfig(fundsAccountIDs, null, QueryErrorCallback);
// 查询外部汇率模版配置表
//_commonQueryService.QueryExtenalTradeRateTmpConfig(fundsAccountIDs, DateTime.Now.ToString("yyyyMMdd"), null, QueryErrorCallback);
// 查询资金账户汇率
//_commonQueryService.QueryTaAccountExchangeRate(fundsAccountIDs, null, QueryErrorCallback);
CacheManager.UpdateMarketRun(models);
}
///
/// 外部交易所查询成功调用
///
///
private void ExternalExchangeCallBack(List externalExchages)
{
////查询交易端配置的菜单
List exchangeLst = new List();
foreach (var exchange in externalExchages)
{
var newExchanage = new Exchange
{
ExchangeId = exchange.AutoID,
ExchangeCode = exchange.ExExchangeCode,
ExchangeName = exchange.ExExchangeName,
IsMarketPrice = exchange.IsMarketPrice
};
exchangeLst.Add(newExchanage);
}
//使用外部交易所做为交易所缓存
CacheManager.LoadExchangeInfo(exchangeLst);
//重新构建分类菜单
MessengerHelper.DefaultSend(UserManager.CurrentTradeAccount, MessengerTokens.UpdateQuoteMarket);
//查询持仓汇总
var queryList = new List
{
new QueryCommonParam() {ParamKey = "accountId", ParamValue = UserManager.CurrentTradeAccount.FundsAccountId + string.Empty}
};
_orderService.QueryHoldingPosistion(QueryStatement.TradePositionDetail, queryList, QuerySuccessCallBack, ErrorEntityCallBack);
CreateLoaclMenu(UserManager.AccessFuncMenus);
}
///
/// Queries the success call back.
///
/// The orders.
private void QuerySuccessCallBack(List orders)
{
_commonQueryService.QueryMarketRun(0, MarketRunQuerySuccessCallBack, ErrorEntityCallBack);
}
///
/// 构建菜单
///
///
private void FuncMenusSuccess(List funcs, ulong menuUTime, List GoodsRuleLst, bool update = true)
{
UserManager.LocalFuncMenus = eSystemMenuValue.CreateInstance().menu;//实例化本地菜单数据;
UserManager.FixedFuncMenus = eSystemMenuValue.CreateInstance().fixedMenuList;
List menus;
try
{
//可使用菜单为 本地固定菜单+服务端获取的且终端已实现的菜单 - dyp
menus = UserManager.FixedFuncMenus.Union(funcs.Where(z => UserManager.LocalFuncMenus.Select(t => t.Value).Contains(z.FuncMenuCode))).ToList();
//对菜单进行排序 - dyp
menus.Sort((x, y) => { return x.SortId > y.SortId ? 1 : (x.SortId == y.SortId ? 0 : -1); });
}
catch
{
menus = new List();
}
//更新交集的菜单
if (update)
{
var hashtable = new Hashtable();
foreach (var menu in menus)
{
hashtable.Add(menu.FuncMenuCode, menu);
}
MenuResxManager.SaveMenuResx(hashtable, menuUTime, UserManager.UserDataFolder);
}
UserManager.AccessFuncMenus = menus;
// ////是否可看
// GetDepositPlan();
// ////更新市场菜单
//// MessengerHelper.DefaultSend(UserManager.CurrentTradeAccount, MessengerTokens.UpdateQuoteMarket);
CreateLoaclMenu(menus);
if (menus != null && menus.Any())
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
ViewModelLocator.MenuTree.LoadMenus(menus);
//缓存 -交易商品的费用计算方式,与交易规则
CacheManager.TradeGoodsFeeRules = GoodsRuleLst.ToArray().ToDictionary(key => key.GoodsID, value => value);
///todo:保存在缓存中
IsBusy = false;
InitComplete();
}));
}
//查询商品组信息
_loginService.QueryGoodsGroup(null, ErrorEntityCallBack);
//外部交易所查询
_loginService.QueryExternalExchange(ExternalExchangeCallBack, ErrorEntityCallBack);
}
///
/// 错误处理
///
/// 错误内容
private void FuncMenusErrorFunc(ErrorEntity error)
{
var funcs = new List();
UserManager.LocalFuncMenus = eSystemMenuValue.CreateInstance().menu;//实例化本地菜单数据;
UserManager.FixedFuncMenus = eSystemMenuValue.CreateInstance().fixedMenuList;
funcs.AddRange(UserManager.FixedFuncMenus);
UserManager.AccessFuncMenus = funcs;
CreateLoaclMenu(funcs); ////查询不到菜单时显示默认
if (funcs != null && funcs.Any())
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
ViewModelLocator.MenuTree.LoadMenus(funcs);
}));
}
}
#endregion
#region 私有方法
///
/// 登录后初始化内容
///
/// 与账号相关基本信息
private void LoadAccountBaseInfoCallback(AccountBaseInfoModel accountInfo)
{
ulong lastUpdateTimeUTC = CacheManager.GetLastUpdateTimeBy(Muchinfo.MTPClient.Data.Enums.LastUpdateTimeType.GoodsUTime);
if (GoodsResxManager.GoodsResx.ResourceHashtable == null || GoodsResxManager.GoodsResx.Version != lastUpdateTimeUTC)
{
_loginService.GoodsInfoSearch(lastUpdateTimeUTC, accountInfo.GoodsRuleAndFeeList, GoodsInfoCallBack, ErrorEntityCallBack);
}
else
{
QuoteGoods[] quoteGoodsArr = Newtonsoft.Json.JsonConvert.DeserializeObject(Newtonsoft.Json.JsonConvert.SerializeObject(GoodsResxManager.GoodsResx.ResourceHashtable.Values));
var goodsLst =quoteGoodsArr == null? new List(): quoteGoodsArr.OrderBy(z=>z.GoodsCode).ToList();
CacheManager.LoadGoodsInfoList(goodsLst, GoodsFromScr.Trade);
GoodsInfoCallBack(goodsLst, 0, false, accountInfo.GoodsRuleAndFeeList);
}
}
private void InitComplete()
{
//创建行情链路, 链路成功后订阅商品
// LinkManager.Instance.CreateQuoteTcpLink();
//进入主界面后再开户断线重连机制
LinkManager.Instance.StartReconnect();
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
//设置系统主题
InitializeThemes();
InitLockTimer();///启动锁屏
////公告查询处理(处理先显示公告时,样式不一致)--pendding dk
// _announcementService.QueryNoticeCount(UserManager.CurrentTradeAccount.AccountId, NoticeCountSuccess, QueryErrorCallback);
////更新市场菜单
MessengerHelper.DefaultSend(UserManager.CurrentTradeAccount, MessengerTokens.UpdateQuoteMarket);
MessengerHelper.DefaultSend(true, MessengerTokens.CheckTokenMsg); ///同步时间
SimpleIoc.Default.GetInstance().InitMainPanel(); ////主界面内容 更新
RaisePropertyChanged(() => IsAccountLogin);
Task.Factory.TryStartNew(() =>
{
//var random = new Random();
//var seconds = random.Next(2000, 10000); ////随机时间再取资源信息
//var seconds = random.Next(1, 10); ////随机时间再取资源信息
//Thread.Sleep(seconds);
//获取资源版本号
//_systemService.QueryResxVer(ResxVerSuccess, QueryResxVerError);
if (CacheManager.CacheLastUpdateTimeList != null)
{
SearchErrorResxAndConstResx();
SearchRiskMsgResx();
}
});
}));
}
///
/// 查询数据库错误资源和常量资源信息
///
private void SearchErrorResxAndConstResx()
{
ulong errorCodeTimeUTC = CacheManager.GetLastUpdateTimeBy(Muchinfo.MTPClient.Data.Enums.LastUpdateTimeType.ErrorcodeUTime);
if (MuchinfoException.ErrorResx.ResourceHashtable == null || MuchinfoException.ErrorResx.Version != errorCodeTimeUTC)
{
//错误码字典查询 MTP2.0
_loginService.ErrorCodeQuerySearch(errorCodeTimeUTC, ErrorCodeResxCallback, QueryResxVerError);
}
ulong constTimeUTC = CacheManager.GetLastUpdateTimeBy(Muchinfo.MTPClient.Data.Enums.LastUpdateTimeType.DirctionaryUTime);
if (ConstResxManager.ConstResx.ResourceHashtable == null || ConstResxManager.ConstResx.Version != constTimeUTC)
{
//枚举常量字典查询 MTP2.0
_loginService.DictionaryQuerySearch(constTimeUTC, ConstCodeResxCallback, QueryResxVerError);
}
}
private void SearchDeliveryGoods()
{
ulong DeliveryGoodsUTime = CacheManager.GetLastUpdateTimeBy(Muchinfo.MTPClient.Data.Enums.LastUpdateTimeType.DvGoodsUTime);
if (DeliveryResxManager.DeliveryResx.ResourceHashtable == null || DeliveryResxManager.DeliveryResx.Version != DeliveryGoodsUTime)
{
//错误码字典查询 MTP2.0
_loginService.DeliveryGoodsQuerySearch(DeliveryGoodsUTime, DeliveryGoodsCallback, DeliveryGoodsError);
}
else
{
DeliveryGoodsInfoModel[] deliveryGoodsArr = Newtonsoft.Json.JsonConvert.DeserializeObject(Newtonsoft.Json.JsonConvert.SerializeObject(DeliveryResxManager.DeliveryResx.ResourceHashtable.Values));
List retLst = deliveryGoodsArr.ToList();
CacheManager.CacheDeliveryGoodsInfo = retLst;
}
}
private void DeliveryGoodsCallback(List retLst, ulong DeliveryGoodsUTime = 0, bool bUpdate = true)
{
if (bUpdate)
{
//如果是调用接口更新的系统参数,需要更新对应的本地文件
var hashtable = new Hashtable();
foreach (var deliveryGoods in retLst)
{
hashtable.Add(deliveryGoods.DeliveryGoodsCode, deliveryGoods);
}
DeliveryResxManager.SaveDeliveryResx(hashtable, DeliveryGoodsUTime, UserManager.UserDataFolder);
}
CacheManager.CacheDeliveryGoodsInfo = retLst;
}
private void DeliveryGoodsError(ErrorEntity errorEntity)
{
var format = "交割商品查询" + string.Format(ErrorManager.FormatErrorMsg(errorEntity));
LogInfoHelper.WriteInfo(format);
}
///
/// 错误资源成功回调
///
///
private void ErrorCodeResxCallback(List descritions, ulong errCodeStamp)
{
Task.Factory.TryStartNew(() =>
{
var hashtable = new Hashtable();
foreach (var desc in descritions)
{
hashtable.Add(desc.ErrorCode, desc.ErrorMsg);
}
MuchinfoException.ErrorResxSaveRep(hashtable, errCodeStamp);
});
}
///
/// 常量资源成功回调
///
///
private void ConstCodeResxCallback(List descritions, ulong constStamp)
{
Task.Factory.TryStartNew(() =>
{
var hashtable = new Hashtable();
foreach (var desc in descritions)
{
hashtable.Add(desc.FieldCode + "_" + desc.Key, desc.Value);
}
ConstResxManager.ConstResxSaveRep(hashtable, constStamp, UserManager.UserDataFolder);
});
}
private void ResxVerSuccess(List resxVer)
{
if (resxVer != null && resxVer.Any())
{
_resxVerInfos = resxVer.ToDictionary((item) => item.Versiontype);
if (_resxVerInfos.ContainsKey(ResxVerType.errorCode))
{
if (MuchinfoException.ErrorResx == null || MuchinfoException.ErrorResx.Version < _resxVerInfos[ResxVerType.errorCode].Versionno)
{
_systemService.QueryResxDescrition(ResxVerType.errorCode, ResxCallback, QueryResxVerError);
}
}
if (_resxVerInfos.ContainsKey(ResxVerType._const))
{
if (ConstResxManager.ConstResx == null || ConstResxManager.ConstResx.Version < _resxVerInfos[ResxVerType._const].Versionno)
{
_systemService.QueryResxDescrition(ResxVerType._const, ResxCallback, QueryResxVerError);
}
}
}
}
///
/// 查询资源回调
///
///
private void ResxCallback(List descritions, ResxVerType varType)
{
Task.Factory.TryStartNew(() =>
{
var hashtable = new Hashtable();
foreach (var desc in descritions)
{
hashtable.Add(desc.ConstKey, desc.Remarks);
}
if (varType == ResxVerType._const)
{
ConstResxManager.ConstResxSaveRep(hashtable, _resxVerInfos[varType].Versionno, UserManager.UserDataFolder);
}
else if (varType == ResxVerType.errorCode)
{
MuchinfoException.ErrorResxSaveRep(hashtable, _resxVerInfos[varType].Versionno);
}
});
}
private void QueryResxVerError(ErrorEntity errorEntity)
{
var format = "资源" + string.Format(ErrorManager.FormatErrorMsg(errorEntity));
LogInfoHelper.WriteInfo(format);
}
#region 风险协议书获取
///
/// 封装获取风险协议书的方法,如有更新就调用接口重新获取
///
private void SearchRiskMsgResx()
{
ulong riskMsgTimeUTC = CacheManager.GetLastUpdateTimeBy(Muchinfo.MTPClient.Data.Enums.LastUpdateTimeType.RiskMsgUTime);
if (RiskMsgResxManager.RiskMsgResx.ResourceHashtable == null || RiskMsgResxManager.RiskMsgResx.Version != riskMsgTimeUTC)
{
//错误码字典查询 MTP2.0
_loginService.RiskTipQuerySearch(riskMsgTimeUTC, RiskMsgResxCallback, QueryResxVerError);
}
}
private void RiskMsgResxCallback(RiskTipQueryRspModel risktip, ulong risktipStamp = 0)
{
Task.Factory.TryStartNew(() =>
{
var hashtable = new Hashtable();
hashtable.Add(risktip.TipTitle, risktip);
RiskMsgResxManager.SaveRiskMsgResx(hashtable, risktipStamp, UserManager.UserDataFolder);
});
}
#endregion
#endregion Methods
#region 锁屏
private bool _isLockScreen;
///
/// 是否锁屏
///
public bool IsLockScreen
{
get { return _isLockScreen; }
set
{
Set(() => IsLockScreen, ref _isLockScreen, value);
}
}
///
/// 锁屏方式
///
public bool LockScreenType
{
get
{
return ApplicationParameter.IsShowBGLockSreen == 1;
}
}
///
/// 锁屏定时器
///
private DispatcherTimer _dispatcherTimer;
private void InitLockTimer(bool result)
{
InitLockTimer();
}
///
/// 初始化锁屏
///
private void InitLockTimer()
{
var userInfo = UserManager.GetCurrentUserInfo(); ////交易菜单设置
int time = 0;
if (userInfo.TradeParams == null)
{
time = ApplicationParameter.LockSreenTime;
}
else
{
time = userInfo.TradeParams.LockScreenTime;
}
if (_dispatcherTimer != null)
{
_dispatcherTimer.Stop();
}
// 目前暂时不显示锁屏
time = 0;
if (time > 0 && UserManager.IsAccountLogin) ////配置了时间才进行锁屏
{
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += _dispatcherTimer_Tick;
int i = 100;
_dispatcherTimer.Interval = new TimeSpan(0, 0, i);
_dispatcherTimer.Start();
}
}
private string _password;
///
/// 密码
///
public string Password
{
get { return _password; }
set { Set(() => Password, ref _password, value); }
}
private string _errorMsg;
///
/// 错误消息
///
public string ErrorMsg
{
get { return _errorMsg; }
set { Set(() => ErrorMsg, ref _errorMsg, value); }
}
private void _dispatcherTimer_Tick(object sender, EventArgs e)
{
var userInfo = UserManager.GetCurrentUserInfo(); ////交易菜单设置
int time = 0;
if (userInfo.TradeParams == null)
{
time = ApplicationParameter.LockSreenTime;
}
else
{
time = userInfo.TradeParams.LockScreenTime;
}
var LastInputTime = GetLastInputInfoHelper.GetLastInputTime();
if (LastInputTime >= time)
{
#if DEBUG
Console.WriteLine("时间:" + LastInputTime);
#endif
WindowCollection list = Application.Current.Windows;
foreach (Window w in list)
{
if (w == Application.Current.MainWindow) ////主窗口
{
////切换到行情列表 , 其他浏览器控件
MessengerHelper.DefaultSend(TabContetMode.QuoteList, MessengerTokens.MainContentChange);
}
else
{
w.Close(); ////关其他窗口
}
}
_dispatcherTimer.Stop();
IsLockScreen = true; ////显示锁屏
MessengerHelper.DefaultSend(false, MessengerTokens.LockScreenSetHideExpandTradeToken);
//var lockScreen=new LockScreenWin(){Owner = Application.Current.MainWindow,WindowStartupLocation =WindowStartupLocation.CenterOwner };
//lockScreen.ShowDialog();
}
}
public RelayCommand UnLockCommand
{
get
{
return new RelayCommand(() =>
{
if (Vailed())
{
ErrorMsg = string.Empty;
var password = EncryptHelper.SHA256(UserManager.CurrentTradeAccount.LoginID.ToString() + Password).ToLower();
if (password.Equals(UserManager.CurrentTradeAccount.Md5Password))
{
IsLockScreen = false;
Password = string.Empty;
if (_dispatcherTimer == null)
{
if (ApplicationParameter.LockSreenTime > 0 && UserManager.IsAccountLogin) ////配置了时间才进行锁屏
{
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += _dispatcherTimer_Tick;
int i = 100;
_dispatcherTimer.Interval = new TimeSpan(0, 0, i);
_dispatcherTimer.Start();
}
}
else
{
_dispatcherTimer.Start();
}
MessengerHelper.DefaultSend(true, MessengerTokens.LockScreenSetHideExpandTradeToken);
}
else
{
//ErrorMsg = Client_Resource.Lock_loginpasswordError;
MessageBoxHelper.ShowInfo(Client_Resource.Lock_loginpasswordError, Client_Resource.UI2014_Tips, true);
}
}
});
}
}
public RelayCommand LoginOutCommand
{
get
{
return new RelayCommand(() =>
{
this.OnClose();
});
}
}
private bool Vailed()
{
if (string.IsNullOrWhiteSpace(Password) || Password.Length < 6)
{
MessageBoxHelper.ShowInfo(Client_Resource.UI2014_AccountNotLessThan6Characters, Client_Resource.UI2014_Tips, true);
return false;
}
return true;
}
#endregion
#endregion
}
}