using Kingdee.BOS.Log;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.WebApi.Client;
using LQKJ.WebApi.Stub;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Caching;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace LQKJ.K3.PeiXunSystem.WebApi
{/// <summary>
 /// 操作类
 /// </summary>
    class WebApiEditService : CustomWebApiService
    {
        private readonly CustomWebApiService obj;
        static object lockObject = new object();
        public WebApiEditService(KDServiceContext context) : base(context)
        {
            obj = new CustomWebApiService(context);
        }
        /// <summary>
        /// 课程报名
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="parmeters"></param>
        /// <returns></returns>
        public SQLResult SignUp(string classId, string parmeters)//string classId, string Id)
        {
            lock (lockObject)//加锁
            {
                SQLResult sqlResult = new SQLResult();
                try
                {
                    K3CloudApiClient Client = apiClient();//返回接口对象
                    var msg = JObject.Parse(parmeters);
                    var FNUMBER = msg["Model"]["FClass"]["FNUMBER"].ToString();
                    string sqlSelect = $"exec SingUp @ClassId ={ classId} --判断计划人数是否等于确认参加人数";
                    DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                    if (dataTable.Rows[0]["state"].ToString() == "0")//判断计划人数是否等于实际人数,0就是还没满
                    {
                        sqlSelect = $"/*dialect*/ select FID from T_PX_ADDRESSBOOK where FCLASS={classId}";
                        if (obj.ExecuteDataTable(sqlSelect).Rows.Count != 0)//如果有该班级
                        {
                            msg["Model"]["FID"] = obj.ExecuteDataTable(sqlSelect).Rows[0][0].ToString();
                            (msg["Model"] as JObject).Remove("FTrainingProgram");//删除属性
                            (msg["Model"] as JObject).Remove("FClass");//删除属性
                        }
                        var result = JObject.Parse(Client.Save("LQKJ_ClassDetails", msg.ToString()));
                        var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                        if ((bool)Sueccess)
                        {
                            sqlResult.msg = "添加成功";
                            sqlResult.code = "200";
                            //增加实际参加人数
                            //string Update = $"update T_PX_CLASS set FCONFIRMQTY=FCONFIRMQTY+1 where FNUMBER = '{FNUMBER}'";
                            //if (obj.Execute(Update) != 1)
                            //{
                            //    sqlResult.msg = "人数更新失败";
                            //    sqlResult.code = "500";
                            //}
                        }
                        else
                        {
                            if (((string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"]).Contains("“学员”是必填项"))
                            {
                                sqlResult.msg = "请联系管理员审核账号";
                            }
                            else
                            {

                                sqlResult.msg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                            }
                            sqlResult.code = "500";
                        }
                    }
                    else
                    {
                        sqlResult.code = "500";
                        sqlResult.msg = "该班级人数已满!";
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("ActionName:SignUp", ex.Message, ex);
                }
                return sqlResult;
            }
        }
        /// <summary>
        /// 退出报名
        /// </summary>
        /// <param name="parmeters"></param>
        /// <returns></returns>
        public SQLResult Quit(string parmeters)
        {
            SQLResult result = new SQLResult();
            try
            {
                var msg = JObject.Parse(parmeters);
                string delSelect = $@"delete from T_PX_ADDRESSBOOKENTRY
                                    where FEntryID = (select T2.FEntryID from T_PX_ADDRESSBOOK T1 left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID = T2.FID
                                    where FCLASS = {msg["classId"]} and FPHONENUMBER = '{msg["Phone"]}')";
                int editRlt = obj.Execute(delSelect);
                if (editRlt == 1)
                {
                    string Update = $"update T_PX_CLASS set FCONFIRMQTY = FCONFIRMQTY - 1 where FCLASSID = '{msg["classId"]}'";
                    int UpdRlt = obj.Execute(Update);
                    if (UpdRlt == 1)
                    {
                        result.code = "200";
                        result.msg = "退出成功";
                    }
                    else
                    {
                        result.code = "500";
                        result.msg = "人数更新失败";
                    }

                }
                else
                {
                    result.code = "500";
                    result.msg = "退出失败";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:Quit", ex.Message, ex);
                result.code = "500";
                result.msg = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 签到打卡
        /// </summary>
        /// <param name="parmeters">课程Id</param>
        /// <returns></returns>
        public SQLResult ClockId(string parmeters)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                var msg = JObject.Parse(parmeters);
                K3CloudApiClient Client = apiClient();

                var result = JObject.Parse(Client.Save("LQKJ_AttendanceRecord", msg.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)
                {
                    sqlResult.msg = "打卡成功";
                    sqlResult.code = "200";
                    var Id = result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"].ToString();
                    Client.Submit("LQKJ_AttendanceRecord", "{\"Ids\":" + Id + "}");
                    Client.Audit("LQKJ_AttendanceRecord", "{\"Ids\":" + Id + "}");
                }
                else
                {
                    sqlResult.msg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                    sqlResult.code = "500";
                }
            }
            catch (Exception ex)
            {

                Logger.Error("ActionName:SignUp", ex.Message, ex);
            }
            return sqlResult;
        }
        /// <summary>
        /// 评价功能
        /// </summary>
        /// <param name="parmeters"></param>
        /// <returns></returns>
        public SQLResult RemarkOn(string parmeters)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                K3CloudApiClient Client = apiClient();
                var msg = JObject.Parse(parmeters);
                var result = JObject.Parse(Client.Save("LQKJ_Evaluates", msg.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)
                {
                    sqlResult.code = "200";
                    var Id = result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"].ToString();
                    sqlResult.msg = "评论成功";
                    Client.Submit("LQKJ_Evaluates", "{\"Ids\":" + Id + "}");
                    Client.Audit("LQKJ_Evaluates", "{\"Ids\":" + Id + "}");
                }
                else
                {
                    sqlResult.msg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                    sqlResult.code = "500";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:RemarkOn", ex.Message, ex);
            }
            return sqlResult;
        }
        private K3CloudApiClient apiClient()
        {
            K3CloudApiClient Client = new K3CloudApiClient(base.url);
            var loginResult = Client.ValidateLogin(base.dbid, base.username, base.password, 2052);
            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
            if (resultType == 1)
            {
                return Client;
            }
            throw new Exception("登陆失败");
        }
        /// <summary>
        /// 设置打卡地点
        /// </summary>
        /// <param name="parmeters"></param>
        /// <returns></returns>
        public SQLResult Sett(string parmeters)
        {
            SQLResult sqlResule = new SQLResult();
            try
            {
                var msg = JObject.Parse(parmeters);
                var val = msg["F_LQKJ_LONGITUDE"].ToString();
                var val2 = msg["F_LQKJ_SCOPE"].ToString();
                var val3 = msg["FCOURSEID"];
                var val5 = msg["F_LQKJ_HITAREA"].ToString();
                var classId = msg["classId"].ToString();
                var type = msg["type"].ToString();
                string UpdSel = "";
                if (type == "0")
                {
                    UpdSel = $@"update T_PX_COURSE set F_LQKJ_LONGITUDE='{val}',F_LQKJ_SCOPE='{val2}',F_LQKJ_HitArea='{val5}',F_LQKJ_TYPE2='0' where FCOURSEID={val3}
                              
                            ";
                }
                else
                {
                    UpdSel = $@"update T_PX_COURSE set F_LQKJ_LONGITUDE='{val}',F_LQKJ_SCOPE='{val2}',F_LQKJ_HitArea='{val5}',F_LQKJ_TYPE2='1' where 
																FCOURSEID in (select T2.FCOURSEID from T_PX_CLASS T1 left join T_PX_CLASSENTRY T2 on T1.FCLASSID=T2.FCLASSID
																 where T1.FCLASSID='{classId}')
                                 ";
                }
                int result = obj.Execute(UpdSel);
                if (result > 0)
                {
                    sqlResule.code = "200";
                    sqlResule.msg = "设置成功";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:Sett", ex.Message, ex);
                sqlResule.code = "500";
                sqlResule.msg = "错误" + ex.Message;
            }
            return sqlResule;
        }
        /// <summary>
        /// 将图片上传到服务器上
        /// </summary>
        /// <returns></returns>
        public List<JObject> Image(HttpRequest request)
        {
            List<string> listPath = new List<string>();

            for (int i = 0; i < request.Files.Count; i++)
            {
                HttpPostedFile HttpFile = request.Files[i];
                Stream stream = HttpFile.InputStream;
                byte[] fileByte = new byte[stream.Length];
                stream.Read(fileByte, 0, fileByte.Length);
                stream.Close();
                string Base64string = Convert.ToBase64String(fileByte);
                listPath.Add(Base64string);
            }
            return obj.ImagePath(listPath);
        }
        /// <summary>
        /// 更新班级二维码
        /// </summary>
        /// <returns></returns>
        public SQLResult ClassImage()
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                List<string> listPath = new List<string>();
                HttpRequest request = System.Web.HttpContext.Current.Request;
                HttpPostedFile HttpFile = request.Files["image"];
                var classId = request.Form["classId"].ToString();
                Stream stream = HttpFile.InputStream;
                byte[] fileByte = new byte[stream.Length];
                stream.Read(fileByte, 0, fileByte.Length);
                stream.Close();
                string Base64string = Convert.ToBase64String(fileByte);
                listPath.Add(Base64string);
                var JOb = obj.ImagePath(listPath)[0];
                string UpSelect = $"update T_PX_CLASS set FQRCODE='{JOb["FileId"]}' where FCLASSID='{classId}'";
                if (obj.Execute(UpSelect) > 0)
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "更新成功";
                    sqlResult.data = JOb;
                }
                else
                {
                    sqlResult.code = "500";
                    sqlResult.msg = "更新失败";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:ClassImage", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "更新失败:" + ex.Message;
            }

            return sqlResult;
        }

        /// <summary>
        /// 微信公众号openid自动登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public SQLResult User(string OpenID,int Type)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                if (string.IsNullOrWhiteSpace(OpenID))
                {
                    sqlResult.code = "500";
                    sqlResult.msg = "微信授权登录失败，请重试，或使用验证码，密码登录！！";
                    return sqlResult;
                }
                var sqlSelect = "";
                if (Type == 0)
                {
                    sqlSelect = $"select FUSERACCOUNT,FNAME,FPHONE,FHeadShot,FHEADIMG,FOPENID  from T_SEC_user where FOPENID='{OpenID}' and FFORBIDSTATUS='A'";
                    DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                    if (dataTable.Rows.Count == 0)
                    {
                        sqlResult.code = "500";
                        sqlResult.msg = "微信授权登录失败，未绑定任何账号";
                        return sqlResult;
                    }
                    //登录成功
                    sqlResult.code = "200";
                    sqlResult.msg = "登录成功";
                    sqlResult.data = dataTable.AsEnumerable().Select(e => new
                    {
                        Name = e.Field<string>("FNAME"),
                        //TeachId = e.Field<int>("FPHONE"),
                        img = e.Field<Byte[]>("FHEADIMG"),
                        Image = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FHeadShot"), obj.UserToken())
                    });
                }
                else
                {
                    sqlSelect = $"select FWORKUNIT1,FIMAGEFILESERVER,T1.FSTUDENTID,FDUTIES,FSEX,FNUMBER,FNAME,FMOBILE from T_PX_StudentsInfo T1 left join T_PX_StudentsInfo_L T2 on T1.FSTUDENTID = T2.FSTUDENTID where FOPENID = '{OpenID}'";
                    DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                    if (dataTable.Rows.Count == 0)
                    {
                        sqlResult.code = "501";
                        sqlResult.msg = "请先注册";
                        return sqlResult;
                    }
                    var DataList = dataTable.AsEnumerable().Select(e => new
                    {
                        FNAME = e.Field<string>("FNAME"),
                        FSTUDENTID = e.Field<int>("FSTUDENTID"),
                        FDUTIES = e.Field<string>("FDUTIES"),
                        FSEX = e.Field<string>("FSEX"),
                        FMOBILE = e.Field<string>("FMOBILE"),
                        FNUMBER = e.Field<string>("FNUMBER"),
                        FWORKUNIT1 = e.Field<string>("FWORKUNIT1"),
                        FIMAGEFILESERVER = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FIMAGEFILESERVER"), obj.UserToken())
                    }).ToList();
                    sqlResult.code = "200";
                    sqlResult.msg = "登录成功";
                    sqlResult.data = DataList;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:User", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "请求无效，请使用验证码,密码登录";
            }
            return sqlResult;
        }
        /* public SQLResult User(string code, int type)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                var appid = "wx459ae5e7c5918bf3";
                var grant_type = "authorization_code";
                var secret = "9d79c35d28d432951d72972bf9566071";
                var baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?";
                string result = "";
                string url = $"{baseUrl}appid={appid}&secret={secret}&code={code}&grant_type={grant_type}";
                HttpClient httpClient = new HttpClient();
                // 设置等待时间为10秒
                httpClient.Timeout = TimeSpan.FromSeconds(10);

                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)//获取成功
                {
                    result = response.Content.ReadAsStringAsync().Result;
                    JObject Json = JObject.Parse(result);
                    //拉取用户信息，获取openid
                    var openId = Json["openid"]?.ToString();
                    if (openId == null)
                    {
                        sqlResult.code = "501";
                        sqlResult.msg = "微信登陆失败，无法获取openid";
                        sqlResult.data = "openId:" + openId;
                        return sqlResult;
                    }
                    var sqlSelect = "";
                    if (type == 0)
                    {

                    }
                    else
                    {
                        sqlSelect = $"select FWORKUNIT1,FIMAGEFILESERVER,T1.FSTUDENTID,FDUTIES,FSEX,FNUMBER,FNAME,FMOBILE from T_PX_StudentsInfo T1 left join T_PX_StudentsInfo_L T2 on T1.FSTUDENTID = T2.FSTUDENTID where FOPENID = '{openId}'";
                    }
                    DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                    if (dataTable.Rows.Count == 0)
                    {
                        sqlResult.code = "501";
                        sqlResult.msg = "请先注册";
                        sqlResult.data = "openId:" + openId;
                        return sqlResult;
                    }
                    var DataList = dataTable.AsEnumerable().Select(e => new
                    {
                        FNAME = e.Field<string>("FNAME"),
                        FSTUDENTID = e.Field<int>("FSTUDENTID"),
                        FDUTIES = e.Field<string>("FDUTIES"),
                        FSEX = e.Field<string>("FSEX"),
                        FMOBILE = e.Field<string>("FMOBILE"),
                        FNUMBER = e.Field<string>("FNUMBER"),
                        FWORKUNIT1 = e.Field<string>("FWORKUNIT1"),
                        FIMAGEFILESERVER = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FIMAGEFILESERVER"), obj.UserToken())
                    }).ToList();
                    sqlResult.data = DataList;
                    sqlResult.code = "200";
                    sqlResult.msg = "openId:" + openId;
                }
                else
                {
                    sqlResult.code = "500";
                    sqlResult.msg = "code无效";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:User", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "请求无效，请使用验证码登录";
            }
            return sqlResult;
        }*/
        public SQLResult GetOpenID(string code)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string appid = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["appid"].Value;
                string secret = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["secret"].Value;
                //var appid = "wx459ae5e7c5918bf3";
                var grant_type = "authorization_code";
                //var secret = "9d79c35d28d432951d72972bf9566071";
                var baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?";
                string result = "";
                string url = $"{baseUrl}appid={appid}&secret={secret}&code={code}&grant_type={grant_type}";
                HttpClient httpClient = new HttpClient();
                // 设置等待时间为10秒
                httpClient.Timeout = TimeSpan.FromSeconds(10);

                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)//获取成功
                {
                    result = response.Content.ReadAsStringAsync().Result;
                    JObject Json = JObject.Parse(result);
                    //拉取用户信息，获取openid
                    var openId = Json["openid"]?.ToString();
                    if (openId == null)
                    {
                        sqlResult.code = "500";
                        sqlResult.msg = "微信授权失败，请使用验证码或密码登陆！！";
                        sqlResult.data = null;
                        return sqlResult;
                    }
                    sqlResult.data = new { OpenID = openId };
                    sqlResult.code = "200";
                    sqlResult.msg = "获取成功";
                }
                else
                {
                    sqlResult.code = "500";
                    sqlResult.msg = "微信授权失败，请使用验证码或密码登陆！！code无效";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:User", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "微信授权失败，请使用验证码或密码登陆！！";
            }
            return sqlResult;
        }
        /// <summary>
        /// 注册//修改个人信息
        /// </summary>
        /// <param name="parmeters"></param>
        /// <returns></returns>
        public SQLResult Login(string parmeters, int type)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                K3CloudApiClient Client = apiClient();
                var msg = JObject.Parse(parmeters);
                string Phone = msg["Model"]["FMobile"].ToString();
                string sqlSelect = "";
                #region 注册
                if (type == 1)
                {
                    sqlSelect = $"select FWORKUNIT1,FIMAGEFILESERVER,T1.FSTUDENTID,FDUTIES,FSEX,FNUMBER,FNAME,FMOBILE from T_PX_StudentsInfo T1 left join T_PX_StudentsInfo_L T2 on T1.FSTUDENTID = T2.FSTUDENTID where FMobile = '{Phone}'";
                    DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                    if (dataTable.Rows.Count == 0)//该手机号没有被注册
                    {
                        string openid = msg["Model"]["FOPENID"]?.ToString();
                        if (string.IsNullOrWhiteSpace(openid))
                        {
                            string sqlSelect1 = $"select FWORKUNIT1,FIMAGEFILESERVER,T1.FSTUDENTID,FDUTIES,FSEX,FNUMBER,FNAME,FMOBILE from T_PX_StudentsInfo T1 left join T_PX_StudentsInfo_L T2 on T1.FSTUDENTID = T2.FSTUDENTID where FOPENID = '{openid}'";
                            DataTable dataTable1 = obj.ExecuteDataTable(sqlSelect1);
                            if (dataTable1.Rows.Count == 0)
                            {
                                sqlResult.code = "500";
                                sqlResult.msg = "该微信号已绑定其他微信，无法注册！！";
                                return sqlResult;
                            }
                        }
                        msg.Remove("NeedUpDateFields");
                        var result = JObject.Parse(Client.Save("LQKJ_StudentsInfo", msg.ToString()));
                        var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                        if ((bool)Sueccess)//新增成功,接下来就要新增图片
                        {
                            dataTable = obj.ExecuteDataTable(sqlSelect);
                            var DataList = dataTable.AsEnumerable().Select(e => new
                            {
                                FNAME = e.Field<string>("FNAME"),
                                FSTUDENTID = e.Field<int>("FSTUDENTID"),
                                FDUTIES = e.Field<string>("FDUTIES"),
                                FSEX = e.Field<string>("FSEX"),
                                FMOBILE = e.Field<string>("FMOBILE"),
                                FNUMBER = e.Field<string>("FNUMBER"),
                                FWORKUNIT1 = e.Field<string>("FWORKUNIT1"),
                                FIMAGEFILESERVER = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FIMAGEFILESERVER"), obj.UserToken())
                            });
                            sqlResult.data = DataList;
                            sqlResult.msg = "添加成功";
                            sqlResult.code = "200";
                        }
                        else
                        {
                            sqlResult.msg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                            sqlResult.code = "500";
                        }
                    }
                    else
                    {
                        sqlResult.code = "500";
                        sqlResult.msg = "该账号已被注册";
                    }

                }
                #endregion
                #region 修改
                else
                {
                    var studentId = msg["Model"]["FSTUDENTID"].ToString();
                    sqlSelect = $"select FWORKUNIT1,FIMAGEFILESERVER,T1.FSTUDENTID,FDUTIES,FSEX,FNUMBER,FNAME,FMOBILE from T_PX_StudentsInfo T1 left join T_PX_StudentsInfo_L T2 on T1.FSTUDENTID = T2.FSTUDENTID where T1.FSTUDENTID = '{studentId}'";
                    var result = JObject.Parse(Client.Save("LQKJ_StudentsInfo", msg.ToString()));
                    var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                    if ((bool)Sueccess)
                    {
                        DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                        dataTable = obj.ExecuteDataTable(sqlSelect);
                        var DataList = dataTable.AsEnumerable().Select(e => new
                        {
                            FNAME = e.Field<string>("FNAME"),
                            FSTUDENTID = e.Field<int>("FSTUDENTID"),
                            FDUTIES = e.Field<string>("FDUTIES"),
                            FSEX = e.Field<string>("FSEX"),
                            FMOBILE = e.Field<string>("FMOBILE"),
                            FNUMBER = e.Field<string>("FNUMBER"),
                            FWORKUNIT1 = e.Field<string>("FWORKUNIT1"),
                            FIMAGEFILESERVER = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FIMAGEFILESERVER"), obj.UserToken())
                        });
                        sqlResult.data = DataList;
                        sqlResult.code = "200";
                        sqlResult.msg = "修改成功";
                    }
                    else
                    {
                        sqlResult.msg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                        sqlResult.code = "500";
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:Login", ex.Message, ex);
            }
            return sqlResult;
        }
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="Phone"></param>
        /// <returns></returns>
        public SQLResult Verification(string Phone)
        {
            SQLResult sqlResult = new SQLResult();
            sqlResult.code = "500";
            try
            {
                string u = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["u"].Value;
                string ApiKey = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["ApiKey"].Value;
                //string u = "18926482017";
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] fromData = Encoding.UTF8.GetBytes(u);
                byte[] targetData = md5.ComputeHash(fromData);
                //string ApiKey = "7fda47dc16a84e8e8592fbc4b126d255";
                WebClient Client = new WebClient();
                Client.Credentials = CredentialCache.DefaultCredentials;
                string code = new Random().Next(1111, 9999).ToString();
                string content = HttpUtility.UrlEncode($"【西部人力】您的验证码是{code},验证码5分钟内有效.若非本人操作请忽略此消息:", Encoding.UTF8);//短信发送内容并进行 urlencode编码
                string Url = $"http://api.smsbao.com/sms?u={u}&p={ApiKey}&m={Phone}&c={content}";
                byte[] result = Client.DownloadData(Url);// 向远程网址发送请求并获取返回值保存至字节数组
                string sres = Encoding.UTF8.GetString(result); /*将返回结果转换成字符串*/
                switch (sres)
                {
                    case "0":
                        {
                            sqlResult.data = Convert.ToBase64String(EncryptAES(code, "lqkj456789A10086", "lqkj456789A10086"));
                            sqlResult.msg = "发送成功！";
                            sqlResult.code = "200";
                            break;
                        }
                    case "30":
                        {
                            sqlResult.msg = "密码错误！";
                            break;
                        }
                    case "40":
                        {
                            sqlResult.msg = "账号不存在！";
                            break;
                        }
                    case "41":
                        {
                            sqlResult.msg = "余额不足！";
                            break;
                        }
                    case "42":
                        {
                            sqlResult.msg = "帐号过期！";
                            break;
                        }
                    case "43":
                        {
                            sqlResult.msg = "IP地址限制！";
                            break;
                        }
                    case "50":
                        {
                            sqlResult.msg = "内容含有敏感词！";
                            break;
                        }
                    case "51":
                        {
                            sqlResult.msg = "手机号码不正确！";
                            break;
                        }
                    case "-1":
                        {
                            sqlResult.msg = "手机号码不正确或缺少参数！";
                            break;
                        }
                    default:
                        {
                            sqlResult.msg = sres;
                            break;
                        }
                }

            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:Verification", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "验证错误" + ex.Message;
            }
            return sqlResult;
        }
        private byte[] EncryptAES(string text, string key, string iv)
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = Encoding.UTF8.GetBytes(iv);

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                byte[] inputBytes = Encoding.UTF8.GetBytes(text);
                byte[] encryptedBytes = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);

                return encryptedBytes;
            }
        }
        /// <summary>
        /// 手机验证码登录
        /// </summary>
        /// <param name="Phone"></param>
        /// <returns></returns>
        public SQLResult LoginCode(string Phone,string OpenId)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $"select FIMAGEFILESERVER,T1.FSTUDENTID,FDUTIES,FSEX,FNUMBER,FNAME,FMOBILE,FWORKUNIT1,FOPENID from T_PX_StudentsInfo T1 left join T_PX_StudentsInfo_L T2 on T1.FSTUDENTID = T2.FSTUDENTID where FMobile = '{Phone}'";
                var dataTable = obj.ExecuteDataTable(sqlSelect);
                if (dataTable.Rows.Count > 0)
                {
                    /*if (!string.IsNullOrWhiteSpace(dataTable.Rows[0]["FOPENID"].ToString()))
                    {
                        if(dataTable.Rows[0]["FOPENID"].ToString()!= OpenId)
                        {
                            sqlResult.code = "500";
                            sqlResult.msg = "绑定的微信与登陆的微信不匹配！！";
                            sqlResult.data = null;
                        }
                    }*/
                    sqlResult.code = "200";
                    sqlResult.msg = "登录成功";
                    var DataList = dataTable.AsEnumerable().Select(e => new
                    {
                        FNAME = e.Field<string>("FNAME"),
                        FSTUDENTID = e.Field<int>("FSTUDENTID"),
                        FDUTIES = e.Field<string>("FDUTIES"),
                        FSEX = e.Field<string>("FSEX"),
                        FMOBILE = e.Field<string>("FMOBILE"),
                        FNUMBER = e.Field<string>("FNUMBER"),
                        FWORKUNIT1 = e.Field<string>("FWORKUNIT1"),
                        FIMAGEFILESERVER = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FIMAGEFILESERVER"), obj.UserToken())
                    });
                    sqlResult.data = DataList;
                    if (!string.IsNullOrWhiteSpace(OpenId))
                    {
                        string sqlSelect1 = $"select 1 from T_PX_StudentsInfo T1 left join T_PX_StudentsInfo_L T2 on T1.FSTUDENTID = T2.FSTUDENTID where FOPENID = '{OpenId}'";
                        DataTable dataTable1 = obj.ExecuteDataTable(sqlSelect1);
                        if (dataTable1.Rows.Count < 1)
                        {
                            if (string.IsNullOrWhiteSpace(dataTable.Rows[0]["FOPENID"].ToString()))
                            {
                                string uptSql = $"update T_PX_StudentsInfo set FOPENID='{OpenId}' where FMobile='{Phone}'";
                                int results = obj.Execute(uptSql);
                                if (results > 0)
                                    sqlResult.msg = "登录成功,微信绑定成功";
                            }
                        }
                        /*else
                        {
                            sqlResult.code = "500";
                            sqlResult.msg = "该微信已绑定其他账号！！";
                            sqlResult.data = null;
                        }*/
                    }
                }
                else
                {
                    sqlResult.code = "500";
                    sqlResult.msg = "不存在该用户";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:LoginCode", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "错误" + ex.Message;
            }
            return sqlResult;
        }
        /// <summary>
        /// 更新头像
        /// </summary>
        /// <returns></returns>
        public SQLResult UserImage()
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                HttpRequest request = System.Web.HttpContext.Current.Request;
                var studenId = request.Form["studentId"];
                var Path = Image(request);
                var Jct = Path[0];
                var FileId = Jct["FileId"].ToString();
                string UptSelect = $"update T_PX_StudentsInfo set FIMAGEFILESERVER='{FileId}' where FSTUDENTID='{studenId}'";
                if (obj.Execute(UptSelect) > 0)
                {
                    sqlResult.code = "200";
                    sqlResult.data = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileId, obj.UserToken());
                    sqlResult.msg = "更换图片成功";
                }
                else
                {
                    sqlResult.code = "500";
                    sqlResult.msg = "更换图片失败";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:UserImage", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "更换图片失败:" + ex.Message;
            }
            return sqlResult;
        }

    }
}
