using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Model;
using RMYY_CallCenter_Api.Models;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace RMYY_CallCenter_Api.Controllers
{
    [AllowAnonymous]
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            return Content("hello world!");
        }

        public ActionResult Daochu()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("code");
            dt.Columns.Add("name");
            DataRow dr = dt.NewRow();
            dr["code"] = "asd";
            dr["name"] = "咋说";
            dt.Rows.Add(dr);

            new NPOIHelper().ExportToExcel2("123", dt);
            return Content("hello world!");
        }
        private string Locking = ConfigHelper.GetValue("Locking");

        private string  privateKey =
"MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDPR0D1+EUM48JkzYWIsZYlbCx2WlbB2MGdyaW9ovva3C3ridbPQ5iWVfmlkd" +
            "yxWVdejrIJ3GAqz4oJkwNnBsiXIVcGEd89M9kKfGBMDRrwsKWzTa33kz4G4znOdIR9FYqij07b0ZhCrOxj4+As1qhz6fiaom0XxlCzbm" +
            "qv3LWVAMt+1PXbcz+nOWjYcyfq6CZi4wogtSmi4xaxBXSykC/0kbUxXS6vgJsxl49KD37l2SLNJMHbeUbircPzeEb88AkZWalYbKFM0uN09idvy" +
            "Y7kmIR6By1bX4oq5d9wMUvT4URdrrBBt/f6lvkqbhdWYYuXnYq/W95ZCed9lR9liJ/zAgMBAAECggEBAMHn+YhhWk9lnkxoy5wF7d1SZgHOH002tm" +
            "Ii6w8Nsqiaw8aN60t4A/3XrjTK0HeEiaxmt31sEPbbslmkk1FFUk+3m86M15dMsqURl5Btzh8OUeT8LVvm/ea5mTFfZTYS+d97Sx1u5Q6y8G2+FtA7" +
            "e9j8L1qRypasKoDBMcMVKTWamM5Ckmyfvqey3kb2oUvAuHrEvzeyoJWmiWwAH+imOjM7fM356/7f9DfZ2+VYwoYG6TKZsTfAKOq7fQIKLsbewNJeOJ9Y" +
            "NUIkSXKOQlh+xrTpMBplCA/bGHOWHR8FxqCYbti/NcLeCz2/e13e31BP3i4/ifb6Z6vdyHfJgzk1yzkCgYEA/W+6ki3Pi4z7PikCNIIq/k7UINvHoEM" +
            "vgpQq5wRtL83d85/n1vpEWlT+f5aDtjmj4LINiFekqKx7j3gkRO9xdDty2ZnPlq1ErN2GM1bW7GOdMCqDTrYiwqypd0YX5tAciW6rrMRlNmUHV+V0ay/Q8iy" +
            "UvrOUg+L1BM+AEmGapyUCgYEA0V//vgDdwEoFjfGIUxc5Lai3R1Fjb9OYClZpYzUPs6T8OAO/wFpN37a2bu/XusxUMa9y/NzrPh2XiwF1jRcyPrp9C" +
            "TgMTi2n/rPD/uAo11fBvWUNWTLrAxE55xwLbtWIOoFApJY9XUI41gnvl4S02536PGd9SM5J4WIZduE1qzcCgYEA/B8jfvq95vlIlC0duXjpJnbrRwj" +
            "9jexonkGicJIRwSXPMOcaL95nE2pMiEcHHsg2xHi9R67Q6tA0V6TQiBegSV4+wkTmo+IZWNNEB1zTkPUEUf9pA2vkJsC4EiUT8BWG3h3QAZ6bhcJ5zLJ" +
            "C38MA3XsGOrTSAWZOFAwNP7wDq1UCgYEAlje2GPAuKUPycECWembzExs1Q+nU2eqJ7wDIY/Ex7sW0X8vwy2T+8j747OcPdGodDfi/G0S1Ur+Qdp75Y9z8o" +
            "5zREMgxq/V9znPTbw4Mv1OrIONbjF/H1U+Kp5Grcj2pm7AYXP2d0Uct2AMQ7zi7OcZCPwxRCudWgmoLswspokkCgYASeZiM5usYWohTep/DrUyive3oG" +
            "0ylQ+OrFhNDgnqYnSzFpTd6IGKgjHr9V56MI0eY/Nzfwm5I45KmcGMYT4HHBHv9Z/t/665pffTHMHUOd3cZCCiSfNpXnnCfOyZgKDiWn0mY24La1nYWl1UVe4" +
            "CDRHnbi0/YeX7vdRexIdeS1Q==";
        /// <summary>
        /// ras解密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string Decrypt(string data,string key)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(RsaPrivateKeyToXml(key));
            var message = rsa.Decrypt(Convert .FromBase64String (data), false );
            return Encoding.UTF8.GetString(message);

        }
        //私钥格式转换
        public static string RsaPrivateKeyToXml(string privateKey)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(privateKey))
                    return "";
                if (privateKey.Contains("<RSAKeyValue>"))
                    return privateKey;
                RsaPrivateCrtKeyParameters privateKeyParam;
                //尝试进行java格式的密钥读取
                try
                {
                    privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
                }
                catch
                {
                    privateKeyParam = null;
                }
                //非java格式密钥进行pem格式的密钥读取
                if (privateKeyParam == null)
                {
                    try
                    {
                        var pemKey = privateKey;
                        if (!pemKey.Contains("BEGIN RSA PRIVATE KEY"))
                        {
                            pemKey = @"-----BEGIN RSA PRIVATE KEY-----
                           " + privateKey + @"
                           -----END RSA PRIVATE KEY-----";
                        }
                        var array = Encoding.ASCII.GetBytes(pemKey);
                        var stream = new MemoryStream(array);
                        var reader = new StreamReader(stream);
                        var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
                        var keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                        privateKeyParam = (RsaPrivateCrtKeyParameters)keyPair.Private;
                    }
                    catch
                    {
                        privateKeyParam = null;
                    }
                }
                //如果都解析失败，则返回原串
                if (privateKeyParam == null)
                    return privateKey;
                //输出XML格式密钥
                return string.Format(
                    "<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                    Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
                    Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
                    Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
                    Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
                    Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
                    Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
                    Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
                    Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())
                );
            }
            catch (Exception)
            {
                return "RSA私钥密钥格式转换失败";
            }
        }

       

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string usercode, string password)
        {
            string pw = "";
            try
            {
                pw = Decrypt(password, privateKey);

            }
            catch (Exception e)
            {
                return Error("错误:" + e.Message);
            }
            Dictionary<string, string> paras = new Dictionary<string, string>();
            string sql = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode and F_PassWord=@F_PassWord";
            paras.Add("@F_UserCode", usercode);
            paras.Add("@F_PassWord", pw);
            var dt = DbHelperSQL.Query(sql, paras).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                var dr = dt.Rows[0];

                if (dr["F_EnableFlag"]?.ToString() == "0")
                {
                    return Error("此账号已经被禁用");
                }
                else if (dr["F_EnableFlag"]?.ToString() == "2")
                {
                    AddLogAsync(dr["F_UserName"].ToString(), dr["F_UserCode"].ToString(), "账号已经被锁定", Common.GetIP(), 1);

                    return Error("此账号已经被锁定,请联系管理员解锁");
                }

                Dictionary<string, string> Dic = new Dictionary<string, string>();
                Dic.Add("F_UserCode", dr["F_UserCode"].ToString());
                Dic.Add("F_RoleId", dr["F_RoleId"].ToString());
                Dic.Add("F_DeptId", dr["F_DeptId"].ToString());

                var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_UserCode"], Dic);
                AddLogAsync(dr["F_UserName"].ToString(), dr["F_UserCode"].ToString(), "登录成功", Common.GetIP(), 1);
                if (dr["F_Locking"] != null && dr["F_Locking"].ToString() != "")
                {
                    if (int.Parse(dr["F_Locking"].ToString()) > 0)
                    {
                        string sql2 = $"update T_Sys_UserAccount set F_Locking=0 where F_UserId='{dr["F_UserId"].ToString()}'" +
                            $" ";
                        var dt2 = DbHelperSQL.ExecuteSql(sql2);
                    }
                }
                return Success("登录成功", token);
            }
            else
            {
                Dictionary<string, string> paras1 = new Dictionary<string, string>();
                string sql1 = " select * from T_Sys_UserAccount where F_UserCode=@F_UserCode ";
                paras1.Add("@F_UserCode", usercode);
                var dt1 = DbHelperSQL.Query(sql1, paras1).Tables[0];



                if (dt1.Rows[0]["F_Locking"] != null && dt1.Rows[0]["F_Locking"].ToString() != "")
                {
                    if (dt1.Rows[0]["F_EnableFlag"]?.ToString() == "2")
                    {
                        AddLogAsync(dt1.Rows[0]["F_UserName"].ToString(), dt1.Rows[0]["F_UserCode"].ToString(), "登录失败，账号已经被锁定", Common.GetIP(), 1);
                        return Error("此账号已经被锁定,请联系管理员解锁");
                    }

                    int intLocking = 9;
                    if (!string.IsNullOrEmpty(Locking))
                        intLocking = int.Parse(Locking)-1;
                    if (int.Parse(dt1.Rows[0]["F_Locking"].ToString()) >= intLocking)
                    {
                        string sql2 = $"update T_Sys_UserAccount set F_Locking=0,F_EnableFlag=2 where F_UserId='{dt1.Rows[0]["F_UserId"].ToString()}'";
                        var dt2 = DbHelperSQL.ExecuteSql(sql2);
                        AddLogAsync(dt1.Rows[0]["F_UserName"].ToString(), dt1.Rows[0]["F_UserCode"].ToString(), "账号已经被锁定", Common.GetIP(), 1);
                        return Error("此账号已经被锁定,请联系管理员解锁");
                    }
                    else
                    {
                        int n = int.Parse(dt1.Rows[0]["F_Locking"].ToString()) + 1;
                        string sql2 = $"update T_Sys_UserAccount set F_Locking={n} where F_UserId='{dt1.Rows[0]["F_UserId"].ToString()}'";
                        
                        var dt2 = DbHelperSQL.ExecuteSql(sql2);
                    }
                }
                else
                {
                    string sql2 = $"update T_Sys_UserAccount set F_Locking=1 where F_UserId='{dt1.Rows[0]["F_UserId"].ToString()}'";
                    var dt2 = DbHelperSQL.ExecuteSql(sql2);
                }
                AddLogAsync(dt1.Rows[0]["F_UserName"].ToString(), dt1.Rows[0]["F_UserCode"].ToString(), "登录失败，账号或密码错误", Common.GetIP(), 1);
                return Error("账号或密码错误");
            }
        }

        /// <summary>
        /// 钉钉获取UserId
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public ActionResult DingTalkGetUserIdByMobile(string mobile)
        {
            return Success(DingTalkHelper.GetUserIdByMobile(mobile));
        }
        /// <summary>
        /// 钉钉
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public ActionResult DingTalkMessagesInfoByMobile(string mobile,string content)
        {
            var userid = DingTalkHelper.GetUserIdByMobile(mobile);
            
            return Success(DingTalkHelper.SendMessageText(userid,"", content));
        }
        /// <summary>
        /// 钉钉发送消息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public ActionResult DingTalkSendMessageText(string userid,string content)
        {
            return Success(DingTalkHelper.SendMessageText(userid, "", content));
        }
        /// <summary>
        /// 钉钉发送消息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public ActionResult DingTalkGetMessage(string task_id)
        {
            return Success("",DingTalkHelper.GetMessage(task_id));
        }
     
        
        private static InternalMessagesController msg = new InternalMessagesController();
        public ActionResult SnedMsg(string tilte,string content,string receiveUserCode,string workorderid)
        {
             bool n = msg.AddInternalMessagesInfo(tilte, content, receiveUserCode, "8000"
                  , (int)EnumSmsType.consulting, 0, workorderid);
            if (n)
            {
                return Success("添加成功");
            }
            else
                return Error("添加失败");
        }

        public ActionResult register(string Username, string Usercode, string Password)
        {


            Model.T_Sys_UserAccount loginUser = new Model.T_Sys_UserAccount();
            if (string.IsNullOrEmpty(Username))
                return Error("请输入姓名!");
            if (string.IsNullOrEmpty(Usercode))
                return Error("请输入账号！");
            if (string.IsNullOrEmpty(Password))
                return Error("请输入密码！");
            Model.T_Sys_UserAccount uModel = new Bll.T_Sys_UserAccount().GetModel(Usercode);
            if (uModel != null)
            {
                return Error("不能重复添加账号");
            }
            var role = new Bll.T_Sys_Role().GetModelList("F_RoleCode='APRY'");

            loginUser.F_UserName = Username;
            loginUser.F_UserCode = Usercode;
            loginUser.F_Password = Password;
            loginUser.F_See = "5";
            if (role!=null && role.Count >0)
            loginUser.F_RoleId = role[0].F_RoleId ;
            var res = new Bll.T_Sys_UserAccount().Add(loginUser);
            if (res > 0)
                return Success("注册成功");
            else
                return Error("注册失败");



        }
        /// <summary>
        /// 钉钉发送模板消息
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="msgjson"></param>
        /// <param name="templateid"></param>
        /// <returns></returns>
        public ActionResult DingTalkSendMessageTemplate(string userid, string msgjson, string templateid)
        {
            return Success(DingTalkHelper.SendMessageByTemplate(userid, "", msgjson, templateid));
        }
        /// <summary>
        /// 存储登录日志
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <param name="log"></param>
        /// <param name="ip"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        private int AddLogAsync(string name, string code, string log, string ip, int channel)
        {
              RMYY_CallCenter_Api.Bll.T_Sys_Login_Logs bll = new RMYY_CallCenter_Api.Bll.T_Sys_Login_Logs();
            var login_log = new T_Sys_Login_Logs()
            {
                T_username = name,
                T_usercode = code,
                T_result = log,
                T_login_ip = ip,
                T_channel = channel,
                T_time = DateTime.Now
            };
            return bll.Add(login_log);
        }
        public ActionResult Logout(string token = "")
        {
            if (string.IsNullOrEmpty(token))
                return Error("身份验证失败");
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
            if (ticket != null && !ticket.Expired && !string.IsNullOrEmpty(ticket.UserData))
            {
                Dictionary<string, string> userData = ticket.UserData.ToObject<Dictionary<string, string>>();
                if (userData != null)
                {
                    var user = new Bll.T_Sys_UserAccount().GetModel(userData["F_UserCode"].ToString());
                    if (user!=null )
                    AddLogAsync(user.F_UserName , user.F_UserCode , "登出成功", Common.GetIP(), 1);
                }
            }
            return Success("退出成功");
        }

        public ActionResult Teljournal(string token = "",int state=0)
        {
            if (string.IsNullOrEmpty(token))
                return Error("身份验证失败");
            if (state<=0)
                return Error("请选择话务状态");
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
            if (ticket != null && !ticket.Expired && !string.IsNullOrEmpty(ticket.UserData))
            {
                Dictionary<string, string> userData = ticket.UserData.ToObject<Dictionary<string, string>>();
                if (userData != null)
                {
                    string message = "";
                    switch (state )
                    {
                        case 1 :
                            message = "签入成功";
                            break;
                        case 2:
                            message = "签出成功";
                            break;
                        case 3:
                            message = "置忙成功";
                            break;
                        case 4:
                            message = "置闲成功";
                            break;
                    }
                    var user = new Bll.T_Sys_UserAccount().GetModel(userData["F_UserCode"].ToString());
                    if (user != null)
                        AddLogAsync(user.F_UserName, user.F_UserCode, message, Common.GetIP(), 1);
                }
            }
            return Success("成功");
        }

        public ActionResult GetLoginLogList(string username,string msg,string ip, string starttime = "", string endtime = "",  int pageindex = 1, int pagesize = 10)
        {
            DataTable datatable= new DataTable();
           
            string sql = "  and 1=1";            
            int recordCount = 0;
            if (!string.IsNullOrEmpty(username))
            {
                sql += " and T_username='" + username + "'";
                 
            }
            if (starttime.Trim() != "" && starttime != "undefined")
                sql += " and datediff(day,T_time,'" + starttime + "')<=0";
            if (endtime.Trim() != "" && endtime != "undefined")
                sql += " and datediff(day,T_time,'" + endtime + "')>=0";
            if (!string.IsNullOrEmpty(msg))
                sql += $"and T_result like '%{msg}%'";
            if (!string.IsNullOrEmpty(ip))
                sql += $"and T_login_ip = '{ip}'";


            //string cols = "(select top 1  LoginTime from  rep_agentState_Duration  where LoginTime>=a.T_time  and LoginTime<=  " +
            //    "[dbo].[GetLoginTime](a.T_id)) as LoginTime, " +
            //    "(select top 1  T_time from  rep_agentState_Duration where LoginTime >= a.T_time  and LoginTime<= " +
            //    " [dbo].[GetLoginTime](a.T_id))as LogoutTime," +
            //    "(select top 1  OccurTime from  rep_agent_state where OccurTime >= a.T_time and State = 2  and OccurTime<= " +
            //    "[dbo].[GetLoginTime](a.T_id))as IdleTime,(select top 1  OccurTime from  rep_agent_state " +
            //    "where OccurTime >= a.T_time and State = 5  and OccurTime<=   [dbo].[GetLoginTime](a.T_id))as BusyTime, *";
            datatable = Bll.PagerBll.GetListPager
                                ("T_Sys_Login_Logs a",
                                  "T_id",
                                  "*",
                                  sql,
                                  "order by T_id desc",
                                  pagesize,
                                  pageindex,
                                  true,
                                  out recordCount

                                );
 
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = datatable,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        public ActionResult DingTalkGetDeUserInfoByUserid(string userid)
        {
            return Content(DingTalkHelper.GetUserInfoByUserId(userid));
        }
        public ActionResult DingTalkGetDeptlist()
        {
            return Content(DingTalkHelper.GetDeptlist());
        }
        private static  string fileurl = ConfigHelper.GetValue("fileurl");
        public  static   string Upload(string pathUrl, string newFileName, string path)
        {

            //文件下载地址
            try
            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileurl+pathUrl);
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream responseStream = response.GetResponseStream();
                string Currentpath = "D:/rmyy" + path;
                // 如果不存在就创建file文件夹
                if (!Directory.Exists(Currentpath))
                {
                    if (Currentpath != null) Directory.CreateDirectory(Currentpath);
                }
                Stream stream = new FileStream(Currentpath + newFileName, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, bArr.Length);
                }
                stream.Close();
                responseStream.Close();

                return "1";
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        public ActionResult DingTalkGetUserIdsByDeptId(double deptid)
        {
            return Content(DingTalkHelper.GetUserIdsByDeptId(deptid));
        }

        public ActionResult taslkfj(int type)
        {
            string str = WorkOrderBase.GetWoTypeName(type);
           return Content(str);
                                  
        }

        /// <summary>
        /// 文本转语音
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public ActionResult TextToFile(string word)
        {
            string str = TtsHelper.GetAudioPath(word) ;
            return Success("成功", str);
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile()
        {
            HttpFileCollectionBase files = Request.Files;
            if (files.Count > 0)
            {
                HttpPostedFileBase file = files[0];
                string path = "/Audio/";
                string name = FileHelper.Upload(file, path);
                return Success("成功", Server.MapPath("..") +path + name);
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }

        /// <summary>
        /// 获取ivr文件文本
        /// </summary>
        /// <returns></returns>
        public ActionResult GetIvrFileText()
        {
            string path = DbHelperSQL.GetSingle(" select top 1 FilePath from conf_ivr_flow")?.ToString() ?? "";

            string result = FileHelper.GetFileText(path);

            return Success("",result);
        }

        /// <summary>
        /// 保存IVR文件
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveIvrFile()
        {
            string text = HttpUtility.UrlDecode(Encoding.GetEncoding(28591).GetString(Convert.FromBase64String(Request.Form["text"])));
            string name = "IVR_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xml";

            string path = DbHelperSQL.GetSingle(" select top 1 FilePath from conf_ivr_flow")?.ToString() ?? "";
            if (!string.IsNullOrEmpty(path))
            {
                string dir = path.Substring(0, path.LastIndexOf("\\"));
                bool bl = FileHelper.CreateTextXMLText(dir, name, text);
                if (bl)
                {
                    DbHelperSQL.ExecuteSql(" update conf_ivr_flow set FilePath='" + dir + "\\" + name + "' limit 1");
                }
                else
                {
                    return Error("保存失败");
                }
            }

            return Success("");
        }

    }
}