using CallCenterApi.Interface.Controllers.Login;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ZXDT.CallCenter.Model;
using ZXDT.CallCenter.MVCWeb.Models;
using ZXDT.Common;

namespace ZXDT.CallCenter.MVCWeb.Controllers
{
    public class DefaultController : Controller
    {
        BLL.T_Sys_UserAccount busUserInfo = new BLL.T_Sys_UserAccount();

        public ActionResult Login()
        {
            T_Sys_UserAccount userInfo = new T_Sys_UserAccount();
            HttpCookie cookies = Request.Cookies["platform"];
            //判断是否有cookie值，有的话就读取出来
            if (cookies != null && cookies.HasKeys)
            {
                userInfo.F_UserName = cookies["Name"];

            }

            userInfo.ExtensionCode = ConfigurationManager.AppSettings["sso"].ToMyString();
           // userInfo.F_UserName = SystemInfo.GetCpuPerformancevalue();
            return View(userInfo);
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public string LoginIn(string username, string extensionphone, string password,string logintime)
        {

            string res = "未知错误，请重新登录";
            DataTable dt = new DataTable();
            try
            {
                #region 密码解密
                string st = DateTime.Parse(logintime).ToString("HHmmss");
                var otherController = DependencyResolver.Current.GetService<AES256Controller>();
                string pw = "";
                try
                {
                    pw = otherController.Decrypt(password.Trim(), st);

                }
                catch (Exception e)
                {
                    res = "错误:" + e.Message;
                   
                }
                #endregion


                dt = busUserInfo.GetList(username, pw).Tables[0];
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["F_UserCode"].ToString() == dt.Rows[0]["F_PassWord"].ToString())
                        {
                            res = "firstlogin" + dt.Rows[0]["F_UserId"].ToString();
                        }
                        else
                        {

                            //记住用户名每3个月更换一次
                            HttpCookie cookie = new HttpCookie("platform");
                            cookie.Values.Add("Name", username);
                            cookie.Values.Add("islocal", "1");
                            cookie.Expires = System.DateTime.Now.AddMonths(3);
                            Response.Cookies.Add(cookie);


                            if (!string.IsNullOrEmpty(extensionphone))
                            {
                            }
                            else if (string.IsNullOrEmpty(dt.Rows[0]["F_ExtensionNumber"].ToMyString()))
                            {
                                extensionphone = dt.Rows[0]["ExtensionCode"].ToMyString();
                            }
                            else
                            {
                                extensionphone = dt.Rows[0]["F_ExtensionNumber"].ToMyString();
                            }
                            int tempExtensionphone = GetNetworkAdpaterID();
                            if (tempExtensionphone > 0)
                            {
                                extensionphone = tempExtensionphone.ToMyString();
                            }
                            LogHelper.Default.WriteInfo("tsKey:" + extensionphone);
                            Dictionary<string, string> Dic = new Dictionary<string, string>();
                            Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToString());
                            Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToString());
                            Dic.Add("F_DeptId", dt.Rows[0]["F_DeptId"].ToString());
                            Dic.Add("F_UserName", HttpUtility.UrlEncode(dt.Rows[0]["F_UserName"].ToString(), Encoding.UTF8));
                            Dic.Add("F_Telephone", dt.Rows[0]["F_Telephone"].ToString());
                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());
                            Dic.Add("F_SeatFlag", dt.Rows[0]["F_SeatFlag"].ToString());
                            Dic.Add("F_PId", dt.Rows[0]["F_PId"].ToString());
                            if (dt.Rows[0]["F_GroupId"].ToString() != null)
                            {
                                Dic.Add("F_GroupId", dt.Rows[0]["F_GroupId"].ToString());
                            }
                            if (dt.Rows[0]["F_SeatRight"].ToString() != null)
                            {
                                Dic.Add("F_SeatRight", dt.Rows[0]["F_SeatRight"].ToString());
                            }

                            Dic.Add("F_ExtensionNumber", extensionphone);
                            Dic.Add("F_WorkNumber", dt.Rows[0]["F_WorkNumber"].ToString());

                            CookieUtil.SetCookie("BaseCallCenter_T_User", Dic);

                            //写入登录日志
                            new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                F_Result = "登录成功",
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                            Common.CommonRequest.dtUserId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString());
                            Common.CommonRequest.dtUserCode = dt.Rows[0]["F_UserCode"].ToString();//Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString());
                            res = "success";
                            //绑定登录用户分机号
                            BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();
                            bll.UpdateWXId("ExtensionCode",extensionphone.ToInt32(), Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()));                        }
                    }
                    else
                    {
                        //写入登录日志
                        DataTable dt1 = busUserInfo.GetList("F_UserCode='" + username + "'").Tables[0];
                        if (dt1.Rows.Count > 0)
                        {
                            int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {

                                F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                F_Result = "登录失败：帐号-" + username + ";分机号-" + extensionphone,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }
                        else
                        {
                            int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = username,
                                F_LoginId = -1,
                                F_Result = "登录失败：帐号-" + username + ";分机号-" + extensionphone,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }
                        res = "账号或密码错误，请重新登录";
                    }
                }
                else
                {
                    res = "账号或密码错误，请重新登录";
                }

            }
            catch (Exception ex)
            {
                res = "错误:" + ex.ToString();
                SysLog.WriteLog(ex);
            }
            finally
            {
                dt.Clear();
                dt.Dispose();

            }

            return res;

        }
        //退出系统
        [AcceptVerbs(HttpVerbs.Post)]
        public string LoginOut(string username)
        {
            string res = "未知错误，请重新登录";
            DataTable dt = new DataTable();
            try {
                string userid = Request.Cookies["BaseCallCenter_T_User"]["F_UserId"];
                dt = busUserInfo.GetList("F_UserId='" + userid + "'").Tables[0];
                //写入登录日志
                new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                {
                    F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                    F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                    F_Result = "退出系统成功",
                    F_LoginIP = Common.DTRequest.GetIP(),
                    F_Hostname = Common.DTRequest.GetIP(),
                    F_LoginDate = DateTime.Now,
                    F_Remark = "",
                    F_State = 0
                });
                res = "success";
                //绑定登录用户分机号
                BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();
                bll.UpdateWXId("ExtensionCode", 0, Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()));
            



            }
            catch(Exception){ }

            return res;
        }




        public ActionResult SSO()
        {
            bool res = false; //标记是否登录


            string LoginName=Request.Headers.Get("OAM_REMOTE_USER");
            LogHelper.Default.WriteInfo("LoginName:" + LoginName.ToMyString());
            if (!string.IsNullOrEmpty(LoginName))
            {
               
                if (!"Anonymous".Equals(LoginName))
                {
                    res = true;
                    TimeSpan ts = DateTime.Now - new DateTime(1999, 1, 1, 0, 0, 0, 0);
                    int ss = Convert.ToInt32(ts.TotalSeconds);
                    string key = DESEncrypt.Encrypt(ss.ToString(), "SSO" + LoginName);
                    return new RedirectResult(string.Format("{2}/default/SSOShow?userid={0}&key={1}", LoginName, key, ConfigurationManager.AppSettings["domain"]));
                }
            }

            return View();
        }
        public ActionResult SSOShow()
        {

            ReturnData rd = new ReturnData { code = -1, msg = "默认错误",data= ConfigurationManager.AppSettings["sso"] };
            string userid = Request.QueryString["userid"].ToMyString();
            string key = Request.QueryString["key"].ToMyString();

            if (userid != "" && key != "")
            {
                TimeSpan ts = DateTime.Now - new DateTime(1999, 1, 1, 0, 0, 0, 0);
                int tsInt = Convert.ToInt32(ts.TotalSeconds); 

                int tsKey = DESEncrypt.Decrypt(key, "SSO" + userid).ToInt32();
                //LogHelper.Default.WriteInfo("tsInt:" + tsInt.ToMyString());
                //LogHelper.Default.WriteInfo("tsKey:" + tsKey.ToMyString());
                if (tsInt - tsKey < 5)
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        DataSet ds = busUserInfo.GetList(" F_UserCode=" + userid);

                        if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                        {
                            dt = ds.Tables[0];

                            rd.code = 0;
                            rd.msg = "成功";
                            //记住用户名每3个月更换一次
                            HttpCookie cookie = new HttpCookie("platform");
                            cookie.Values.Add("Name", userid);
                            cookie.Values.Add("islocal", "0");
                            cookie.Expires = System.DateTime.Now.AddMonths(3);
                            Response.Cookies.Add(cookie);

                            string extensionphone = "";
                            if (!string.IsNullOrEmpty(extensionphone))
                            {                               
                            }
                            else if (string.IsNullOrEmpty(dt.Rows[0]["F_ExtensionNumber"].ToMyString()))
                            {
                                extensionphone = dt.Rows[0]["ExtensionCode"].ToMyString();
                            }
                            else
                            {
                                extensionphone = dt.Rows[0]["F_ExtensionNumber"].ToMyString();
                            }
                            int tempExtensionphone = GetNetworkAdpaterID();
                            if (tempExtensionphone > 0)
                            {
                                extensionphone = tempExtensionphone.ToMyString();
                            }



                            Dictionary<string, string> Dic = new Dictionary<string, string>();
                            Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToMyString());
                            Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToMyString());
                            Dic.Add("F_DeptId", dt.Rows[0]["F_DeptId"].ToMyString());
                            Dic.Add("F_UserName", HttpUtility.UrlEncode(dt.Rows[0]["F_UserName"].ToMyString(), Encoding.UTF8));
                            Dic.Add("F_Telephone", dt.Rows[0]["F_Telephone"].ToMyString());
                            Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToMyString());
                            Dic.Add("F_SeatFlag", dt.Rows[0]["F_SeatFlag"].ToMyString());
                            Dic.Add("F_PId", dt.Rows[0]["F_PId"].ToMyString());
                            Dic.Add("F_GroupId", dt.Rows[0]["F_GroupId"].ToMyString());
                            Dic.Add("F_SeatRight", dt.Rows[0]["F_SeatRight"].ToMyString());
                            Dic.Add("F_ExtensionNumber", extensionphone);
                            Dic.Add("F_WorkNumber", dt.Rows[0]["F_WorkNumber"].ToMyString());

                            CookieUtil.SetCookie("BaseCallCenter_T_User", Dic);


                            //写入登录日志
                            new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                F_LoginId = dt.Rows[0]["F_UserId"].ToInt32(),
                                F_Result = "单点登录成功",
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                            Common.CommonRequest.dtUserId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString());
                            Common.CommonRequest.dtUserCode = dt.Rows[0]["F_UserCode"].ToString();
                            //绑定登录用户分机号
                            BLL.T_Sys_UserAccount bll = new BLL.T_Sys_UserAccount();
                            bll.UpdateWXId("ExtensionCode", extensionphone.ToInt32(), dt.Rows[0]["F_UserId"].ToInt32());

                        }
                        else
                        {
                            rd.msg = "没有权限";
                        }


                    }
                    catch (Exception ex)
                    {
                        rd.msg = "error";
                        LogHelper.Default.WriteError(ex.Message, ex);
                    }
                    finally
                    {
                        dt.Clear();
                        dt.Dispose();
                    }
                }
                else
                {
                    rd.msg = "非法路径";
                }
            }
            else
            {
                rd.msg = "没有登录";
            }

            if (rd.code == 0)
            {
                return RedirectToAction("Index", "Main");
            }
            else
                return View(rd);
        }

        /// <summary>
        /// 获取网卡ID代码
        /// </summary>
        /// <returns></returns>
        public static int GetNetworkAdpaterID()
        {
            int ret = 0;
            //NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            //if (nics != null && nics.Length > 0)
            //{
            //    foreach (NetworkInterface nic in nics)
            //    {   string mac = nic.GetPhysicalAddress().ToString();
            //        LogHelper.Default.WriteInfo("MAC:" + mac);
            //        if (string.IsNullOrEmpty(mac))
            //            continue;
            //        ret = new BLL.T_Mac().GetNum(mac);
            //        if (ret > 0)
            //        {
            //            LogHelper.Default.WriteInfo("MAC1:" + mac);
            //            break;
            //        }
            //    }
            //}
            string mac = GetClientMAC();
            ret = new BLL.T_Mac().GetNum(mac);
            return ret;
        }
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        private static string GetClientMAC()
        {
            string mac_dest = string.Empty;
            // 在此处放置用户代码以初始化页面
            try
            {
                string userip = System.Web.HttpContext.Current.Request.UserHostAddress;
                string strClientIP = System.Web.HttpContext.Current.Request.UserHostAddress.ToString().Trim();
                Int32 ldest = inet_addr(strClientIP); //目的地的ip 
                Int32 lhost = inet_addr("");   //本地服务器的ip 
                Int64 macinfo = new Int64();
                Int32 len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }
                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }

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

    }
}
