using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using QMAPP.ServicesAgent;
using QMAPP.FJC.Entity;
using System.Configuration;
using QMAPP.WinForm.Common;
using System.Windows.Forms;
namespace QMAPP.WinForm
{
    /// <summary>
    /// 应用上下文
    /// </summary>
    public class ClientContext
    {
        /// <summary>
        /// sessionID
        /// </summary>
        public static string SessionID { get; set; }

        /// <summary>
        /// 当前加工计数器
        /// </summary>
        public static int MadeNum = 0;

        /// <summary>
        /// 登录信息
        /// </summary>
        public static QMAPP.ServicesAgent.LoginService.LoginInfo LoginInfo { get; set; }

        /// <summary>
        /// 设备信息
        /// </summary>
        public static QMAPP.FJC.Entity.Basic.MachineInfo MachineInfo { get; set; }

        /// <summary>
        /// 班次信息
        /// </summary>
        public static QMAPP.FJC.Entity.Basic.ProduceShift produceShift { get; set; }

        /// <summary>
        /// 权限列表
        /// </summary>
        public static Dictionary<string, FormAuthority> AuthList = new Dictionary<string, FormAuthority>();
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Init()
        {
            //设置sessionID
            SessionID = Guid.NewGuid().ToString();

            //初始化服务
            ServiceAgent.Init();
            string locationfile = System.Configuration.ConfigurationManager.AppSettings["loactionfile"];
            if (System.IO.File.Exists(locationfile))
            {
                string machinecode = System.IO.File.ReadAllText(locationfile);
                if (!string.IsNullOrEmpty(machinecode.Trim()))
                {
                    //设置ip
                    QMAPP.FJC.Entity.Basic.MachineInfo searchModel = new QMAPP.FJC.Entity.Basic.MachineInfo();
                    searchModel.MACHINECODDE = machinecode.Trim();
                    List<QMAPP.FJC.Entity.Basic.MachineInfo> list = new List<FJC.Entity.Basic.MachineInfo>();
                    //searchModel.PRODUCELINE = QMAPP.FJC.Entity.EnumGeter.PRODUCELINE.B9.ToString();
                    //执行查询
                    QMAPP.ServicesAgent.ServiceAgent agent = ClientContext.GetServiceAgent();
                    list = agent.InvokeServiceFunction<List<QMAPP.FJC.Entity.Basic.MachineInfo>>(B9BasicService.MachineInfoBLL_GetAllList.ToString(), searchModel);
                    if (list.Count > 0)
                    {
                        MachineInfo = list[0];
                    }
                }
            }
            #region 定位设备工位 OLDCODE
            /*
            //获取设备信息
            if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains("ipFlag"))
            {
                string ipFlag = System.Configuration.ConfigurationManager.AppSettings["ipFlag"].ToString();
                if (ipFlag.Equals("0"))//代表没有ip用config中的machinecode来匹配
                {
                    if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains("machineCode"))
                    {
                        string machineCode = System.Configuration.ConfigurationManager.AppSettings["machineCode"].ToString();
                        if (!string.IsNullOrEmpty(machineCode.Trim()))
                        {
                            //设置ip
                            QMAPP.FJC.Entity.Basic.MachineInfo searchModel = new QMAPP.FJC.Entity.Basic.MachineInfo();
                            searchModel.MACHINECODDE = machineCode.Trim();
                            List<QMAPP.FJC.Entity.Basic.MachineInfo> list = new List<FJC.Entity.Basic.MachineInfo>();
                            searchModel.PRODUCELINE = QMAPP.FJC.Entity.EnumGeter.PRODUCELINE.B9.ToString();
                            //执行查询
                            QMAPP.ServicesAgent.ServiceAgent agent = ClientContext.GetServiceAgent();
                            list = agent.InvokeServiceFunction<List<QMAPP.FJC.Entity.Basic.MachineInfo>>(B9BasicService.MachineInfoBLL_GetAllList.ToString(), searchModel);
                            if (list.Count > 0)
                            {
                                MachineInfo = list[0];
                            }
                        }
                    }
                }
                else if (ipFlag.Equals("1"))
                {
                    IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
                    IPAddress ipa = ipe.AddressList[1];
                    string ipAddress = ipa.ToString();
                    if (!string.IsNullOrEmpty(ipAddress))
                    {
                        //设置ip
                        QMAPP.FJC.Entity.Basic.MachineInfo searchModel = new QMAPP.FJC.Entity.Basic.MachineInfo();
                        searchModel.IPADDRESS = ipAddress;
                        List<QMAPP.FJC.Entity.Basic.MachineInfo> list = new List<FJC.Entity.Basic.MachineInfo>();
                        searchModel.PRODUCELINE = QMAPP.FJC.Entity.EnumGeter.PRODUCELINE.B9.ToString();
                        //执行查询
                        QMAPP.ServicesAgent.ServiceAgent agent = ClientContext.GetServiceAgent();
                        list = agent.InvokeServiceFunction<List<QMAPP.FJC.Entity.Basic.MachineInfo>>(B9BasicService.MachineInfoBLL_GetAllList.ToString(), searchModel);
                        if (list.Count > 0)
                        {
                            MachineInfo = list[0];
                        }
                    }
                }
            }
            */
            #endregion
            //获取班组信息
            produceShift = new FJC.Entity.Basic.ProduceShift();
            QMAPP.ServicesAgent.ServiceAgent agent1 = ClientContext.GetServiceAgent();
            var shift = agent1.InvokeServiceFunction<FJC.Entity.Basic.ProduceShift>(B9BasicService.ProduceShiftBLL_GetWorkingShift.ToString(), MachineInfo != null ? MachineInfo.WORKCENTER_CODE : "");
            if (shift != null)
            {
                produceShift = shift;
            }
        }

        #region 获取服务代理

        public static ServicesAgent.ServiceAgent GetServiceAgent()
        {
            try
            {
                //创建代理
                ServicesAgent.ServiceAgent agent = new ServicesAgent.ServiceAgent();

                //设置凭据
                agent.ClientCredential = new QMFrameWork.ServiceInterface.CredentialInfo();
                if (ClientContext.LoginInfo != null)
                    agent.ClientCredential.UserID = ClientContext.LoginInfo.UserID;
                agent.ClientCredential.CredentialID = ClientContext.SessionID;

                return agent;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion    

        #region 获取登录凭据

        public static QMFrameWork.ServiceInterface.CredentialInfo GetCredentialInfo()
        {
            QMFrameWork.ServiceInterface.CredentialInfo credential = new QMFrameWork.ServiceInterface.CredentialInfo();
            credential.CredentialID = ClientContext.SessionID;

            return credential;
        }

        /// <summary>
        /// 设定用户权限
        /// </summary>
        /// <param name="MenuName"></param>
        /// <param name="c"></param>
        public static void SetUserAuth(string MenuName,System.Windows.Forms.Control c)
        {
            if (AuthList.Count > 0)
            {


                System.Windows.Forms.Control[] cs = c.Controls.Find("toolStrip1", false);
                if (cs.Length > 0)
                {
                    var MenuId = from en
                                   in AuthList
                                 where en.Value.Equals(MenuName)
                                 select en.Key;
                    var listValues = from en
                                                  in AuthList
                                     where en.Key.Substring(0, 5).Equals(MenuId.First().ToString().Substring(0, 5))
                                     select en.Value;

                    for (int i = 0; i < ((System.Windows.Forms.ToolStrip)cs[0]).Items.Count; i++)
                    {
                        //if (listValues.Contains(((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Name))
                        //{
                        //    ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Visible = true;
                        //    ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Enabled = true;
                        //}
                        //else
                        //{
                        //    ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Visible = false;
                        //    ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Enabled = false;
                        //}
                    }
                }
            }
        }
        /// <summary>
        /// 设定用户权限
        /// </summary>
        /// <param name="c"></param>
        public static void SetUserAuth(System.Windows.Forms.Form form)
        {
            System.Windows.Forms.Control[] toolStrips = form.Controls.Find("toolStrip1", false);
            var toolstrip = (System.Windows.Forms.ToolStrip)toolStrips.FirstOrDefault();
            var authOnform=from auth in AuthList 
                           where auth.Value.Form==form.Name
                           select auth.Value;
            
            foreach (var auth in authOnform)
            {
                if(string.IsNullOrWhiteSpace(auth.Button))
                {
                    continue;
                }
                var controls = form.Controls.Find(auth.Button, true);
                if (controls.Length > 0)
                {
                    foreach (var btn in controls)
                    {
                        btn.Enabled = auth.HasAuthority || string.Equals(LoginInfo.LoginUserID.ToUpper(), "ADMIN");
                        btn.Visible = auth.HasAuthority || string.Equals(LoginInfo.LoginUserID.ToUpper(), "ADMIN");
                    }
                    continue;
                }
                if (toolstrip != null)
                {
                    var toolstripitems = toolstrip.Items.Find(auth.Button, true);
                    if (toolstripitems.Length > 0)
                    {
                        foreach (var btn in toolstripitems)
                        {
                            btn.Enabled = auth.HasAuthority || string.Equals(LoginInfo.LoginUserID.ToUpper(), "ADMIN");
                            btn.Visible = auth.HasAuthority || string.Equals(LoginInfo.LoginUserID.ToUpper(), "ADMIN");
                        }
                    }
                }
            }

            //if (AuthList.Count > 0)
            //{


            //    
            //    if (cs.Length > 0)
            //    {
            //        var MenuId = from en
            //                       in AuthList
            //                     where en.Value.Equals(MenuName)
            //                     select en.Key;
            //        var listValues = from en
            //                                      in AuthList
            //                         where en.Key.Substring(0, 5).Equals(MenuId.First().ToString().Substring(0, 5))
            //                         select en.Value;

            //        for (int i = 0; i < ((System.Windows.Forms.ToolStrip)cs[0]).Items.Count; i++)
            //        {
            //            if (listValues.Contains(((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Name))
            //            {
            //                ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Visible = true;
            //                ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Enabled = true;
            //            }
            //            else
            //            {
            //                ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Visible = false;
            //                ((System.Windows.Forms.ToolStrip)cs[0]).Items[i].Enabled = false;
            //            }
            //        }
            //    }
            //}
        }

        /// <summary>
        /// 登录码登录
        /// </summary>
        /// <param name="passcode"></param>
        /// <returns></returns>
        public static string CodeLogin(string passcode)
        {
            if (passcode.StartsWith("<") && passcode.EndsWith(">"))
            {
                var passport = passcode.Trim('<', '>').Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
                if (passport.Length == 2)
                {
                    string userid = passport[0];
                    string pwd = passport[1];
                    try
                    {
                        QMAPP.ServicesAgent.LoginService.LoginServiceClient _loginClient = new ServicesAgent.LoginService.LoginServiceClient();

                        pwd = QMFrameWork.Common.Encrypt.DESEncrypt.Decrypt(pwd);
                        //登录验证
                        var loginUser = _loginClient.IsLogin(new QMAPP.ServicesAgent.LoginService.LoginInfo { LoginUserID = userid, PassWord = pwd, UserDes = "" }
                            , ClientContext.GetCredentialInfo());

                        if (loginUser == null)
                        {
                            return "登录码不正确或已过期,请联系管理员更换!";
                        }

                        ClientContext.LoginInfo = loginUser;
                        //打开主窗体
                        MainForm form = Application.OpenForms["MainForm"] as MainForm;  //查找是否打开过Form1窗体
                        if (form != null)  //没打开过
                        {
                            form.SetLoginInfo(loginUser);
                        }
                        return "登录成功!";
                    }
                    catch (System.Security.Cryptography.CryptographicException)
                    {
                        return "登录码格式不正确!";
                    }
                    catch (System.FormatException)
                    {
                        return "登录码格式不正确!";
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            return "";

        }
        #endregion
        /// <summary>
        /// OPC服务状态
        /// 0:不使用OPC连接
        /// 1: OPC连接正常
        /// 2: OPC连接断开(发送失败)
        /// 3:OPC连接断开(无法接收返回消息或接收超时)
        /// 4: 正在连接
        /// </summary>
        public static int OpcState { get; set; }
    }
}