using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Platform.Presentation.Interfaces;
using Platform.Presentation.PageFunctions;
using TellerSystem.Communication;
using TellerSystem.Library.Ext.Function;
using System.Windows;
using System.Windows.Controls;
using Platform.Controls.ControlsHelper;
using TellerSystem.ServiceProxy.Ext.ServiceEntitys;
using System.Xml;
using TellerSystem.ServiceProxy.Ext.ServiceHelper;
using Platform.Common.RunningParameters;
using TellerSystem.Library.Ext.Variables;
using Platform.Library;
using TellerSystem.Library.Ext.TradeExtension;
using TellerSystem.Contract.ContractBase;
using System.Windows.Controls.Primitives;
using System.IO;
using System.Windows.Media;
using System.Globalization;
using System.Windows.Media.Imaging;
using System.Reflection;
using TellerSystem.ServiceProxy.Ext.WebAPI.Auth;
using TellerSystem.ServiceProxy.Ext.WebAPI.Auth.Entity;


namespace TellerSystem.Contract.Function
{
    /// <summary>
    /// 授权对象，在交易中使用此对象来申请授权
    /// </summary>
    public class AuthManager
    {

        public static AuthManager GetAuthManager(DependencyObject obj)
        {
            return (AuthManager)obj.GetValue(AuthManagerProperty);
        }

        public static void SetAuthManager(DependencyObject obj, AuthManager value)
        {
            obj.SetValue(AuthManagerProperty, value);
        }

        // Using a DependencyProperty as the backing store for AuthManager.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AuthManagerProperty =
            DependencyProperty.RegisterAttached("AuthManager", typeof(AuthManager), typeof(AuthManager), new UIPropertyMetadata(null));

        public delegate void AsksuperResultHandle(AsksuperResultType result, TradeBusData busData);
        /// <summary>
        /// 授权有结果时触发的事件
        /// </summary>
        public event AsksuperResultHandle AsksuperResultMessage;

        public AuthManager()
        {

        }

        /// <summary>
        /// 获取柜员信息的操作类实例，替代缓存单例，否则会破坏登录柜员的缓存数据，导致异常
        /// </summary>
        private static LoginAuthentication loginAuthentication = new LoginAuthentication();

        #region 授权人员清单
        //为了向上级授权员兼容的改造处理
        private static List<string> lvls = TradeHandle.GetAuthLvls().Select(x => x.Split(':')[0]).ToList();
        private static string GenLvl(string x)
        {
            //解析逗号分割的配置情况
            var min = x.Split(',').Min();
            var lvl = new StringBuilder();
            lvls.Where(y => y.CompareTo(min) >= 0).ToList().ForEach(z =>
            {
                lvl.AppendFormat("{0},", z);
            });
            return lvl.ToString(0, lvl.Length - 1);
        }

        public static string[] GetTeller2Auth(string tellerNo, string lvl, string branch)
        {
            //检查角色授权的情况
            if (lvl.StartsWith("role:"))
            {
                //通过角色编号查询柜员列表
                var role = lvl.Substring(5);
                var sql = "SELECT USERCODE FROM TT_LOGINUSER tl WHERE USERID in( SELECT USERID  FROM TT_USERROLE tu WHERE tu.GROUPID IN (SELECT GROUPID FROM TT_ROLEGROUP tr WHERE tr.GROUPCODE = '" + role + "'))";
                if (!string.IsNullOrEmpty(branch))
                {
                    var kinbr = branch;
                    if (kinbr == "@") kinbr = LoginUserInfo.KinbrNo;//本机构;#：动态机构暂未支持
                    sql += " AND KINBRID IN (SELECT KINBRID  FROM TT_KINBRINFO tk WHERE KINBRNO = '" + kinbr + "')";
                }
                return UserManagerHandle.ExecuteQuery(sql);
            }
            return TradeHandle.GetTellerByLvlBranch(tellerNo, GenLvl(lvl), branch);
        }
        #endregion

        /// <summary>
        /// 检查授权
        /// </summary>
        /// <param name="target">IPage对象</param>
        /// <param name="Element"> 授权要素</param>
        /// <param name="msg">报文对象</param>
        /// <param name="pagedata">发送给授权人看的被授权人界面数据，可以传入null，如果为null取IPage的content作为传递给授权人看的画面，如果包涵多页等复杂的界面，请从外面自行创建此对象传递进来</param>
        /// <param name="funcnum"></param>
        /// <param name="accountno">账号</param>
        /// <param name="amount">发生金额</param>
        /// <param name="count"></param>
        /// <param name="custname">客户名称</param>
        /// <param name="des">备注信息</param>
        /// <param name="Branch"></param>
        /// <returns>true,不需要授权，或者授权已通过;false,检查授权出错;需要授权，申请不成功;授权未通过</returns>
        public bool DoAuth(PageBase target, AuthConditionElement Element, Message msg, PageData[] pagedata, string funcnum, string accountno, string amount, string count, string custname, string des, string Branch)
        {
            string FLAG = TradeManagerHandle.TT_SYSCONFIG_GetConfigValueByConfigID("2ea3a7e6cfa04f89a335bf1e363295de");
            var data = TradeInfoData.GetTradeInfo(target as DependencyObject);

            TradeBusData tradedata = data.TradeBus;
            byte[] pagedatas = pagedata.Length > 0 ? pagedata[0].datas : new byte[0];
            //授权要素为null，返回false
            if (Element == null)
            {
                ClearDataBus(target, pagedatas);
                return false;
            }
            // 如果为null取IPage的content作为传递给授权人看的画面，如果包涵多页等复杂的界面，请从外面自行创建此对象传递进来
            if (pagedata == null && target != null)
            {
                pagedata = new TellerSystem.ServiceProxy.Ext.ServiceEntitys.PageData[1];
                pagedata[0] = new TellerSystem.ServiceProxy.Ext.ServiceEntitys.PageData() { index = 1, datas = target.SaveTradePage((FrameworkElement)((ContentControl)target).Content) };
            }
            // ((TradePage)target).GetCurrentTabItem().Tag = this;
            TradePage page = (TradePage)target;
            // 记下此授权管理对象，后面可能需要再触发它的授权结果事件
            this.SystemSerialNumber = page.CreateSerialNumber();
            msg.SerialNumber = this.SystemSerialNumber;
            //page.GetCurrentTabItem().Tag = this;
            SetAuthManager(page, this);
            bool result = CheckAuth(target, Element, msg, data.TradeCode, funcnum, Branch, pagedatas);
            if (result)
            {
                AuthDataHelper authdata = new AuthDataHelper(target);

                var listImgTrade = new List<ImageSource>();
                //listImgTrade = data.TradeScreens.ToList<ImageSource>();
                //循环添加交易截图
                foreach (var item in data.TradeScreens)
                {
                    listImgTrade.AddRange(item.Value);
                }
                //远程授权的将授权人数改为 远程授权的编号，如果以后某些行需要两人授权的话这里需要改造
                var AuthPersonNum = authdata.AuthPersonNum;
                var authLv1 = authdata.Lvl;
                //获取截屏信息加到屏幕截屏集合中
                var title = string.Format("交易信息:({0})-{1}", page.TradeModel.Code, page.TradeModel.Name);
                //  authphoto.imgname = title;
                if (data.TradeScreens != null)
                {
                    //
                    listImgTrade.AddRange(GetPageImages(target, title));
                    //这个是两种不同的方法
                    //var  listimg    = SystemFunction.addImageScreens(page, GetPageImages(target, title));
                }
                else
                {
                    listImgTrade = GetPageImages(target, title);
                }
                //带逗号的数字形式在服务端无法转换，故在此去掉数字中的逗号
                if (!string.IsNullOrWhiteSpace(amount))
                {
                    amount = amount.Replace(",", "");
                }
                double tmpamount = string.IsNullOrEmpty(amount) ? 0 : Double.Parse(amount);
                //检查授权出现错误
                if (!bool.Parse(authdata.CheckFlag))
                {
                    return false;
                }
                else
                {
                    #region 预授权检查
                    if (authdata.AuthMode[2] == '1')
                    {
                        //预授权标志
                        string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        if (!string.IsNullOrEmpty(preauthresult))
                        {
                            string[] tmpresult = preauthresult.Split(':');
                            if (tmpresult.Length == 4)
                            {
                                //预授权下发或申请机构与当前机构一至
                                if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                                {
                                    authdata.AuthFlag = "true";
                                    authdata.PreAuthId = tmpresult[0];
                                    authdata.AuthTeller = tmpresult[1];
                                    //tradedata["AuthFlag"] = "true";
                                    //tradedata["PreAuthId"] = tmpresult[0];
                                    //tradedata["AuthTeller"] = tmpresult[1];
                                    return true;
                                }
                                else
                                {
                                    target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                                    return false;
                                }
                            }
                            else
                            {
                                target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                                return false;
                            }
                        }
                        else if (authdata.AuthMode[0] == '0' && authdata.AuthMode[1] == '0')
                        {
                            //仅支持预授权
                            target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                            return false;
                        }
                    }
                    #endregion
                    #region 授权抉择
                    //无论本地或远程授权，都请求操作者进行抉择，需要挑选授权者
                    if (authdata.AuthMode[0] == '0' && authdata.AuthMode[1] == '0' && authdata.AuthMode[3] == '0')
                    {
                        //需要授权，但没有指定相应的授权模式
                        target.TradeAPIs.ShowErrorMessageBox("需要授权，但未指定任何授权方式！");
                        return false;
                    }
                    //如果只有集中授权直接弹出授权页面
                    else if (authdata.AuthMode[0] == '0' && authdata.AuthMode[1] == '0' && authdata.AuthMode[3] == '1')
                    {
                        var defaultBtn = FLAG == "V18" ? MessageBoxResult.No : MessageBoxResult.Yes;
                        if (target.TradeAPIs.ShowQuestionMessageBox("该交易需要集中授权是否继续？", "询问信息", defaultBtn, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            //创建页面
                            var authPage = PageFactory.CreatePage("Trade.OperationManage.REMOTEAUTH");
                            if (authPage == null)
                            {
                                target.ShowInfoMessageBox("无法打开授权页面！请检查...");
                                return false;
                            }
                            ElementInfoResult ElementInfoResult = null;
                            try
                            {
                                ElementInfoResult = AuthHandle.GetRmAuthElementByMenu(page.TradeModel.Code, AuthPersonNum);
                            }
                            catch (Exception e)
                            {
                                target.TradeAPIs.ShowInfoMessageBox(e.Message.ToString());
                                return false;
                            }

                            authPage.SetViewStateData(new Dictionary<string, object> { { "photo", listImgTrade }, { "ElementInfoResult", ElementInfoResult }, { "authLv1", authLv1 }, { "SerialNumber", data.SystemSerialNumber } });//, { "imgUri", imgUri }
                            if (ElementInfoResult != null)
                            {
                                var a = target.ShowPage(authPage, "集中授权");
                                if (a != null)
                                {
                                    foreach (var item in a)
                                    {
                                        if (item.Key == "result" && item.Value.ToString() == "4")
                                        {
                                            return remoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                                            //return true;
                                        }
                                    }
                                }
                            }
                            return false;
                        }
                        else
                        {

                            //阳光要求当选择否时 提交到本地授权
                            //组装页面
                            var content = new AuthQuestion();
                            //远程授权 
                            content.local.Visibility = Visibility.Visible;
                            content.local.IsChecked = true;
                            content.local.IsEnabled = true;
                    #endregion
                            //授权柜员清单
                            string[] lvlPerson = authdata.Lvl.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                            for (int j = 0; j < lvlPerson.Length; j++)
                            {
                                string[] tellers = GetTeller2Auth(LoginUserInfo.TellerNo, lvlPerson[j], authdata.Branch);
                                if (tellers == null || tellers.Count() == 0 || (tellers.Length == 1 && tellers.Contains(LoginUserInfo.TellerNo)))
                                {
                                    target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                    return false;
                                }
                                //与核心进行交互，验证柜员锁定状态
                                string tellergroup = string.Empty;
                                foreach (var tmp in tellers)
                                {
                                    if (tmp == LoginUserInfo.TellerNo)
                                        continue;
                                    tellergroup += tmp + "|";
                                }
                                //验证柜员是否有效
                                var tellerstat = target.TradeAPIs.TF_Manage_QueryTellerStatusBatch(new QueryTellerStatusBatch.Input()
                                {
                                    GYH = tellergroup
                                });
                                if (tellerstat.IsFailed)
                                {
                                    target.TradeAPIs.ShowErrorMessageBox(tellerstat.FailureCause);
                                    return false;
                                }
                                StringReader tmptellerstat = new StringReader(tellerstat.WJ);
                                List<string> tellerList = new List<string>();
                                string line = tmptellerstat.ReadLine();
                                while (!string.IsNullOrEmpty(line))
                                {
                                    string[] tmpline = line.Split('|');
                                    if (tmpline.Length >= 3)
                                    {
                                        //状态3是锁定状态，4是删除状态
                                        if (tmpline[2] != "3" && tmpline[2] != "4")
                                        {
                                            tellerList.Add(tmpline[0]);
                                        }
                                    }
                                    line = tmptellerstat.ReadLine();
                                }
                                #region 停用柜员不出现在本地授权列表中
                                List<string> tellerList_JX = new List<string>();
                                foreach (var item in tellerList)
                                {
                                    loginAuthentication.InitData(item);
                                    if (loginAuthentication.ISLOGIN)
                                    {
                                        tellerList_JX.Add(item);
                                    }
                                }
                                tellerList = tellerList_JX;
                                #endregion
                                Dictionary<string, string> dic = new Dictionary<string, string> { };
                                if (tellerList != null && tellerList.Count > 0 && !(tellerList.Count == 1 && tellerList.Contains(LoginUserInfo.TellerNo)))
                                {
                                    dic.Add("全部", "0");
                                    int i = 1;
                                    foreach (var item in tellerList)
                                    {
                                        dic.Add(item, i.ToString());
                                        i++;
                                    }
                                    content.authteller.SetItems(dic);
                                    content.authteller.SelectedIndex = 0;
                                    //如果是双人授权，则只能选择全部柜员，不能指定柜员
                                    if (authdata.AuthPersonNum == "2")
                                    {
                                        content.authteller.IsEnabled = false;
                                    }
                                    else
                                    {
                                        content.authteller.IsEnabled = true;
                                    }
                                    content.reason.Text = authdata.AuthReason;
                                    list.Add(dic);
                                }
                                else
                                {
                                    target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                    return false;
                                }
                            }
                            if (target.TradeAPIs.ShowQuestionMessageBox(content, "需要授权") == MessageBoxResult.No)
                            {
                                //取消授权操作
                                return false;
                            }
                            //操作者指定的授权模式和授权柜员
                            //操作都指定了授权柜员 
                            if (content.authteller.SelectedIndex != 0)
                            {

                                authdata.AppointTeller = ((KeyValuePair<string, string>)(content.authteller.SelectedItem)).Key;
                            }
                            if (content.local.IsChecked == true)
                            {
                                tradedata["authtellers"] = target.Serialize(list[0]);
                                if (list.Count >= 2)
                                {
                                    tradedata["authtellers2"] = target.Serialize(list[1]);
                                }
                                return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                            }
                            if (content.remot.IsChecked == true)
                            {
                                //远程授权，将报文对象序列化上传到总线
                                tradedata["MSG"] = target.Serialize(msg);
                                return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                            }
                            target.TradeAPIs.ShowErrorMessageBox("未指定任何授权方式");
                            return false;

                        }
                    }
                    else
                    {
                        //组装页面
                        var content = new AuthQuestion();
                        //远程授权       
                        if (authdata.AuthMode[1] == '1')
                        {
                            content.remot.Visibility = Visibility.Visible;
                            content.remot.IsChecked = true;
                            content.remot.IsEnabled = true;
                        }
                        if (authdata.AuthMode[0] == '1')
                        {
                            content.local.Visibility = Visibility.Visible;
                            content.local.IsChecked = true;
                            content.local.IsEnabled = true;
                        }
                        //授权柜员清单
                        string[] lvlPerson = authdata.Lvl.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                        for (int j = 0; j < lvlPerson.Length; j++)
                        {
                            string[] tellers = GetTeller2Auth(LoginUserInfo.TellerNo, lvlPerson[j], authdata.Branch);
                            if (tellers == null || tellers.Count() == 0 || (tellers.Length == 1 && tellers.Contains(LoginUserInfo.TellerNo)))
                            {
                                target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                return false;
                            }
                            //与核心进行交互，验证柜员锁定状态
                            string tellergroup = string.Empty;
                            foreach (var tmp in tellers)
                            {
                                if (tmp == LoginUserInfo.TellerNo)
                                    continue;
                                tellergroup += tmp + "|";
                            }
                            //验证柜员是否有效
                            var tellerstat = target.TradeAPIs.TF_Manage_QueryTellerStatusBatch(new QueryTellerStatusBatch.Input()
                            {
                                GYH = tellergroup
                            });
                            if (tellerstat.IsFailed)
                            {
                                target.TradeAPIs.ShowErrorMessageBox(tellerstat.FailureCause);
                                return false;
                            }
                            StringReader tmptellerstat = new StringReader(tellerstat.WJ);
                            List<string> tellerList = new List<string>();
                            string line = tmptellerstat.ReadLine();
                            while (!string.IsNullOrEmpty(line))
                            {
                                string[] tmpline = line.Split('|');
                                if (tmpline.Length >= 3)
                                {
                                    //状态3是锁定状态，4是删除状态
                                    if (tmpline[2] != "3" && tmpline[2] != "4")
                                    {
                                        tellerList.Add(tmpline[0]);
                                    }
                                }
                                line = tmptellerstat.ReadLine();
                            }
                            #region 停用柜员不出现在本地授权列表中
                            List<string> tellerList_JX = new List<string>();
                            foreach (var item in tellerList)
                            {
                                loginAuthentication.InitData(item);
                                if (loginAuthentication.ISLOGIN)
                                {
                                    tellerList_JX.Add(item);
                                }
                            }
                            tellerList = tellerList_JX;
                            #endregion
                            Dictionary<string, string> dic = new Dictionary<string, string> { };
                            if (tellerList != null && tellerList.Count > 0 && !(tellerList.Count == 1 && tellerList.Contains(LoginUserInfo.TellerNo)))
                            {
                                dic.Add("全部", "0");
                                int i = 1;
                                foreach (var item in tellerList)
                                {
                                    dic.Add(item, i.ToString());
                                    i++;
                                }
                                content.authteller.SetItems(dic);
                                content.authteller.SelectedIndex = 0;
                                //如果是双人授权，则只能选择全部柜员，不能指定柜员
                                if (authdata.AuthPersonNum == "2")
                                {
                                    content.authteller.IsEnabled = false;
                                }
                                else
                                {
                                    content.authteller.IsEnabled = true;
                                }
                                content.reason.Text = authdata.AuthReason;
                                list.Add(dic);
                            }
                            else
                            {
                                target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                return false;
                            }
                        }
                        if (target.TradeAPIs.ShowQuestionMessageBox(content, "需要授权") == MessageBoxResult.No)
                        {
                            //取消授权操作
                            return false;
                        }
                        //操作者指定的授权模式和授权柜员
                        //操作都指定了授权柜员 
                        if (content.authteller.SelectedIndex != 0)
                        {

                            authdata.AppointTeller = ((KeyValuePair<string, string>)(content.authteller.SelectedItem)).Key;
                        }
                        if (content.local.IsChecked == true)
                        {
                            tradedata["authtellers"] = target.Serialize(list[0]);
                            if (list.Count >= 2)
                            {
                                tradedata["authtellers2"] = target.Serialize(list[1]);
                            }
                            return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        }
                        if (content.remot.IsChecked == true)
                        {
                            //远程授权，将报文对象序列化上传到总线
                            tradedata["MSG"] = target.Serialize(msg);
                            return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        }
                        target.TradeAPIs.ShowErrorMessageBox("未指定任何授权方式");
                        return false;

                        #region 删除
                        ////本地授权
                        //if ("100".Equals(authdata.AuthMode))
                        //{
                        //    //target.OpenTradePage(new AuthQuestion(1, new string[0]), TradePageExtension.OpenOptions.Dialog,authdata);
                        //    return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //}
                        ////远程授权
                        //else if ("010".Equals(authdata.AuthMode))
                        //{
                        //    //远程授权，将报文对象序列化上传到总线
                        //    tradedata["MSG"] = target.Serialize(msg);
                        //    return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //}
                        ////预授权
                        //else if ("001".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //        return false;
                        //    }
                        //    else
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //}
                        ////本地或远程授权
                        //else if ("110".Equals(authdata.AuthMode))
                        //{
                        //    int msres = SystemFunction.ShowComfirmBox(target, "选择授权方式", new string[] { "本地授权", "远程授权", "取消" });
                        //    //选择本地授权
                        //    if (msres == 1)
                        //    {
                        //        return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //    }
                        //    //远程授权
                        //    else if (msres == 2)
                        //    {
                        //        //远程授权，将报文对象序列化上传到总线
                        //        tradedata["MSG"] = target.Serialize(msg);
                        //        return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //    }
                        //    else
                        //    {
                        //        return false;
                        //    }
                        //}
                        ////本地授权或者远程授权或预授权
                        //else if ("111".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (!string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        int msres = SystemFunction.ShowComfirmBox(target, "选择授权方式", new string[] { "本地授权", "远程授权", "取消" });
                        //        //选择本地授权
                        //        if (msres == 1)
                        //        {
                        //            return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //        }
                        //        //远程授权
                        //        else if (msres == 2)
                        //        {
                        //            //远程授权，将报文对象序列化上传到总线
                        //            tradedata["MSG"] = target.Serialize(msg);
                        //            return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //        }
                        //        else
                        //        {
                        //            return false;
                        //        }
                        //    }

                        //}
                        ////远程授权或预授权
                        //else if ("011".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (!string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        //远程授权，将报文对象序列化上传到总线
                        //        tradedata["MSG"] = target.Serialize(msg);
                        //        return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //    }
                        //}
                        ////本地授权或预授权
                        //else if ("101".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (!string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");

                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //    }
                        //}
                        //else
                        //{
                        //    //需要授权，但没有指定相应的授权模式
                        //    return false;
                        //}
                    }
                        #endregion
                }
            }
            else
            {
                //AuthDataHelper authdata = new AuthDataHelper(target);
                //authdata.ClearAuthData();
            }
            return true;
        }

        /// <summary>
        /// 检查授权_无条件强制授权
        /// </summary>
        /// <param name="target">IPage对象</param>
        /// <param name="Element"> 授权要素</param>
        /// <param name="msg">报文对象</param>
        /// <param name="pagedata">发送给授权人看的被授权人界面数据，可以传入null，如果为null取IPage的content作为传递给授权人看的画面，如果包涵多页等复杂的界面，请从外面自行创建此对象传递进来</param>
        /// <param name="funcnum"></param>
        /// <param name="accountno">账号</param>
        /// <param name="amount">发生金额</param>
        /// <param name="count"></param>
        /// <param name="custname">客户名称</param>
        /// <param name="des">备注信息</param>
        /// <param name="Branch"></param>
        /// <returns>true,不需要授权，或者授权已通过;false,检查授权出错;需要授权，申请不成功;授权未通过</returns>
        public bool DoAuth_ZP(PageBase target, AuthConditionElement Element, Message msg, PageData[] pagedata, string funcnum, string accountno, string amount, string count, string custname, string des, string Branch)
        {
            string FLAG = TradeManagerHandle.TT_SYSCONFIG_GetConfigValueByConfigID("2ea3a7e6cfa04f89a335bf1e363295de");
            var data = TradeInfoData.GetTradeInfo(target as DependencyObject);

            TradeBusData tradedata = data.TradeBus;
            byte[] pagedatas = pagedata.Length > 0 ? pagedata[0].datas : new byte[0];
            //授权要素为null，返回false
            if (Element == null)
            {
                ClearDataBus(target, pagedatas);
                return false;
            }
            // 如果为null取IPage的content作为传递给授权人看的画面，如果包涵多页等复杂的界面，请从外面自行创建此对象传递进来
            if (pagedata == null && target != null)
            {
                pagedata = new TellerSystem.ServiceProxy.Ext.ServiceEntitys.PageData[1];
                pagedata[0] = new TellerSystem.ServiceProxy.Ext.ServiceEntitys.PageData() { index = 1, datas = target.SaveTradePage((FrameworkElement)((ContentControl)target).Content) };
            }
            // ((TradePage)target).GetCurrentTabItem().Tag = this;
            TradePage page = (TradePage)target;
            // 记下此授权管理对象，后面可能需要再触发它的授权结果事件
            this.SystemSerialNumber = page.CreateSerialNumber();
            msg.SerialNumber = this.SystemSerialNumber;
            //page.GetCurrentTabItem().Tag = this;
            SetAuthManager(page, this);
            bool result = CheckAuth_ZP(target, Element, msg, data.TradeCode, funcnum, Branch, pagedatas);
            if (result)
            {
                AuthDataHelper authdata = new AuthDataHelper(target);

                var listImgTrade = new List<ImageSource>();
                //listImgTrade = data.TradeScreens.ToList<ImageSource>();
                //循环添加交易截图
                foreach (var item in data.TradeScreens)
                {
                    listImgTrade.AddRange(item.Value);
                }
                //远程授权的将授权人数改为 远程授权的编号，如果以后某些行需要两人授权的话这里需要改造
                var AuthPersonNum = authdata.AuthPersonNum;
                var authLv1 = authdata.Lvl;
                //获取截屏信息加到屏幕截屏集合中
                var title = string.Format("交易信息:({0})-{1}", page.TradeModel.Code, page.TradeModel.Name);
                //  authphoto.imgname = title;
                if (data.TradeScreens != null)
                {
                    //
                    listImgTrade.AddRange(GetPageImages(target, title));
                    //这个是两种不同的方法
                    //var  listimg    = SystemFunction.addImageScreens(page, GetPageImages(target, title));
                }
                else
                {
                    listImgTrade = GetPageImages(target, title);
                }
                //带逗号的数字形式在服务端无法转换，故在此去掉数字中的逗号
                if (!string.IsNullOrWhiteSpace(amount))
                {
                    amount = amount.Replace(",", "");
                }
                double tmpamount = string.IsNullOrEmpty(amount) ? 0 : Double.Parse(amount);
                //检查授权出现错误
                if (!bool.Parse(authdata.CheckFlag))
                {
                    return false;
                }
                else
                {
                    #region 预授权检查
                    if (authdata.AuthMode[2] == '1')
                    {
                        //预授权标志
                        string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        if (!string.IsNullOrEmpty(preauthresult))
                        {
                            string[] tmpresult = preauthresult.Split(':');
                            if (tmpresult.Length == 4)
                            {
                                //预授权下发或申请机构与当前机构一至
                                if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                                {
                                    authdata.AuthFlag = "true";
                                    authdata.PreAuthId = tmpresult[0];
                                    authdata.AuthTeller = tmpresult[1];
                                    //tradedata["AuthFlag"] = "true";
                                    //tradedata["PreAuthId"] = tmpresult[0];
                                    //tradedata["AuthTeller"] = tmpresult[1];
                                    return true;
                                }
                                else
                                {
                                    target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                                    return false;
                                }
                            }
                            else
                            {
                                target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                                return false;
                            }
                        }
                        else if (authdata.AuthMode[0] == '0' && authdata.AuthMode[1] == '0')
                        {
                            //仅支持预授权
                            target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                            return false;
                        }
                    }
                    #endregion
                    #region 授权抉择
                    //无论本地或远程授权，都请求操作者进行抉择，需要挑选授权者
                    if (authdata.AuthMode[0] == '0' && authdata.AuthMode[1] == '0' && authdata.AuthMode[3] == '0')
                    {
                        //需要授权，但没有指定相应的授权模式
                        target.TradeAPIs.ShowErrorMessageBox("需要授权，但未指定任何授权方式！");
                        return false;
                    }
                    //如果只有集中授权直接弹出授权页面
                    else if (authdata.AuthMode[0] == '0' && authdata.AuthMode[1] == '0' && authdata.AuthMode[3] == '1')
                    {
                        var defaultBtn = FLAG == "V18" ? MessageBoxResult.No : MessageBoxResult.Yes;
                        if (target.TradeAPIs.ShowQuestionMessageBox("该交易需要集中授权是否继续？", "询问信息", defaultBtn, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            //创建页面
                            var authPage = PageFactory.CreatePage("Trade.OperationManage.REMOTEAUTH");
                            if (authPage == null)
                            {
                                target.ShowInfoMessageBox("无法打开授权页面！请检查...");
                                return false;
                            }
                            ElementInfoResult ElementInfoResult = null;
                            try
                            {
                                ElementInfoResult = AuthHandle.GetRmAuthElementByMenu(page.TradeModel.Code, AuthPersonNum);
                            }
                            catch (Exception e)
                            {
                                target.TradeAPIs.ShowInfoMessageBox(e.Message.ToString());
                                return false;
                            }

                            authPage.SetViewStateData(new Dictionary<string, object> { { "photo", listImgTrade }, { "ElementInfoResult", ElementInfoResult }, { "authLv1", authLv1 }, { "SerialNumber", data.SystemSerialNumber } });//, { "imgUri", imgUri }
                            if (ElementInfoResult != null)
                            {
                                var a = target.ShowPage(authPage, "集中授权");
                                if (a != null)
                                {
                                    foreach (var item in a)
                                    {
                                        if (item.Key == "result" && item.Value.ToString() == "4")
                                        {
                                            return remoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                                            //return true;
                                        }
                                    }
                                }
                            }
                            return false;
                        }
                        else
                        {

                            //阳光要求当选择否时 提交到本地授权
                            //组装页面
                            var content = new AuthQuestion();
                            //远程授权 
                            content.local.Visibility = Visibility.Visible;
                            content.local.IsChecked = true;
                            content.local.IsEnabled = true;
                    #endregion
                            //授权柜员清单
                            string[] lvlPerson = authdata.Lvl.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                            for (int j = 0; j < lvlPerson.Length; j++)
                            {
                                string[] tellers = GetTeller2Auth(LoginUserInfo.TellerNo, lvlPerson[j], authdata.Branch);
                                if (tellers == null || tellers.Count() == 0 || (tellers.Length == 1 && tellers.Contains(LoginUserInfo.TellerNo)))
                                {
                                    target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                    return false;
                                }
                                //与核心进行交互，验证柜员锁定状态
                                string tellergroup = string.Empty;
                                foreach (var tmp in tellers)
                                {
                                    if (tmp == LoginUserInfo.TellerNo)
                                        continue;
                                    tellergroup += tmp + "|";
                                }
                                //验证柜员是否有效
                                var tellerstat = target.TradeAPIs.TF_Manage_QueryTellerStatusBatch(new QueryTellerStatusBatch.Input()
                                {
                                    GYH = tellergroup
                                });
                                if (tellerstat.IsFailed)
                                {
                                    target.TradeAPIs.ShowErrorMessageBox(tellerstat.FailureCause);
                                    return false;
                                }
                                StringReader tmptellerstat = new StringReader(tellerstat.WJ);
                                List<string> tellerList = new List<string>();
                                string line = tmptellerstat.ReadLine();
                                while (!string.IsNullOrEmpty(line))
                                {
                                    string[] tmpline = line.Split('|');
                                    if (tmpline.Length >= 3)
                                    {
                                        //状态3是锁定状态，4是删除状态
                                        if (tmpline[2] != "3" && tmpline[2] != "4")
                                        {
                                            tellerList.Add(tmpline[0]);
                                        }
                                    }
                                    line = tmptellerstat.ReadLine();
                                }
                                #region 停用柜员不出现在本地授权列表中
                                List<string> tellerList_JX = new List<string>();
                                foreach (var item in tellerList)
                                {
                                    loginAuthentication.InitData(item);
                                    if (loginAuthentication.ISLOGIN)
                                    {
                                        tellerList_JX.Add(item);
                                    }
                                }
                                tellerList = tellerList_JX;
                                #endregion
                                Dictionary<string, string> dic = new Dictionary<string, string> { };
                                if (tellerList != null && tellerList.Count > 0 && !(tellerList.Count == 1 && tellerList.Contains(LoginUserInfo.TellerNo)))
                                {
                                    dic.Add("全部", "0");
                                    int i = 1;
                                    foreach (var item in tellerList)
                                    {
                                        dic.Add(item, i.ToString());
                                        i++;
                                    }
                                    content.authteller.SetItems(dic);
                                    content.authteller.SelectedIndex = 0;
                                    //如果是双人授权，则只能选择全部柜员，不能指定柜员
                                    if (authdata.AuthPersonNum == "2")
                                    {
                                        content.authteller.IsEnabled = false;
                                    }
                                    else
                                    {
                                        content.authteller.IsEnabled = true;
                                    }
                                    content.reason.Text = authdata.AuthReason;
                                    list.Add(dic);
                                }
                                else
                                {
                                    target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                    return false;
                                }
                            }
                            if (target.TradeAPIs.ShowQuestionMessageBox(content, "需要授权") == MessageBoxResult.No)
                            {
                                //取消授权操作
                                return false;
                            }
                            //操作者指定的授权模式和授权柜员
                            //操作都指定了授权柜员 
                            if (content.authteller.SelectedIndex != 0)
                            {

                                authdata.AppointTeller = ((KeyValuePair<string, string>)(content.authteller.SelectedItem)).Key;
                            }
                            if (content.local.IsChecked == true)
                            {
                                tradedata["authtellers"] = target.Serialize(list[0]);
                                if (list.Count >= 2)
                                {
                                    tradedata["authtellers2"] = target.Serialize(list[1]);
                                }
                                return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                            }
                            if (content.remot.IsChecked == true)
                            {
                                //远程授权，将报文对象序列化上传到总线
                                tradedata["MSG"] = target.Serialize(msg);
                                return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                            }
                            target.TradeAPIs.ShowErrorMessageBox("未指定任何授权方式");
                            return false;

                        }
                    }
                    else
                    {
                        //组装页面
                        var content = new AuthQuestion();
                        //远程授权       
                        if (authdata.AuthMode[1] == '1')
                        {
                            content.remot.Visibility = Visibility.Visible;
                            content.remot.IsChecked = true;
                            content.remot.IsEnabled = true;
                        }
                        if (authdata.AuthMode[0] == '1')
                        {
                            content.local.Visibility = Visibility.Visible;
                            content.local.IsChecked = true;
                            content.local.IsEnabled = true;
                        }
                        //授权柜员清单
                        string[] lvlPerson = authdata.Lvl.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                        for (int j = 0; j < lvlPerson.Length; j++)
                        {
                            string[] tellers = GetTeller2Auth(LoginUserInfo.TellerNo, lvlPerson[j], authdata.Branch);
                            if (tellers == null || tellers.Count() == 0 || (tellers.Length == 1 && tellers.Contains(LoginUserInfo.TellerNo)))
                            {
                                target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                return false;
                            }
                            //与核心进行交互，验证柜员锁定状态
                            string tellergroup = string.Empty;
                            foreach (var tmp in tellers)
                            {
                                if (tmp == LoginUserInfo.TellerNo)
                                    continue;
                                tellergroup += tmp + "|";
                            }
                            //验证柜员是否有效
                            var tellerstat = target.TradeAPIs.TF_Manage_QueryTellerStatusBatch(new QueryTellerStatusBatch.Input()
                            {
                                GYH = tellergroup
                            });
                            if (tellerstat.IsFailed)
                            {
                                target.TradeAPIs.ShowErrorMessageBox(tellerstat.FailureCause);
                                return false;
                            }
                            StringReader tmptellerstat = new StringReader(tellerstat.WJ);
                            List<string> tellerList = new List<string>();
                            string line = tmptellerstat.ReadLine();
                            while (!string.IsNullOrEmpty(line))
                            {
                                string[] tmpline = line.Split('|');
                                if (tmpline.Length >= 3)
                                {
                                    //状态3是锁定状态，4是删除状态
                                    if (tmpline[2] != "3" && tmpline[2] != "4")
                                    {
                                        tellerList.Add(tmpline[0]);
                                    }
                                }
                                line = tmptellerstat.ReadLine();
                            }
                            #region 停用柜员不出现在本地授权列表中
                            List<string> tellerList_JX = new List<string>();
                            foreach (var item in tellerList)
                            {
                                loginAuthentication.InitData(item);
                                if (loginAuthentication.ISLOGIN)
                                {
                                    tellerList_JX.Add(item);
                                }
                            }
                            tellerList = tellerList_JX;
                            #endregion
                            Dictionary<string, string> dic = new Dictionary<string, string> { };
                            if (tellerList != null && tellerList.Count > 0 && !(tellerList.Count == 1 && tellerList.Contains(LoginUserInfo.TellerNo)))
                            {
                                dic.Add("全部", "0");
                                int i = 1;
                                foreach (var item in tellerList)
                                {
                                    dic.Add(item, i.ToString());
                                    i++;
                                }
                                content.authteller.SetItems(dic);
                                content.authteller.SelectedIndex = 0;
                                //如果是双人授权，则只能选择全部柜员，不能指定柜员
                                if (authdata.AuthPersonNum == "2")
                                {
                                    content.authteller.IsEnabled = false;
                                }
                                else
                                {
                                    content.authteller.IsEnabled = true;
                                }
                                content.reason.Text = authdata.AuthReason;
                                list.Add(dic);
                            }
                            else
                            {
                                target.TradeAPIs.ShowErrorMessageBox("没有合适的授权柜员，无法完成授权");
                                return false;
                            }
                        }
                        if (target.TradeAPIs.ShowQuestionMessageBox(content, "需要授权") == MessageBoxResult.No)
                        {
                            //取消授权操作
                            return false;
                        }
                        //操作者指定的授权模式和授权柜员
                        //操作都指定了授权柜员 
                        if (content.authteller.SelectedIndex != 0)
                        {

                            authdata.AppointTeller = ((KeyValuePair<string, string>)(content.authteller.SelectedItem)).Key;
                        }
                        if (content.local.IsChecked == true)
                        {
                            tradedata["authtellers"] = target.Serialize(list[0]);
                            if (list.Count >= 2)
                            {
                                tradedata["authtellers2"] = target.Serialize(list[1]);
                            }
                            return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        }
                        if (content.remot.IsChecked == true)
                        {
                            //远程授权，将报文对象序列化上传到总线
                            tradedata["MSG"] = target.Serialize(msg);
                            return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        }
                        target.TradeAPIs.ShowErrorMessageBox("未指定任何授权方式");
                        return false;

                        #region 删除
                        ////本地授权
                        //if ("100".Equals(authdata.AuthMode))
                        //{
                        //    //target.OpenTradePage(new AuthQuestion(1, new string[0]), TradePageExtension.OpenOptions.Dialog,authdata);
                        //    return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //}
                        ////远程授权
                        //else if ("010".Equals(authdata.AuthMode))
                        //{
                        //    //远程授权，将报文对象序列化上传到总线
                        //    tradedata["MSG"] = target.Serialize(msg);
                        //    return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //}
                        ////预授权
                        //else if ("001".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //        return false;
                        //    }
                        //    else
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //}
                        ////本地或远程授权
                        //else if ("110".Equals(authdata.AuthMode))
                        //{
                        //    int msres = SystemFunction.ShowComfirmBox(target, "选择授权方式", new string[] { "本地授权", "远程授权", "取消" });
                        //    //选择本地授权
                        //    if (msres == 1)
                        //    {
                        //        return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //    }
                        //    //远程授权
                        //    else if (msres == 2)
                        //    {
                        //        //远程授权，将报文对象序列化上传到总线
                        //        tradedata["MSG"] = target.Serialize(msg);
                        //        return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //    }
                        //    else
                        //    {
                        //        return false;
                        //    }
                        //}
                        ////本地授权或者远程授权或预授权
                        //else if ("111".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (!string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        int msres = SystemFunction.ShowComfirmBox(target, "选择授权方式", new string[] { "本地授权", "远程授权", "取消" });
                        //        //选择本地授权
                        //        if (msres == 1)
                        //        {
                        //            return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //        }
                        //        //远程授权
                        //        else if (msres == 2)
                        //        {
                        //            //远程授权，将报文对象序列化上传到总线
                        //            tradedata["MSG"] = target.Serialize(msg);
                        //            return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //        }
                        //        else
                        //        {
                        //            return false;
                        //        }
                        //    }

                        //}
                        ////远程授权或预授权
                        //else if ("011".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (!string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");
                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        //远程授权，将报文对象序列化上传到总线
                        //        tradedata["MSG"] = target.Serialize(msg);
                        //        return RemoteAuth(target, pagedata, accountno, tmpamount, custname, des);
                        //    }
                        //}
                        ////本地授权或预授权
                        //else if ("101".Equals(authdata.AuthMode))
                        //{
                        //    string preauthresult = TradeHandle.CheckPreAuth(data.TradeCode, accountno, amount, count);
                        //    if (!string.IsNullOrEmpty(preauthresult))
                        //    {
                        //        string[] tmpresult = preauthresult.Split(':');
                        //        if (tmpresult.Length == 4)
                        //        {
                        //            //预授权下发或申请机构与当前机构一至
                        //            if ("4".Equals(tmpresult[3]) || LoginUserInfo.KinbrNo.Equals(tmpresult[2]))
                        //            {
                        //                authdata.AuthFlag = "true";
                        //                authdata.PreAuthId = tmpresult[0];
                        //                authdata.AuthTeller = tmpresult[1];
                        //                //tradedata["AuthFlag"] = "true";
                        //                //tradedata["PreAuthId"] = tmpresult[0];
                        //                //tradedata["AuthTeller"] = tmpresult[1];
                        //                return true;
                        //            }
                        //            else
                        //            {
                        //                target.TradeAPIs.ShowErrorMessageBox("需要提前预授权");

                        //                return false;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            target.TradeAPIs.ShowErrorMessageBox("检查预授权出错");
                        //            return false;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        return LocalAuth(target, pagedata, accountno, tmpamount, custname, des, tradedata);
                        //    }
                        //}
                        //else
                        //{
                        //    //需要授权，但没有指定相应的授权模式
                        //    return false;
                        //}
                    }
                        #endregion
                }
            }
            else
            {
                //AuthDataHelper authdata = new AuthDataHelper(target);
                //authdata.ClearAuthData();
            }
            return true;
        }


        /// <summary>
        /// 远程授权
        /// </summary>
        /// <param name="target"></param>
        /// <param name="pagedata"></param>
        /// <param name="accountno"></param>
        /// <param name="amount"></param>
        /// <param name="custname"></param>
        /// <param name="des"></param>
        /// <returns></returns>
        private bool RemoteAuth(PageBase target, PageData[] pagedata, string accountno, double amount, string custname, string des)
        {

            if (AskAuth(target, pagedata, 2, accountno, amount, custname, des))
            {
                //SystemFunction.ShowComfirmBox(target, "提示：已提交远程授权，稍后请从待办任务中继续做此交易", new string[] { "确定" });
                target.TradeAPIs.ShowInfoMessageBox("已提交远程授权，稍后请从待办任务中继续做此交易");
                #region  从技术角度，此时应卡在这里，等远程授权返回结果再继续执行，临时先返回false


                target.HideTradeTab(target);
                return false;
                #endregion
            }
            else
            {
                target.TradeAPIs.ShowErrorMessageBox("提交远程授权错误，交易无法继续进行");
                return false;
            }
        }
        /// <summary>
        /// 远程集中授权
        /// </summary>
        /// <param name="target"></param>
        /// <param name="pagedata"></param>
        /// <param name="accountno"></param>
        /// <param name="amount"></param>
        /// <param name="custname"></param>
        /// <param name="des"></param>
        /// <returns></returns>
        private bool remoteAuth(PageBase target, PageData[] pagedata, string accountno, double amount, string custname, string des)
        {

            if (AskAuth(target, pagedata, 1, accountno, amount, custname, des))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 本地授权
        /// </summary>
        /// <param name="target"></param>
        /// <param name="pagedata"></param>
        /// <param name="accountno"></param>
        /// <param name="amount"></param>
        /// <param name="custname"></param>
        /// <param name="des"></param>
        /// <param name="tradedata"></param>
        /// <returns></returns>
        private bool LocalAuth(PageBase target, PageData[] pagedata, string accountno, double amount, string custname, string des, TradeBusData tradedata)
        {
            ////不走工作流，向下传递流水号，页面名称，页面数据，交易数据
            AuthDataHelper authdata = new AuthDataHelper(target);
            //tradedata["AuthWay"] = "local";
            authdata.AuthWay = "local";
            if (AskAuth(target, pagedata, 1, accountno, amount, custname, des))
            {
                var authId = authdata.AuthId;//取本次的授权id
                target.OpenTradePage("Trade.OperationManage.T9906", TradePageExtension.OpenOptions.Dialog, null, tradedata);
                // if (tradedata["AuthFlag"] == "true") 
                //授权成功
                if (authdata.AuthFlag == "true" && authId == authdata.AuthId)//授权成功的判定，还需要加上授权id不变；为了防止多次发起授权窗口导致一次授权多次通过的bug
                {
                    this.Result(AsksuperResultType.Success, tradedata);
                    return true;
                }
                // else if (tradedata["AuthFlag"] == "false")
                //授权失败
                else if (authdata.AuthFlag == "false")
                {
                    this.Result(AsksuperResultType.Failed, tradedata);
                    //tradedata.Clear();
                    authdata.ClearAuthData();
                    return false;
                }
                // AuthFlag空表示撤销了
                else
                {
                    this.Result(AsksuperResultType.Undo, tradedata);
                    //tradedata.Clear(); 
                    //清空总线
                    authdata.ClearAuthData();
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 检查授权
        /// </summary>
        /// <param name="target"></param>
        /// <param name="Element"> 授权要素</param>
        /// <param name="msg">报文对象</param>
        /// <param name="accountno">交易账号</param>
        /// <param name="funcnum">授权条件序号</param>
        /// <param name="accountno">账号</param>
        /// <param name="amount">金额</param>
        /// <param name="custname">户名</param>
        /// <param name="count">积数</param>
        /// <param name="askDays">申请有效天数</param>
        /// <param name="inspDays">审批有效天数</param>
        /// <param name="upAmount">金额上限</param>
        /// <param name="PageData">页面数据</param>
        /// <param name="des">描述</param>
        /// <param name="Branch">指定机构号</Branch>
        /// <returns>true,需要预授权，且申请成功;false,不需要预授权，或申请不成功</returns>
        public bool DoPreAuth(PageBase target, string TradeNo, AuthConditionElement Element, Message msg, string funcnum, string accountno, string amount, string custname, string count, int askDays, int inspDays, double upAmount, byte[] PageData, string des, string Branch, bool downIssued)
        {
            //
            if (Element == null)
                return false;
            //((TradePage)target).GetCurrentTabItem().Tag = this;
            SetAuthManager(target, this);
            //var data = TradeInfoData.GetTradeInfo(target as DependencyObject);
            //if (data == null) return false;
            bool result = CheckAuth(target, Element, msg, TradeNo, funcnum, Branch, PageData);
            if (result)
            {
                AuthDataHelper authdata = new AuthDataHelper(target);
                // TradeBusData tradedata = data.TradeBus;//TradeBusData.GetTradeBusData((TradePage)target);
                //检查授权出现错误
                if (!bool.Parse(authdata.CheckFlag))
                {
                    return false;
                }
                else
                {
                    //预授权
                    if (authdata.AuthMode.EndsWith("1"))
                    {
                        if (AskPreAuth(target, TradeNo, accountno, amount, custname, count, askDays, inspDays, upAmount, PageData, des, downIssued))
                            return true;
                        else
                            return false;
                    }
                    return false;
                }
            }
            else
                return false;
        }

        /// <summary>
        /// 有授权结果时，调用此方法，激活此对象的回调函数
        /// 在收到授权的结果消息或者用户取消撤销申请时调用此函数
        /// </summary>
        /// <param name="type"></param>
        /// <param name="busData"></param>
        public void Result(AsksuperResultType type, TradeBusData busData)
        {
            if (this.AsksuperResultMessage != null)
                this.AsksuperResultMessage(type, busData);
        }

        /// <summary>
        /// 可能有多个交易已经申请授权，这里使用前端流水号来作为区别标识，
        /// 在授权有返回结果的时候使用它找到此对象并激活授权结果事件
        /// </summary>
        public string SystemSerialNumber
        {
            get;
            set;
        }

        #region 授权
        /// <summary>
        /// 检查复核
        /// </summary>
        /// <param name="target"></param>
        /// <param name="Element"> 复核要素</param>
        /// <param name="msg">报文对象</param>
        /// <param name="TradeNo">交易号</param>
        /// <param name="funcnum">复核条件序号</param>
        /// <param name="Branch">指定机构号</param>
        /// <returns></returns>
        private bool CheckAuth(PageBase target, AuthConditionElement Element, Message msg, string TradeNo, string funcnum, string Branch, byte[] pagedata)
        {
            bool result = false;
            CheckInfo checkinfo = new CheckInfo();
            checkinfo.tx_code = TradeNo;
            checkinfo.funcnum = funcnum;
            checkinfo.flag = 1;
            // TradeBusData tradedata = TradeInfoData.GetTradeInfo(target as DependencyObject).TradeBus;//TradeBusData.GetTradeBusData((TradePage)target);
            string element = MergeElement(Element, msg);
            checkinfo.element = element;
            CheckResult res = TradeHandle.Check(checkinfo);
            if (res == null)
            {
                throw new Exception("检查是否授权出错，请检查网络是否正常");
            }
            else
            {
                if (res.checkresult)
                {
                    AuthDataHelper authdata = new AuthDataHelper(target);
                    ClearDataBus(target, pagedata);
                    result = res.checkresult;
                    authdata.Lvl = res.lvl;
                    authdata.CheckFlag = "true";
                    // tradedata["lvl"] = res.lvl;
                    //指定机构号
                    if (res.brno.Contains('#'))
                    {
                        if (string.IsNullOrEmpty(Branch))
                        {
                            target.TradeAPIs.ShowErrorMessageBox("需要指定授权机构，但未指定");
                            // tradedata["CheckFlag"] = "false";
                            //检查授权出现错误
                            authdata.CheckFlag = "false";
                        }
                        else
                        {
                            authdata.Branch = Branch;
                            //tradedata["Branch"] = Branch;
                            //tradedata["CheckFlag"] = "true";
                        }
                    }
                    else
                    {
                        //tradedata["CheckFlag"] = "true";
                        //tradedata["Branch"] = res.brno;
                        authdata.Branch = res.brno;
                    }
                    //tradedata["AuthMode"] = res.mode;
                    authdata.AuthMode = res.mode;
                    authdata.AuthReason = res.des;
                    authdata.AuthPersonNum = res.personnum;

                }
            }
            return result;
        }

        /// <summary>
        /// 检查复核
        /// </summary>
        /// <param name="target"></param>
        /// <param name="Element"> 复核要素</param>
        /// <param name="msg">报文对象</param>
        /// <param name="TradeNo">交易号</param>
        /// <param name="funcnum">复核条件序号</param>
        /// <param name="Branch">指定机构号</param>
        /// <returns></returns>
        private bool CheckAuth_ZP(PageBase target, AuthConditionElement Element, Message msg, string TradeNo, string funcnum, string Branch, byte[] pagedata)
        {
            bool result = false;
            CheckInfo checkinfo = new CheckInfo();
            checkinfo.tx_code = TradeNo;
            checkinfo.funcnum = funcnum;
            checkinfo.flag = 1;
            // TradeBusData tradedata = TradeInfoData.GetTradeInfo(target as DependencyObject).TradeBus;//TradeBusData.GetTradeBusData((TradePage)target);
            string element = MergeElement(Element, msg);
            checkinfo.element = element;
            CheckResult res = new CheckResult();
            res.brno = "@";
            res.checkresult = true;
            res.des = "黑名单用户操作业务需要授权";
            res.lvl = "1,2,3,4";
            res.mode = "1000";
            res.personnum = "0";
            if (res == null)
            {
                throw new Exception("检查是否授权出错，请检查网络是否正常");
            }
            else
            {
                if (res.checkresult)
                {
                    AuthDataHelper authdata = new AuthDataHelper(target);
                    ClearDataBus(target, pagedata);
                    result = res.checkresult;
                    authdata.Lvl = res.lvl;
                    authdata.CheckFlag = "true";
                    // tradedata["lvl"] = res.lvl;
                    //指定机构号
                    if (res.brno.Contains('#'))
                    {
                        if (string.IsNullOrEmpty(Branch))
                        {
                            target.TradeAPIs.ShowErrorMessageBox("需要指定授权机构，但未指定");
                            // tradedata["CheckFlag"] = "false";
                            //检查授权出现错误
                            authdata.CheckFlag = "false";
                        }
                        else
                        {
                            authdata.Branch = Branch;
                            //tradedata["Branch"] = Branch;
                            //tradedata["CheckFlag"] = "true";
                        }
                    }
                    else
                    {
                        //tradedata["CheckFlag"] = "true";
                        //tradedata["Branch"] = res.brno;
                        authdata.Branch = res.brno;
                    }
                    //tradedata["AuthMode"] = res.mode;
                    authdata.AuthMode = res.mode;
                    authdata.AuthReason = res.des;
                    authdata.AuthPersonNum = res.personnum;

                }
            }
            return result;
        }
        /// <summary>
        /// 申请授权
        /// </summary>
        /// <param name="target"></param>
        /// <param name="basedatas"></param>
        /// <param name="Superdata"></param>
        /// <param name="accountno">账号</param>
        /// <param name="amount">金额</param>
        /// <param name="custname">用户名</param>
        /// <param name="des">复核描述</param>
        private bool AskAuth(PageBase target, PageData[] pagedata, int model, string accountno, double amount, string custname, string des)
        {
            TradePage page = (TradePage)target;
            TradeInfoData data = TradeInfoData.GetTradeInfo(target as DependencyObject);
            TradeBusData tradedata = data.TradeBus;
            AskAuthInfo askauth = new AskAuthInfo();
            askauth.accountno = accountno;
            askauth.amount = amount.ToString();
            askauth.model = model;
            askauth.custname = custname;
            askauth.des = des;
            string serials = page.CreateSerialNumber();// WorkFlowHandle.GenNextSerialNo("2000", LoginUserInfo.TellerNo, LoginUserInfo.KinbrNo, "20120523");
            //asksuper.serialID = tradedata["SerialId"] ;
            askauth.serialID = serials;
            askauth.TellerNo = LoginUserInfo.TellerNo;
            AuthDataHelper authdata = new AuthDataHelper(target);
            //远程授权
            if (model == 2)
            {
                authdata.AuthWay = "remote";
                //tradedata["AuthWay"] = "remote";
                askauth.WorkFlowID = "Auth";
                // 选择附件对话框
                //TODO chenming 20140424 承德银行暂时不要附件 begin
                //OpenImageFilesViewer of = new OpenImageFilesViewer();
                //target.OpenTradePage(of, TradePageExtension.OpenOptions.Dialog);
                //string f = "";
                //// 等于null表示取消了或者没有附件
                //if (of.FilesId != null) 
                //{
                //    for (int i = 0; i < of.FilesId.Length; i++)
                //    {
                //        f += of.FilesId[i];
                //        f += i == of.FilesId.Length - 1 ? "" : "|";
                //    }
                //}
                //authdata.ImageId = f;
                //TODO  end
                authdata.IsWorkFlow = "true";
            }
            tradedata["TradeNo"] = data.TradeCode;
            // "开户交易";
            tradedata["TradeName"] = data.TradeName;
            tradedata["SerialId"] = serials;
            //tradedata["AuthType"] = "auth";
            authdata.AuthType = "auth";
            tradedata["TellerNo"] = LoginUserInfo.TellerNo;
            string authid = TradeHandle.AskAuth(askauth, (Dictionary<string, string>)tradedata.Serialize(), pagedata);
            if (string.IsNullOrEmpty(authid))
            {
                return false;
            }
            else
            {
                if (model == 1) //本地授权
                {
                    authdata.AuthId = authid;
                    // tradedata["AuthId"] = authid;
                }
                return true;
            }

        }
        /// <summary>
        /// 申请预授权
        /// </summary>
        /// <param name="target"></param>
        /// <param name="basedatas"></param>
        /// <param name="Superdata"></param>
        /// <param name="accountno">账号</param>
        /// <param name="amount">金额</param>
        /// <param name="custname">用户名</param>
        /// <param name="des">复核描述</param>
        private bool AskPreAuth(PageBase target, string tradeNo, string accountno, string amount, string custname, string count, int askDays, int inspDays, double upAmount, byte[] PageData, string des, bool downIssued)
        {
            TradePage page = (TradePage)target;
            string serials = page.CreateSerialNumber();
            TradeBusData tradedata = TradeInfoData.GetTradeInfo(target as DependencyObject).TradeBus;
            PreAuthInfo preAuthInfo = new PreAuthInfo();
            AuthDataHelper authdata = new AuthDataHelper(target);
            preAuthInfo.SerialId = serials;
            preAuthInfo.AccountNum = accountno;
            preAuthInfo.Amount = amount;
            preAuthInfo.Custname = custname;
            preAuthInfo.AskDays = askDays;
            preAuthInfo.AskKinbrno = LoginUserInfo.KinbrNo;
            preAuthInfo.AskTeller = LoginUserInfo.TellerNo;
            preAuthInfo.Count = count;
            preAuthInfo.Des = des;
            preAuthInfo.DownAmount = 0;
            preAuthInfo.InspDays = inspDays;
            preAuthInfo.PageData = PageData;
            preAuthInfo.TradeNo = tradeNo;
            preAuthInfo.UpAmount = upAmount;
            preAuthInfo.DownIssued = downIssued;
            preAuthInfo.LegalPerson = LoginAuthentication.Instance.GroupKinbrNo;
            tradedata["TradeNo"] = page.TradeModel.Code;
            tradedata["TradeName"] = page.TradeModel.Name;
            tradedata["SerialId"] = serials;
            //tradedata["AuthType"] = "preauth";
            authdata.AuthType = "preauth";
            tradedata["TellerNo"] = LoginUserInfo.TellerNo;
            if (TradeHandle.AskPreAuth("Auth", preAuthInfo, (Dictionary<string, string>)tradedata.Serialize()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 整合核心返回要素值与前台要素值
        /// </summary>
        /// <param name="property"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        private string MergeElement(AuthConditionElement Element, Message msg)
        {
            StringBuilder result = new StringBuilder();
            result.Append("{\"Message\":");
            if (msg != null)
            {
                result.Append(msg.SerializeForAuth());
            }
            else
            {
                result.Append("[]");
            }
            result.Append(",\"Element\":");
            if (Element != null)
            {
                result.Append(Element.JsonValue);
            }
            else
            {
                result.Append("[]");
            }
            result.Append("}");
            return result.ToString();
        }
        /// <summary>
        /// 如果之前做过授权或复核，则清空总线数据
        /// </summary>
        /// <param name="tradedata"></param>
        private void ClearDataBus(PageBase target, byte[] pagedata)
        {
            var data = TradeInfoData.GetTradeInfo(target as DependencyObject);
            //TradeBusData tradedata = data.TradeBus;
            AuthDataHelper authdata = new AuthDataHelper(target);
            CheckDataHelper checkdata = new CheckDataHelper(target);
            if (!string.IsNullOrEmpty(authdata.AuthFlag) || !string.IsNullOrEmpty(checkdata.SuperFlag)) //之前做过复核或授权操作
            {
                // 将上一流程的提交岗向服务端提交数据
                var tradeInfo = new TellerInfo
                {
                    TellerNo = LoginUserInfo.TellerNo,
                    TradeNo = data.TradeCode,
                    Tlrlvl = "",
                    BrNo = LoginUserInfo.KinbrNo,
                    //默认为1，标明该流程为正常结束
                    Status = 0,
                    TradeFileName = target.GetType().FullName,
                    BusinessDate = LoginUserInfo.TradeDate
                };
                WorkFlowHandle.GetWorkFlowTradeSubmit(
                                tradeInfo, pagedata, (Dictionary<string, string>)data.TradeBus.Serialize(), authdata.WorkItemId, target.CreateSerialNumber(), false, true);
                authdata.ClearAuthData();
                checkdata.ClearCheckData();
            }
        }
        #endregion

        #region GetPageImages
        /// <summary>
        /// 获取交易页面的截图集合
        /// </summary>
        /// <param name="page"></param>
        /// <param name="per"></param>
        /// <returns></returns>
        public static List<ImageSource> GetPageImages(PageBase page, double per = 600)
        {
            return GetPageImages(page, null, per);
        }

        /// <summary>
        /// 获取交易页面的截图集合
        /// </summary>
        /// <param name="page"></param>
        /// <param name="title"></param>
        /// <param name="per"></param>
        /// <returns></returns>
        public static List<ImageSource> GetPageImages(PageBase page, string title, double per = 600)
        {
            var ret = new List<ImageSource>();
            if (page != null)
            {

                var content = page as FrameworkElement;
                ////若存在tab页签，则为了照顾整合交易，需要获取到tab页下的pagebase
                //var tabs = content.FindVisualTreeAncestor(x => x is TabControl && (x as TabControl).SelectedItem is PageBase) as TabControl;
                //  if (tabs != null)
                //    content = (tabs.SelectedItem as PageBase) as FrameworkElement;
                //  var sv = FirstVisualTreeChildren(content ,x => x is ScrollViewer && (x as ScrollViewer).Name == "PART_ScrollViewer") as ScrollViewer;
                var sv = content.FirstVisualTreeChildren(x => x is ScrollViewer && (x as ScrollViewer).Name == "TradeScrollViewer") as ScrollViewer;
                //  PART_ScrollContentPresenter
                if (sv != null)
                    content = sv.Content as FrameworkElement;
                var width = 800;
                //原始图像
                var dv = new DrawingVisual();
                using (var dc = dv.RenderOpen())
                {
                    dc.DrawRectangle(Brushes.WhiteSmoke, null, new Rect(new Size(width + 240, content.ActualHeight)));// + per
                    var p = new Point();
                    //补充title的位置
                    if (!string.IsNullOrEmpty(title))
                    {
                        dc.DrawText(new FormattedText(title, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("SimSun"), 18, Brushes.Black), new Point(10, 3));
                        p.Y = 30;
                    }
                    var brush = new VisualBrush(content)
                    {
                        Stretch = Stretch.None,
                        AlignmentX = AlignmentX.Center,
                        AlignmentY = AlignmentY.Top,
                    };
                    //界面要素Title没截全，水平偏移加50
                    dc.DrawRectangle(brush, null, new Rect(p, new Size(content.ActualWidth + 50, content.ActualHeight)));
                }
                //循环裁剪，按照per来裁剪高
                var height = 0.00;
                //while (height < content.ActualHeight)
                //{
                //本次裁剪高度
                var rect = new Rect(0, height, width, content.ActualHeight + 40);
                if (height > 0)
                    rect.Y -= 30;
                var rtb = new RenderTargetBitmap((int)rect.Width + 240, (int)rect.Height, 96, 96, PixelFormats.Default);
                dv.Transform = new TranslateTransform(-rect.X, -rect.Y);
                rtb.Render(dv);
                ret.Add(rtb);
                //  height += per;
                //}
            }
            return ret;
        }
        #endregion
    }
}
