using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Input;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.Sms
{
    public class SmsNewController : BaseController
    {
        // GET: SmsNew
        public ActionResult Index()
        {
            return Content("Index");
        }
        private BLL.T_Bus_Operation operBLL = new BLL.T_Bus_Operation();
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string Md5(string txt)
        {
            byte[] sor = Encoding.UTF8.GetBytes(txt);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                //加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
                strbul.Append(result[i].ToString("x2"));
            }
            return strbul.ToString().ToLower(); ;
        }
        /// <summary>
        /// 接收短信
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>

        public ActionResult Receive(string apiKey, List<SmsDetailInput> data)
        {
            LogFactory.GetLogger("SmsNew/Receive").Debug(data.ToJson());
            //存入数据库
            if (data != null && data!=null && data.Count>0)
            {
                foreach (var item in data)
                {
                    //Model.T_SMS_Receive model = new Model.T_SMS_Receive();
                    //model.F_Telephone = item.tel;
                    //model.F_Content = item.content;
                    //DateTime dt = DateTime.ParseExact(item.arriveTime, "yyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
                    //model.F_Time = dt;
                    //model.F_State = 0;
                    //model.F_CreateTime = DateTime.Now;
                    //new BLL.T_SMS_Receive().Add(model);
                    Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                    dModel.CallerNum = item.tel;
                   
                    dModel.Content = item.content;
                    if (item.content.Contains ("#"))
                    {
                        string[] Split = item.content.Split('#');
                        if (Split.Length  >1)
                        {
                           try
                            {
                                string ids = Split[0].Trim();
                                int id = int.Parse(ids.Trim ('+'));
                                var model = new BLL.T_Bus_WorkOrder().GetModel(id);
                                if (model!=null )
                                {
                                    string strStm_Src_Dsc = "";
                                    if (model.F_InfoSource  == 2458)
                                    {
                                        strStm_Src_Dsc = "连线政府";
                                    }
                                    if (model.F_InfoSource == 1)
                                    {
                                        strStm_Src_Dsc = "市长热线";
                                    }
                                    if (model.F_InfoSource == 2)
                                    {
                                        strStm_Src_Dsc = "市长信箱";
                                    }
                                    if (model.F_InfoSource == 4)
                                    {
                                        strStm_Src_Dsc = "人民网";
                                    }
                                    string strWrkOrder_Cst_Ssf_Cd = "";
                                    string content = "";
                                    if (Split.Length > 2)
                                    {
                                        content = Split[2].Trim().Trim('+');
                                    }
                                    if (Split[1].Trim().Trim('+').Contains ("不满意")|| Split[1].Trim().Trim('+').Contains("3"))
                                    {
                                        strWrkOrder_Cst_Ssf_Cd = "不满意";
                                    }
                                    else if (Split[1].Trim().Trim('+').Contains("基本满意") || Split[1].Trim().Trim('+').Contains("2"))
                                    {
                                        strWrkOrder_Cst_Ssf_Cd = "基本满意";
                                        Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                                        keyValuePairs.Add("F_WorkState", 9);
                                        keyValuePairs.Add("F_IsSatisfie", 1);
                                        keyValuePairs.Add("F_IsClosed", 1);
                                        keyValuePairs.Add("F_CloseUser", "");
                                        keyValuePairs.Add("F_CloseTime", DateTime.Now);
                                        keyValuePairs.Add("F_FinalOpinion", content);
                                        keyValuePairs.Add("F_IsStandard", 1);
                                        keyValuePairs.Add("F_StandardIDS", "");
                                        keyValuePairs.Add("F_ToBereply", 0);
                                        new BLL .T_Bus_WorkOrder ().UpdateWorkOrder(model.F_Id, keyValuePairs);
                                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                        oper.F_WorkOrderId = model.F_WorkOrderId;
                                        // oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                        oper.F_State = model.F_WorkState;
                                        oper.F_Message = "市民短信评议基本满意，自动结案";
                                        oper.F_CreateUser = "短信评议";
                                        oper.F_CreateTime = DateTime.Now;
                                        oper.F_IsDelete = 0;
                                        operBLL.Add(oper);
                                       
                                    }
                                    else if (Split[1].Trim().Trim('+').Contains("满意") || Split[1].Trim().Trim('+').Contains("1"))
                                    {
                                        strWrkOrder_Cst_Ssf_Cd = "满意";
                                        Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                                        keyValuePairs.Add("F_WorkState", 9);
                                        keyValuePairs.Add("F_IsSatisfie", 1);
                                        keyValuePairs.Add("F_IsClosed", 1);
                                        keyValuePairs.Add("F_CloseUser", "");
                                        keyValuePairs.Add("F_CloseTime", DateTime.Now);
                                        keyValuePairs.Add("F_FinalOpinion", content);
                                        keyValuePairs.Add("F_IsStandard", 1);
                                        keyValuePairs.Add("F_StandardIDS", "");
                                        keyValuePairs.Add("F_ToBereply", 0);
                                        new BLL.T_Bus_WorkOrder().UpdateWorkOrder(model.F_Id, keyValuePairs);
                                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                        oper.F_WorkOrderId = model.F_WorkOrderId;
                                        // oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                        oper.F_State = model.F_WorkState;
                                        oper.F_Message = "市民短信评议满意，自动结案";
                                        oper.F_CreateUser ="短信评议";
                                        oper.F_CreateTime = DateTime.Now;
                                        oper.F_IsDelete = 0;
                                        operBLL.Add(oper);
                                    }
                                    else
                                    {
                                        continue ;
                                    }
                                   
                                    string strSql = string.Format(@"INSERT INTO PublicComment ( [WorkOrderId], [strStm_Src_Dsc], [strWrkOrder_Cst_Ssf_Cd], [strUdt_Psn_ID], [strSsf_Cst_Ass_CntDsc], [strRltv_InsID], [strInpt_Inst_Nm], [strHpCnt], [CreateTime],[str_type]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}') ;select @@IDENTITY ", model.F_WorkOrderId , strStm_Src_Dsc, strWrkOrder_Cst_Ssf_Cd, "", content, "", "", "", DateTime.Now, 1);
                                    object objres = DbHelperSQL.GetSingle(strSql);
                                    dModel.F_CustomerID = 1;
                                }
                                
                            }
                            catch
                            {

                            }
                        }
                    }
                    else if (item.content.Contains("＃"))
                    {
                        string[] Split = item.content.Split('＃');
                        if (Split.Length > 1)
                        {
                            try
                            {
                                string ids = Split[0].Trim();
                                int id = int.Parse(ids.Trim('+'));
                                var model = new BLL.T_Bus_WorkOrder().GetModel(id);
                                if (model != null)
                                {
                                    string strStm_Src_Dsc = "";
                                    var DictionaryValue = new BLL.T_Sys_DictionaryValue().GetModel((int )model.F_InfoSource);
                                    if (DictionaryValue!=null )
                                    {
                                        strStm_Src_Dsc = DictionaryValue.F_Value;
                                    }
                                    string strWrkOrder_Cst_Ssf_Cd = "";

                                    if (Split[1].Trim().Trim('+').Contains("不满意") || Split[1].Trim().Trim('+').Contains("3"))
                                    {
                                        strWrkOrder_Cst_Ssf_Cd = "不满意";
                                    }
                                    else if (Split[1].Trim().Trim('+').Contains("基本满意") || Split[1].Trim().Trim('+').Contains("2"))
                                    {
                                        strWrkOrder_Cst_Ssf_Cd = "基本满意";
                                    }
                                    else if (Split[1].Trim().Trim('+').Contains("满意") || Split[1].Trim().Trim('+').Contains("1"))
                                    {
                                        strWrkOrder_Cst_Ssf_Cd = "满意";
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                    string content = "";
                                    if (Split.Length > 2)
                                    {
                                        content = Split[2].Trim().Trim('+');
                                    }
                                    string strSql = string.Format(@"INSERT INTO PublicComment ( [WorkOrderId], [strStm_Src_Dsc], [strWrkOrder_Cst_Ssf_Cd], [strUdt_Psn_ID], [strSsf_Cst_Ass_CntDsc], [strRltv_InsID], [strInpt_Inst_Nm], [strHpCnt], [CreateTime],[str_type]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}') ;select @@IDENTITY ", model.F_WorkOrderId, strStm_Src_Dsc, strWrkOrder_Cst_Ssf_Cd, "", content, "", "", "", DateTime.Now, 1);
                                    object objres = DbHelperSQL.GetSingle(strSql);
                                    dModel.F_CustomerID = 1;
                                }


                            }
                            catch
                            {

                            }
                        }
                    }
                    // dModel.RecvModemIMEI = addSerial;
                    // dModel.F_Name = workorderid;
                    dModel.State = 1;
                    // dModel.F_UserID = userId;
                    try
                    {
                        dModel.RecvTime = DateTime.ParseExact(item.arriveTime, "yyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
                    }
                    catch
                    {
                        dModel.RecvTime = DateTime.Now;
                    }
                    int b = new BLL.T_SMS_RecvSMS().Add(dModel);
                }
            }
            return Content("");
        }

        /// <summary>
        /// 获取接收短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetReceiveList(string tel, string content, string starttime,string endtime, int page =1,int pagesize=10)
        {
            string sql = "";
            DataTable dt = new DataTable();


            if (tel!=null&& tel.Trim() != "" && tel != "undefined")
            {
                sql += " and F_Telephone= '" + tel.Trim() + "' ";
            }
            if (content != null && content.Trim() != "" && content != "undefined")
            {
                sql += " and F_Content like '%" + content.Trim() + "%' ";
            }
            if (starttime != null && starttime.Trim() != "" && starttime != "undefined")
            {
                sql += " and F_CreateTime >= '" + Convert.ToDateTime(starttime.Trim()) + "' ";
            }
            if (endtime != null && endtime.Trim() != "" && endtime != "undefined")
            {
                sql += " and F_CreateTime <= '" + Convert.ToDateTime(endtime.Trim()) + "' ";
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_SMS_Receive",
                "F_Id",
                "*",
                sql,
                "ORDER BY F_Id desc",
                pagesize,
                page,
                true,
                out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 发送评价短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="WorkOrderId"></param>
        /// <returns></returns>
        public ActionResult SendVisit(string phone, string WorkOrderId)
        {
            if (!string.IsNullOrEmpty(phone))
            {
                if (phone.Trim().Length > 11)
                    phone = phone.Substring(1, 11);
            }
            else
            {
                return Error("请输入号码");
            }
          //  var model = new BLL.T_Bus_WorkOrder().GetModel(WorkOrderId);
          //  if (model != null)
           // {
             //   Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
              //  keyValuePairs.Add("F_IsSms", "1");
                // model.F_IsSms = 1;
                //new BLL.T_Bus_WorkOrder().UpdateWorkOrder(model.F_Id, keyValuePairs);

                //string count = "您反映的诉求已有回复，请前往安阳政务服务官网（https://zwfw.anyang.gov.cn）登录后查看办结结果并对办理情况进行评价，或者拨打12345市长热线来电咨询，谢谢！";
                string content = "您提交的施划停车位事项的办理结果为：" + "文峰区政府于时间（2021年12月07日 15时45分38秒）回复：施划停车位应达到路面的宽度要求，此处无法施划，南关街道已对辖区内的停车位应划尽划，。 经副科级干部靳少杰同意上报，电话：2228192" + "请于15天内回复：“$" + "4308916" + "#”+1、满意，2、基本满意，3、不满意+#评议内容，进行评价。（不超过60字）";
                string mag = "[\"" + "施划停车位" + "\",\"" + "文峰区政府于时间（2021年12月07日 15时45分38秒）回复：施划停车位应达到路面的宽度要求，此处无法施划，南关街道已对辖区内的停车位应划尽划，。 经副科级干部靳少杰同意上报，电话：2228192" + "\",\"" + "4308916" + "\"]";
                string n = AddSmS(0, content, phone, "660571546305982464", mag, WorkOrderId);
                if (n == "")
            { //{
                //    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                //    oper.F_WorkOrderId = model.F_WorkOrderId;
                //    oper.F_State = model.F_WorkState;
                //    oper.F_CallRecordId = model.F_CallRecordId;
                //    oper.F_File = model.F_File;
                //    string userinfo = User.depname + "(" + User.F_UserCode + ")";
                //    oper.F_Message = userinfo + "发送了市民评价短信";

                //    oper.F_CreateUser = User.F_UserCode;
                //    oper.F_CreateTime = DateTime.Now;
                //    oper.F_IsDelete = 0;
                //    operBLL.Add(oper);
                //    return Success("发送成功");
                }
               
                   return Error(n);
          }
           
        public static string apiKey = "b1672487a0d46d3b3376c55897b8c705";
        public static string accessKey = "31492894daed7e09001a95c6e0df7db57bbbf6e6d378b2a9d043b2cc96a9a380";
        public static string authHost = "https://opassapi.ums86.com/message/send";
      

        public static string  AddSmS(int userId, string Content, string mobiles, string templateCode
         , string templateParam = "", string workorderid = "")
        {
            int t = 0;
            try
            {
                return "";
                var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var currentTime = Convert.ToInt64(ts.TotalMilliseconds).ToString();
                HttpClient client = new HttpClient();

                var requestHeaders = new Dictionary<string, string>();
                //签名算法。支持HmacSHA256、HmacMD5、HmacSHA224、HmacSHA384、HmacSHA512
                requestHeaders.Add("x-sign-method", "HmacSHA256");
                requestHeaders.Add("x-api-key", $"{apiKey}");
                //随机数。每次请求随机数建议不相同
                requestHeaders.Add("x-nonce", $"{GetRandom()}");
                //时间戳
                requestHeaders.Add("x-timestamp", $"{currentTime}");


                // client.DefaultRequestHeaders.Host = "recognition.image.myqcloud.com";
                //设置headers请求参数 
                foreach (var item in requestHeaders)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }

                //短信接口请求参数。参见接口规范
                var jsArr = new Dictionary<string, string>();
                jsArr.Add("phones", mobiles);
              
                jsArr.Add("templateCode", templateCode);
              
                //"[\"变量值1\",\"变量值2\"]"
                if (!string .IsNullOrEmpty (templateParam))
                jsArr.Add("templateParam", templateParam);
              
                //将headers参与与接口报文参数合并、排序，并生成本次请求的签名信息
               var signDic = jsArr.Union(requestHeaders).ToDictionary(k => k.Key, v => v.Value);
               
           //     var signDic = requestHeaders.ToDictionary(k => k.Key, v => v.Value);
                var dicStr = GetSignContent(signDic);
                var sign = Hmacsha256Encrypt(dicStr, accessKey);
                //在header中设置本次请求签名信息
                client.DefaultRequestHeaders.Add("x-sign", sign);
                HttpContent str = new StringContent(JsonConvert.SerializeObject(jsArr));
                str.Headers.Remove("Content-Type");
                str.Headers.Add("Content-Type", "application/json");
               
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                HttpResponseMessage response = client.PostAsync(authHost, str).Result;
               
               

                string result = response.Content.ReadAsStringAsync().Result;
              
                JObject jo = (JObject)JsonConvert.DeserializeObject(result);
               
                string code = jo["code"].ToString();
               

                if (code == "200")
                {
                    Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                    dModel.CallerNum = mobiles.Trim();
                    dModel.Content = Content.Trim();
                    dModel.RecvModemIMEI = "";
                    dModel.F_Name = workorderid;
                    dModel.State = 0;
                    dModel.F_UserID = userId;
                    dModel.RecvTime = DateTime.Now;
                    int b = new BLL.T_SMS_RecvSMS().Add(dModel);
                    if (b > 0)
                    {
                        return "";
                    }
                    else
                    {
                        return "发送失败";
                    }
                }
                else
                {
                    string desc = jo["message"].ToString();
                    return code+"("+ desc+")";
                    
                }
                
            }
            catch (Exception e)
            {
                return e.ToString ();
            }


        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        /// <summary>
        /// Get Sign Content
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private static string GetSignContent(IDictionary<string, string> parameters)
            {
                // 第一步：把字典按Key的字母顺序排序
                IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
                IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

                // 第二步：把所有参数名和参数值串在一起
                StringBuilder query = new StringBuilder("");
                while (dem.MoveNext())
                {
                    string key = dem.Current.Key;
                    string value = dem.Current.Value;
                    if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                    {
                        query.Append(key).Append("=").Append(value).Append("&");
                    }
                }
                string content = query.ToString().Substring(0, query.Length - 1);

                return content;
            }

            /// <summary>
            /// HMACSHA1算法加密
            /// </summary>
            private static string Hmacsha256Encrypt(string encryptText, string encryptKey)
            {
                var encoding = new System.Text.UTF8Encoding();
                StringBuilder builder = new StringBuilder();

                using (var hmacsha256 = new HMACSHA256(encoding.GetBytes(encryptKey)))
                {
                    byte[] hashmessage = hmacsha256.ComputeHash(encoding.GetBytes(encryptText));
                    for (int i = 0; i < hashmessage.Length; i++)
                    {
                        builder.Append(hashmessage[i].ToString("x2"));
                    }
                }
                return builder.ToString();
            }
            /// <summary>
            /// 获取随机数
            /// </summary>
            private static int GetRandom()
            {
                var random = new Random();
                var rand = random.Next(10000, 999999999);
                return rand;
            }
        
    
}
}