using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Saving;
using Kingdee.BOS.Log;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.ServicesStub;
using LQKJ.WebApi.Stub;
using Newtonsoft.Json.Linq;
using NPOI.SS.Util;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

namespace LQKJ.K3.WebsiteAndSignUpSystem.WebApi
{
    public class WebApiService : CustomWebApiService
    {
        private readonly CustomWebApiService obj = null;
        static object lockObject = new object();
        public WebApiService(KDServiceContext context) : base(context)
        {
            obj = new CustomWebApiService(context);
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <returns></returns>
        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>
        /// word转富文本
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private string ConvertWordToRichText(string filePath)
        {
            try
            {
                using (HttpClient webClient = new HttpClient())
                {
                    webClient.Timeout = TimeSpan.FromSeconds(15);
                    byte[] buffer = webClient.GetByteArrayAsync(filePath).Result;
                    if (buffer.Length >= 8 && buffer[0] == 0x50 && buffer[1] == 0x4B && buffer[2] == 0x03 && buffer[3] == 0x04)
                    {
                        using (MemoryStream byteStream = new MemoryStream(buffer))
                        {
                            Document doc = new Document(byteStream);
                            HtmlSaveOptions saveOptions = new HtmlSaveOptions();
                            saveOptions.ExportImagesAsBase64 = true;
                            MemoryStream stream = new MemoryStream();
                            doc.Save(stream, saveOptions);
                            //将内存流的内容转换为字符串
                            string htmlContent = Encoding.UTF8.GetString(stream.ToArray());
                            return htmlContent;
                        }
                    }
                    else
                    {
                        // 如果下载的不是有效的Word文档，你可以在这里进行相应的处理
                        return "";
                    }
                }
            }
            catch (Exception)
            {
                return "请求超时或文件服务器错误！！请刷新重试，若无效请联系管理员";
            }
        }

        /// <summary>
        /// 获取word的纯文本
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private string ConvertWordToText(string filePath)
        {
            try
            {
                using (HttpClient webClient = new HttpClient())
                {
                    webClient.Timeout = TimeSpan.FromSeconds(5);
                    byte[] buffer = webClient.GetByteArrayAsync(filePath).Result;
                    if (buffer.Length >= 8 && buffer[0] == 0x50 && buffer[1] == 0x4B && buffer[2] == 0x03 && buffer[3] == 0x04)
                    {
                        using (MemoryStream byteStream = new MemoryStream(buffer))
                        {
                            Document doc = new Document(byteStream);
                            return doc.GetText().Substring(0, 200);
                        }
                    }
                    else
                    {
                        return "";
                    }
                }
            }
            catch (Exception)
            {
                return "请求超时或文件服务器错误！！，请刷新重试，若无效请联系管理员";
            }
           
        }

        /// <summary>
        /// 保留了原始表的结构只包含传入的DataRow数组中的数据
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        private DataTable ConvertToDataTable(DataRow[] rows)
        {
            if (rows == null || rows.Length == 0) return null;
            DataTable dtnew = rows[0].Table.Clone();  // 复制DataRow的表结构
            foreach (DataRow dr in rows)
            {
                DataRow drnew = dtnew.NewRow(); //这行是关键
                drnew.ItemArray = dr.ItemArray;//这是加入的是第一行
                dtnew.Rows.Add(drnew);
            }
            return dtnew;
        }

        /*       /// <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 GetHomeData()
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string Sql = "/*dialect*/exec GW_GetHomeData";
                DataSet data = (DataSet)obj.ExecutDataSet(Sql).data;
                if (data == null || data.Tables.Count < 1)
                {
                    sqlReselt.code = "200";
                    sqlReselt.msg = "没有任何数据";
                    return sqlReselt;
                }
                var DataList = new
                {
                    //海报
                    medioBanner = data.Tables[0].AsEnumerable().Select(e => new
                    {
                        FEntryID = e.Field<Int64>("FEntryID"),//id
                        FEFSKIPLINKS = e.Field<String>("FEFSKIPLINKS"),//跳转链接
                        FEPOSTERPICTURE = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FEPOSTERPICTURE"), obj.UserToken())//图片地址
                    }),
                    //产品与服务
                    cpService = data.Tables[1].AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FPRODUCTSSERVICES = e.Field<string>("FPRODUCTSSERVICES"),//服务名称
                        FPICTURE = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FPICTURE"), obj.UserToken())//图片地址
                    }),
                    //头条资讯
                    ttAdvise = data.Tables[2].AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FTITLE = e.Field<string>("FTITLE"),//标题
                        FRELEASETIME = e.Field<DateTime>("FRELEASETIME"),//发布时间
                        FTYPE = e.Field<string>("FTYPE")//类型
                    }),
                    //公示公告
                    gsAdvise = data.Tables[3].AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FTITLE = e.Field<string>("FTITLE"),//标题
                        FRELEASETIME = e.Field<DateTime>("FRELEASETIME"),//发布时间
                        FTYPE = e.Field<string>("FTYPE")//类型
                    }),
                    //招聘公告
                    zpNotice = data.Tables[4].AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FTITLE = e.Field<string>("FTITLE"),//标题
                        FRELEASETIME = e.Field<DateTime>("FRELEASETIME"),//发布时间
                        FTYPEANNOUN = e.Field<string>("FTYPEANNOUN")//公告类型
                    }),
                    //惠企政策
                    hqNotice = data.Tables[5].AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FTITLE = e.Field<string>("FTITLE"),//标题
                        FRELEASETIME = e.Field<DateTime>("FRELEASETIME"),//发布时间
                        FTYPEANNOUN = e.Field<string>("FTYPEANNOUN")//公告类型
                    }),
                    //技能培训
                    jlNotice = data.Tables[6].AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FTITLE = e.Field<string>("FTITLE"),//标题
                        FRELEASETIME = e.Field<DateTime>("FRELEASETIME"),//发布时间
                        FTYPEANNOUN = e.Field<string>("FTYPEANNOUN")//公告类型
                    }),
                    //党建风采
                    djNotice = data.Tables[7].AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FTITLE = e.Field<string>("FTITLE"),//标题
                        FRELEASETIME = e.Field<DateTime>("FRELEASETIME"),//发布时间
                        FTYPEANNOUN = e.Field<string>("FTYPEANNOUN")//公告类型
                    })
                };
                sqlReselt.code = "200";
                sqlReselt.msg = "查询成功";
                sqlReselt.data = DataList;
                return sqlReselt;
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:GetHomeData", ex.Message, ex);
                sqlReselt.msg = "查询失败,服务端错误";
                return sqlReselt;
            }
        }

        /// <summary>
        /// 海报信息
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        public SQLResult PosterInfo(string Type)
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string Sql = $"/*dialect*/select T2.FEntryID,T2.FEFSKIPLINKS,T2.FEPOSTERPICTURE From T_GW_PosterConfiig T1,T_GW_Poster T2 where T1.FID=T2.FID and FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A' and FPOSTERMODULE='{Type}'";
                DataTable HbDt = obj.ExecuteDataTable(Sql);
                if (HbDt != null && HbDt.Rows.Count > 0)
                {
                    sqlReselt.data = HbDt.AsEnumerable().Select(e => new
                    {
                        FEntryID = e.Field<Int64>("FEntryID"),
                        FEFSKIPLINKS = e.Field<string>("FEFSKIPLINKS"),//跳转链接
                        FEPOSTERPICTURE = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FEPOSTERPICTURE"), obj.UserToken()),//图片地址
                    });
                    sqlReselt.msg = "查询成功";
                    sqlReselt.code = "200";

                }
                else
                {
                    sqlReselt.code = "200";
                    sqlReselt.data = null;
                    sqlReselt.msg = "无数据";
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:PosterInfo", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 查询所有产品与服务
        /// </summary>
        /// <returns></returns>
        public SQLResult SelectCpServerAll()
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string Sql = "/*dialect*/select FID,FPRODUCTSSERVICES,FCONTENTFILE From T_GW_ProductsServices where FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A'";
                DataTable CpDt = obj.ExecuteDataTable(Sql);
                if (CpDt != null && CpDt.Rows.Count > 0)
                {
                    sqlReselt.code = "200";
                    sqlReselt.msg = "查询成功";
                    sqlReselt.data = CpDt.AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FPRODUCTSSERVICES = e.Field<string>("FPRODUCTSSERVICES"),//产品服务名称
                        FCONTENTS = ConvertWordToRichText(string.Format(url + "FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FCONTENTFILE"), obj.UserToken())),//内容
                    });
                }
                else
                {
                    sqlReselt.code = "200";
                    sqlReselt.data = null;
                    sqlReselt.msg = "无数据";
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectCpServerAll", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 公告详情
        /// </summary>
        /// <param name="Fid"></param>
        /// <returns></returns>
        public SQLResult SelectGgDetails(string FID)
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string Sql = $"/*dialect*/ exec GW_GetGgDetails @FID='{FID}'";
                DataSet dataSet = (DataSet)obj.ExecutDataSet(Sql).data;
                if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                {
                    var DetailsRow = dataSet.Tables[0].AsEnumerable().FirstOrDefault();
                    //DataTable dataTable = ConvertToDataTable(dataSet.Tables[1].AsEnumerable().ToArray());
                    sqlReselt.data = new
                    {
                        FID = DetailsRow.Field<Int64>("FID"),
                        FTITLE = DetailsRow.Field<string>("FTITLE"),//标题
                        FPUBLISHER = DetailsRow.Field<string>("FPUBLISHER"),//标题
                        FRELEASETIME = DetailsRow.Field<DateTime>("FRELEASETIME").ToString("yyyy-MM-dd HH:mm"),//发布时间
                        FCONTENTS = ConvertWordToRichText(string.Format(url + "FileUpLoadServices/download.aspx?fileId={0}&token={1}", DetailsRow.Field<string>("FCONTENTFILE"), obj.UserToken())),//内容
                        FTYPE = DetailsRow.Field<string>("FTYPE"),//资讯公告类型
                        FTYPEANNOUN = DetailsRow.Field<string>("FTYPEANNOUN"),//公告类型
                        Attachmens = dataSet.Tables[1].AsEnumerable().Select(e => new
                        {
                            FATTACHMENTNAME = e.Field<string>("FATTACHMENTNAME"),//文件名称
                            Url = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FFILEID"), obj.UserToken())//下载地址
                        })
                    };
                    sqlReselt.code = "200";
                    sqlReselt.msg = "获取数据成功";
                }
                else
                {
                    sqlReselt.code = "200";
                    sqlReselt.data = null;
                    sqlReselt.msg = "无数据";
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectGgDetails", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 通知公告列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public SQLResult SelectTzGgList(int? pageSize, int? pageIndex)
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string sqlTotal = string.Format("/*dialect*/ select COUNT(*) From T_GW_Announcement where FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A'and (FTYPE='ZX'or FTYPE='GG')");
                DataTable CountDt = obj.ExecuteDataTable(sqlTotal);
                if (CountDt == null || CountDt.Rows.Count < 1 || (int)CountDt.Rows[0][0] == 0)
                {
                    sqlReselt.code = "200";
                    sqlReselt.msg = "无数据";
                }
                else
                {
                    int StartRow = ((pageIndex ?? 1) - 1) * (pageSize ?? 10);
                    string sqlSelect = string.Format($@"/*dialect*/select  FID,FTITLE,FRELEASETIME,FCONTENTFILE,FTYPE 
	                                                    From T_GW_Announcement 
	                                                    where FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A' and (FTYPE='ZX'or FTYPE='GG')
	                                                    ORDER BY FRELEASETIME Desc
	                                                    OFFSET {StartRow} ROWS
	                                                    FETCH NEXT {pageSize ?? 10} ROWS ONLY;");
                    DataTable dtSelect = obj.ExecuteDataTable(sqlSelect);
                    if (dtSelect.Rows.Count < 1)
                    {
                        sqlReselt.code = "200";
                        sqlReselt.msg = "该页面无数据";
                    }
                    else
                    {
                        sqlReselt.data = dtSelect.AsEnumerable().Select(e => new
                        {
                            FID = e.Field<Int64>("FID"),
                            FTITLE = e.Field<string>("FTITLE"),
                            FRELEASETIME = e.Field<DateTime>("FRELEASETIME").ToString("yyyy-MM-dd HH:MM:ss"),
                            FTYPE = e.Field<string>("FTYPE"),
                            FCONTENT = ConvertWordToText(string.Format(url + "FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FCONTENTFILE"), obj.UserToken())),//内容,
                        });
                        sqlReselt.total = (int)CountDt.Rows[0][0];
                        sqlReselt.code = "200";
                        sqlReselt.msg = "查询成功";
                    }
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectTzGgList", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 招聘公告列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        public SQLResult SelectZpGgLIst(int? pageSize, int? pageIndex, string Type)
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string SqlTotal = string.Format("select COUNT(*) From T_GW_Announcement where FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A' AND FTYPEANNOUN='{0}'", Type);
                DataTable CountDt = obj.ExecuteDataTable(SqlTotal);
                if (CountDt == null || CountDt.Rows.Count < 1 || (int)CountDt.Rows[0][0] == 0)
                {
                    sqlReselt.code = "200";
                    sqlReselt.msg = "无数据";
                }
                else
                {
                    int StartRow = ((pageIndex ?? 1) - 1) * (pageSize ?? 10);
                    string sqlSelect = string.Format($@"/*dialect*/select  FID,FTITLE,FRELEASETIME,FCONTENTFILE,FTYPEANNOUN 
	                                                    From T_GW_Announcement 
	                                                    where FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A' and FTYPEANNOUN='{Type}'
	                                                    ORDER BY FRELEASETIME Desc
	                                                    OFFSET {StartRow} ROWS
	                                                    FETCH NEXT {pageSize ?? 10} ROWS ONLY;");
                    DataTable dtSelect = obj.ExecuteDataTable(sqlSelect);
                    if (dtSelect.Rows.Count < 0)
                    {
                        sqlReselt.code = "200";
                        sqlReselt.msg = "该页面无数据";
                    }
                    else
                    {
                        sqlReselt.data = dtSelect.AsEnumerable().Select(e => new
                        {
                            FID = e.Field<Int64>("FID"),
                            FTITLE = e.Field<string>("FTITLE"),
                            FRELEASETIME = e.Field<DateTime>("FRELEASETIME").ToString("yyyy-MM-dd HH:MM:ss"),
                            FTYPEANNOUN = e.Field<string>("FTYPEANNOUN"),
                            FCONTENT = ConvertWordToText(string.Format(url + "FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FCONTENTFILE"), obj.UserToken())),//内容,
                        });
                        sqlReselt.total = (int)CountDt.Rows[0][0];
                        sqlReselt.code = "200";
                        sqlReselt.msg = "查询成功";
                    }
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectTzGgList", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 查询所有关于我们内容
        /// </summary>
        /// <returns></returns>
        public SQLResult SelectAboutUsAll()
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string Sql = "/*dialect*/select FID,FTITLE,FCONTENTFILE,FORDER From T_GW_AboutUs where FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A' order by FORDER";
                DataTable CpDt = obj.ExecuteDataTable(Sql);
                if (CpDt != null && CpDt.Rows.Count > 0)
                {
                    sqlReselt.data = CpDt.AsEnumerable().Select(e => new
                    {
                        FID = e.Field<Int64>("FID"),
                        FTITLE = e.Field<string>("FTITLE"),//标题
                        FORDER = e.Field<int>("FORDER"),//显示序号
                        FCONTENTS = ConvertWordToRichText(string.Format(url + "FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FCONTENTFILE"), obj.UserToken())),//内容
                    });
                    sqlReselt.code = "200";
                    sqlReselt.msg = "查询成功";
                }
                else
                {
                    sqlReselt.code = "200";
                    sqlReselt.data = null;
                    sqlReselt.msg = "无数据";
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectCpServerAll", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 查询考试报名列表
        /// </summary>
        /// <returns></returns>
        public SQLResult SelectExaminaRegistraList(int? pageSize, int? pageIndex)
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string sqlTotal = string.Format("/*dialect*/ select  COUNT(*) from T_GW_TestRegistration where FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A'");//已开始报名的所有数据（FREGISTRATIONSTARTTIME<GETDATE()）
                DataTable CountDt = obj.ExecuteDataTable(sqlTotal);
                if (CountDt == null || CountDt.Rows.Count < 1 || (int)CountDt.Rows[0][0] == 0)
                {
                    sqlReselt.code = "200";
                    sqlReselt.msg = "无数据";
                }
                else
                {
                    int StartRow = ((pageIndex ?? 1) - 1) * (pageSize ?? 10);
                    string sqlSelect = string.Format($@"/*dialect*/select  T1.FID,CASE WHEN FREGISTRATIONENDTIME>GETDATE() THEN 1 ELSE 2 END [State],
                                                        FREGISTRATIONSTARTTIME,T2.FNAME
                                                        from T_GW_TestRegistration T1,T_GW_TestRegistration_L T2 where FDOCUMENTSTATUS = 'C' AND 
                                                        FFORBIDSTATUS = 'A'And  T2.FLocaleID=2052 and T1.FID=T2.FID
                                                        order by [State],FREGISTRATIONENDTIME Desc,FREGISTRATIONSTARTTIME desc
	                                                    OFFSET {StartRow} ROWS
	                                                    FETCH NEXT {pageSize ?? 10} ROWS ONLY;");
                    DataTable dtSelect = obj.ExecuteDataTable(sqlSelect);
                    if (dtSelect.Rows.Count < 1)
                    {
                        sqlReselt.code = "200";
                        sqlReselt.msg = "无数据";
                    }
                    else
                    {
                        sqlReselt.data = dtSelect.AsEnumerable().Select(e => new
                        {
                            FID = e.Field<Int32>("FID"),
                            State = e.Field<int>("State"),
                            FTITLEREGISTRATION = e.Field<string>("FNAME"),//标题
                            FREGISTRATIONSTARTTIME = e.Field<DateTime>("FREGISTRATIONSTARTTIME").ToString("yyyy-MM-dd HH:MM:ss"),
                        });
                        sqlReselt.total = (int)CountDt.Rows[0][0];
                        sqlReselt.code = "200";
                        sqlReselt.msg = "查询成功";
                    }
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectTzGgList", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 考试报名详情
        /// </summary>
        /// <param name="Fid"></param>
        /// <returns></returns>
        public SQLResult SelectExaminaRegistraDetails(string FID)
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string Sql = $"/*dialect*/exec GW_GetExaminaRegistraDetails @FID='{FID}'";
                DataSet dataSet = (DataSet)obj.ExecutDataSet(Sql).data;
                if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
                {
                    var DetailsRow = dataSet.Tables[0].AsEnumerable().FirstOrDefault();
                    //DataTable dataTable = ConvertToDataTable(dataSet.Tables[1].AsEnumerable().ToArray());
                    sqlReselt.data = new
                    {
                        FID = DetailsRow.Field<Int32>("FID"),
                        FTITLEREGISTRATION = DetailsRow.Field<string>("FNAME"),//标题
                        State = DetailsRow.Field<int>("State"),//状态
                        FREGISTRATIONSTARTTIME = DetailsRow.Field<DateTime>("FREGISTRATIONSTARTTIME").ToString("yyyy-MM-dd HH:mm"),//开始时间
                        FREGISTRATIONENDTIME = DetailsRow.Field<DateTime>("FREGISTRATIONENDTIME").ToString("yyyy-MM-dd HH:mm"),//结束时间
                        FTIMEEXAMINATION = DetailsRow.Field<DateTime>("FTIMEEXAMINATION").ToString("yyyy-MM-dd HH:mm"),//考试时间时间
                        FLOCATIONEXAMINATION = DetailsRow.Field<string>("FLOCATIONEXAMINATION"),//考试地点
                        FNUMBEREXAMINATIONS = DetailsRow.Field<int>("FNUMBEREXAMINATIONS"),//名额人数
                        FAPPLICANTSNUMBER = DetailsRow.Field<int>("FAPPLICANTSNUMBER"),//报名人数
                        FSURPLUSNUMBER = DetailsRow.Field<int>("FSURPLUSNUMBER"),//剩余名额人数
                        FCONTENTS = ConvertWordToRichText(string.Format(url + "FileUpLoadServices/download.aspx?fileId={0}&token={1}", DetailsRow.Field<string>("FCONTENTFILE"), obj.UserToken())),//内容

                        Attachmens = dataSet.Tables[1].AsEnumerable().Select(e => new
                        {
                            FATTACHMENTNAME = e.Field<string>("FATTACHMENTNAME"),//文件名称
                            Url = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FFILEID"), obj.UserToken())//下载地址
                        })
                    };
                    sqlReselt.code = "200";
                    sqlReselt.msg = "获取数据成功";
                }
                else
                {
                    sqlReselt.code = "200";
                    sqlReselt.data = null;
                    sqlReselt.msg = "无数据";
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectExaminaRegistraDetails", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 查询所有辅助资料
        /// </summary>
        /// <returns></returns>
        public SQLResult SelectSecondaryData()
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string Sql = "/*dialect*/EXEC GW_SecondaryData";
                DataSet FzDst = (DataSet)obj.ExecutDataSet(Sql).data;
                if (FzDst != null)
                {
                    sqlReselt.data = new
                    {
                        CertificateCategory = ConvertToDataTable(FzDst.Tables[0].AsEnumerable().ToArray()),
                        POLITICAL = ConvertToDataTable(FzDst.Tables[1].AsEnumerable().ToArray()),
                        National = ConvertToDataTable(FzDst.Tables[2].AsEnumerable().ToArray()),
                        EDUCATION = ConvertToDataTable(FzDst.Tables[3].AsEnumerable().ToArray()),
                        DEGREE = ConvertToDataTable(FzDst.Tables[4].AsEnumerable().ToArray()),
                        HEALTH = ConvertToDataTable(FzDst.Tables[5].AsEnumerable().ToArray()),
                        MARRIAGE = ConvertToDataTable(FzDst.Tables[6].AsEnumerable().ToArray()),
                        SKILLLEVEL = ConvertToDataTable(FzDst.Tables[7].AsEnumerable().ToArray())
                    };
                    sqlReselt.code = "200";
                    sqlReselt.msg = "查询成功";
                }
                else
                {
                    sqlReselt.code = "200";
                    sqlReselt.data = null;
                    sqlReselt.msg = "无数据";
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectSecondaryData", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }

        /// <summary>
        /// 查看报名表
        /// </summary>
        /// <returns></returns>
        public SQLResult SelectEntryForm()
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                string tokenstr = request.Headers["Authorization"]?.ToString();
                SQLResult result = Utility.DecryptTokens(tokenstr);
                if (result.code != "200")
                    return result;
                Token token = (Token)result.data;
                string Selectsql = $"/*dialect*/exec GW_SelectEntryForm @FID='{token.FID}'";
                DataSet dtSet = (DataSet)obj.ExecutDataSet(Selectsql).data;
                string objToken= obj.UserToken();
                if (dtSet == null|| dtSet.Tables[0].Rows.Count == 0)
                {
                    sqlReselt.code = "501";
                    sqlReselt.msg = "查询失败,账号不存在或已被禁用，请联系管理员维护";
                    sqlReselt.data =null;
                }
                else
                {
                    sqlReselt.code = "200";
                    sqlReselt.msg = "查询成功";
                    var FileRow = dtSet.Tables[1].AsEnumerable().FirstOrDefault();
                    sqlReselt.data = new
                    {
                        BasicInfo = ConvertToDataTable(dtSet.Tables[0].AsEnumerable().ToArray()),
                        FileInfo = new
                        {
                            FFProfilePictureService = FileRow.Field<string>("FFProfilePictureService"),
                            FFProfilePictureServiceUrl = string.Format(string.IsNullOrWhiteSpace(FileRow.Field<string>("FFProfilePictureService")) ? "" : "FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileRow.Field<string>("FFProfilePictureService"), objToken),
                            FIdCardFront = FileRow.Field<string>("FIdCardFront"),
                            FIdCardFrontUrl = string.Format(string.IsNullOrWhiteSpace(FileRow.Field<string>("FIdCardFront")) ? "" : "FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileRow.Field<string>("FIdCardFront"), objToken),
                            FIdCdardBack = FileRow.Field<string>("FIdCdardBack"),
                            FUndergraduateCertificate = FileRow.Field<string>("FUndergraduateCertificate"),
                            FUndergraduateCertificateUrl = string.Format(string.IsNullOrWhiteSpace(FileRow.Field<string>("FUndergraduateCertificate")) ? "" : "FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileRow.Field<string>("FUndergraduateCertificate"), objToken),
                            FMasterCertificate = FileRow.Field<string>("FMasterCertificate"),
                            FMasterCertificateUrl = string.Format(string.IsNullOrWhiteSpace(FileRow.Field<string>("FMasterCertificate")) ? "" : "FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileRow.Field<string>("FMasterCertificate"), objToken),
                            FDoctorCertificate = FileRow.Field<string>("FDoctorCertificate"),
                            FDoctorCertificateUrl = string.Format(string.IsNullOrWhiteSpace(FileRow.Field<string>("FDoctorCertificate")) ? "" : "FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileRow.Field<string>("FDoctorCertificate"), objToken),
                            FOtherCertificate = FileRow.Field<string>("FOtherCertificate"),
                            FOtherCertificateUrl = string.Format(string.IsNullOrWhiteSpace(FileRow.Field<string>("FOtherCertificate")) ? "" : "FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileRow.Field<string>("FOtherCertificate"), objToken),
                            FPracticeCertificate = FileRow.Field<string>("FPracticeCertificate"),
                            FPracticeCertificateUrl = string.Format(string.IsNullOrWhiteSpace(FileRow.Field<string>("FPracticeCertificate")) ? "" : "FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileRow.Field<string>("FPracticeCertificate"), objToken),
                        },
                        FamilyList = ConvertToDataTable(dtSet.Tables[2].AsEnumerable().ToArray()),
                        WorkList = ConvertToDataTable(dtSet.Tables[3].AsEnumerable().ToArray())
                    };
                }
            }
            catch (Exception ex)
            {
                sqlReselt.code = "500";
                Logger.Error("ActionName:SelectEntryForm", ex.Message, ex);
                sqlReselt.data = null;
                sqlReselt.msg = "查询失败,服务端错误";
            }
            return sqlReselt;
        }
        /*/// <summary>
        /// 上传图片-单张
        /// </summary>
        /// <returns></returns>
        public SQLResult UploadImage()
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                HttpRequest request = System.Web.HttpContext.Current.Request;
                var Path = Image(request);
                var Jct = Path[0];
                var FileId = Jct["FileId"].ToString();
                sqlResult.code = "200";
                sqlResult.data = Jct;
                sqlResult.msg = "上传图片成功";
                
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:UserImage", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "上传图片失败:";
            }
            return sqlResult;
        }*/

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        public ApiResult UploadFile()
        {
            lock (lockObject)
            {
                ApiResult apiResult = new ApiResult();
                try
                {
                    HttpRequest request = System.Web.HttpContext.Current.Request;
                    var HttpFile = request.Files?["File"];
                    if (HttpFile == null)
                    {
                        apiResult.code = 500;
                        apiResult.msg = "未上传文件:";
                        apiResult.success = false;
                    }
                    else
                    {
                        string fileName = System.IO.Path.GetFileName(HttpFile.FileName);
                        Stream stream = HttpFile.InputStream;
                        byte[] fileByte = new byte[stream.Length];
                        stream.Read(fileByte, 0, fileByte.Length);
                        stream.Close();
                        string Base64string = Convert.ToBase64String(fileByte);
                        var Result = obj.FilePath(Base64string, fileName);
                        if (Result == null)
                        {
                            apiResult.code = 500;
                            apiResult.msg = "上传文件失败,请检查文件是否合法，或重新尝试！";
                            apiResult.success = false;
                        }
                        else
                        {
                            apiResult.code = 200;
                            apiResult.msg = "上传成功";
                            apiResult.data = Result;
                            apiResult.success = true;
                        }
                        apiResult.data = Result;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("ActionName:UploadFile", ex.Message, ex);
                    apiResult.code = 500;
                    apiResult.msg = "上传文件失败:";
                    apiResult.success = false;
                }
                return apiResult;
            }
        }

        /// <summary>
        /// 登录注册
        /// </summary>
        /// <returns></returns>
        public ApiResult LoginRegistration(string Phone, string UserType)
        {
            try
            {
                if (UserType == "GR")//待定
                {
                    string SelectGRSql = $"select  FID,FNUMBER,(select top 1 FNAME From T_GW_ApplicationForm_L where FLocaleID=2052 and FID=T1.FID)as FNAME,FFORBIDSTATUS,FUSERPHONE from T_GW_ApplicationForm T1  where FUSERPHONE='{Phone}'";//审核状态 and  FDOCUMENTSTATUS = 'C'
                    DataTable dataTable = obj.ExecuteDataTable(SelectGRSql);
                    if (dataTable == null || dataTable.Rows.Count < 1)
                    {
                        
                        K3CloudApiClient Client = apiClient();
                        string json = "{\"IsDeleteEntry\":\"false\",\"Model\":{\"FName\":\"\",\"FUserPhone\":\"" + Phone + "\",\"FDOCUMENTSTATUS\":\"C\"}";
                        var result = JObject.Parse(Client.Save("LQKJ_ApplicationForm", json));
                        var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                        if ((bool)Sueccess)
                        {
                            return ApiResultHelper.Success(new {token = Utility.CreateToken(result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"].ToString(),  (string)result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"], Phone), }, "注册成功");
                        }
                        else
                        {
                            return ApiResultHelper.Error("注册失败！！请联系管理员");
                        }
                    }
                    else
                    {
                        if (dataTable.Rows[0][3].ToString() != "A")
                        {
                            return ApiResultHelper.Error("账号已禁用！！请联系管理员");
                        }
                        return ApiResultHelper.Success(new { token = Utility.CreateToken(dataTable.Rows[0][0].ToString(), (string)dataTable.Rows[0][1],(string)dataTable.Rows[0][4]), FName = string.IsNullOrWhiteSpace(dataTable.Rows[0][2]?.ToString()) ? "" : dataTable.Rows[0][2]?.ToString() }, "登录成功");
                    }
                }
                else
                {
                    return ApiResultHelper.Error("企业用户登录注册未开放！");

                }
                /*string SelectSql = $"select FID from T_GW_XBRLUser where  FDOCUMENTSTATUS = 'C' AND FFORBIDSTATUS = 'A' and FPHONE='{Phone}'";
                DataTable dataTable=obj.ExecuteDataTable(SelectSql);
                if (dataTable == null||dataTable.Rows.Count<1)
                {
                    K3CloudApiClient Client = apiClient();
                    string json = "{\"NeedReturnFields\":[\"FID\",\"FBillNo\"],\"IsDeleteEntry\":\"false\",\"Model\":{\"FPhone\":\"" + Phone + "\"}";
                    var result = JObject.Parse(Client.Save("LQKJ_SystemUser", json));
                    var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                    if ((bool)Sueccess)
                    {
                        return ApiResultHelper.Success(new { FID = (string)result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"] }, "注册成功");
                    }
                    else
                    {
                        return ApiResultHelper.Error("登录注册失败！！请联系管理员");
                    }
                }
                else
                {
                    return ApiResultHelper.Success(new { FID = (string)dataTable.Rows[0][0] }, "登录成功");
                }
                */
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:LoginRegistration", ex.Message, ex);
                return ApiResultHelper.Error("登录注册失败！！请联系管理员");
            }
        }
        
        /// <summary>
        /// 修改报名表
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateEntryForm(string parmeter)
        {
            lock (lockObject)
            {
                try
                {
                    HttpRequest request = HttpContext.Current.Request;
                    string tokenstr = request.Headers["Authorization"]?.ToString();
                    ApiResult result = Utility.DecryptToken(tokenstr);
                    if (result.code != 200)
                        return result;
                    Token token = result.data;

                    if (string.IsNullOrWhiteSpace(parmeter))
                    {
                        return ApiResultHelper.Error("参数错误！！");
                    }
                    var Parmeters = JObject.Parse(parmeter);
                    JObject innerObject = (JObject)Parmeters["Model"];
                    // 添加新的键值对
                    innerObject.Add("FID", token.FID);
                    innerObject.Add("FNumber", token.FNumber);
                    innerObject.Add("FUserPhone", token.FUserPhone);
                    K3CloudApiClient Client = apiClient();
                    var results = JObject.Parse(Client.Save("LQKJ_ApplicationForm", Parmeters.ToString()));
                    var Sueccess = results["Result"]["ResponseStatus"]["IsSuccess"];
                    if ((bool)Sueccess)
                    {
                        return ApiResultHelper.Success(null, "修改成功");
                    }
                    else
                    {
                        return ApiResultHelper.Error("修改失败请联系管理员维护！");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("ActionName:UpdateEntryForm", ex.Message, ex);
                    return ApiResultHelper.Error("保存失败！！请联系管理员");
                }
            }
        }

        /// <summary>
        /// 查看报名信息列表
        /// </summary>
        /// <returns></returns>
        public  SQLResult SelectRegistrationInforList()
        { 
            SQLResult sqlResult = new SQLResult();
            try
            {

            }
            catch (Exception ex)
            {
                sqlResult.code = "500";
                Logger.Error("ActionName:SelectEntryForm", ex.Message, ex);
                sqlResult.data = null;
                sqlResult.msg = "查询失败,服务端错误";
            }
            return sqlResult;   
        }

        /// <summary>
        /// 考试报名
        /// </summary>
        /// <returns></returns>
        public ApiResult ExaminationRegistration(string ExaminFID, string parmeter)
        {
            lock (lockObject)
            {
                try
                {
                    HttpRequest request = HttpContext.Current.Request;
                    string tokenstr = request.Headers["Authorization"]?.ToString();
                    ApiResult result = Utility.DecryptToken(tokenstr);
                    if (result.code != 200)
                        return result;
                    Token token = result.data;
                    string FormID = token.FID;
                    //验证考试报名是否在报名时间内以及是否存在
                    string SelectExamination = $"select FNUMBER,FREGISTRATIONSTARTTIME,FREGISTRATIONENDTIME,FSURPLUSNUMBER From T_GW_TestRegistration where FDOCUMENTSTATUS='C' and FFORBIDSTATUS='A' and FID={ExaminFID}";
                    DataTable SelectExaminationDt = obj.ExecuteDataTable(SelectExamination);
                    if (SelectExaminationDt == null || SelectExaminationDt.Rows.Count < 1)
                    {
                        return ApiResultHelper.Error("报名失败，报名项目不存在，请刷新数据！");
                    }
                    DateTime StartTime;
                    DateTime EndTime;
                    if (!DateTime.TryParse(SelectExaminationDt.Rows[0]["FREGISTRATIONSTARTTIME"]?.ToString() ?? "", out StartTime) || !DateTime.TryParse(SelectExaminationDt.Rows[0]["FREGISTRATIONENDTIME"]?.ToString() ?? "", out EndTime))
                        return ApiResultHelper.Error("报名失败，报名信息有误，请联系管理员！");
                    if (StartTime > DateTime.Now)
                    {
                        return ApiResultHelper.Error("报名失败，未到报名时间！");
                    }
                    else if (EndTime < DateTime.Now)
                    {
                        return ApiResultHelper.Error("报名失败，已过报名时间！");
                    }
                    else if (int.Parse(SelectExaminationDt.Rows[0]["FSURPLUSNUMBER"].ToString()) < 1)
                    {
                        return ApiResultHelper.Error("报名失败，名额已满！");
                    }
                    //查询报名用户
                    string SelectForm = $"select FDOCUMENTSTATUS,FFORBIDSTATUS From T_GW_ApplicationForm  where  FID={FormID}";
                    DataTable SelectFormDt = obj.ExecuteDataTable(SelectForm);
                    if (SelectFormDt == null || SelectFormDt.Rows.Count < 1)
                    {
                        return ApiResultHelper.Error("报名失败，用户不存在，请联系管理员维护！");
                    }
                    else if ((SelectFormDt.Rows[0]["FFORBIDSTATUS"]?.ToString() ?? "") != "A")
                    {
                        return ApiResultHelper.Error("报名失败，账号被禁用！");
                    }
                    else if ((SelectFormDt.Rows[0]["FDOCUMENTSTATUS"]?.ToString() ?? "") != "C")
                    {
                        return ApiResultHelper.Error("报名失败，账号未审核！");
                    }
                    //判断是否已报名
                    string SelectExaminList = $"select FDOCUMENTSTATUS from T_GW_RegistrationInfor where FDOCUMENTSTATUS='C'and FFORBIDSTATUS='A'and FREGISTRATIONSTATUS='A' and FAPPLICATIONPROJECT='{ExaminFID}'and FREGISTEREDUSER='{FormID}'";
                    DataTable SelectExaminListDt = obj.ExecuteDataTable(SelectExaminList);
                    if (SelectExaminListDt.Rows.Count>0)
                    {
                        return ApiResultHelper.Error("报名失败，你已报考该考试项目！");
                    }
                    if (string.IsNullOrWhiteSpace(parmeter))
                    {
                        return ApiResultHelper.Error("参数错误！！请检查报名输入的数据是否合法！");
                    }
                    var Parmeters = JObject.Parse(parmeter);
                    JObject innerObject = (JObject)Parmeters["Model"];
                    // 添加新的键值对
                    Parmeters["Model"]["FSignUpDate"]= DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
                    Parmeters["Model"]["FApplicationProject"]["FNUMBER"] = SelectExaminationDt.Rows[0]["FNUMBER"].ToString();
                    Parmeters["Model"]["FRegisteredUser"]["FNUMBER"] = token.FNumber;
                    K3CloudApiClient Client = apiClient();
                    var results = JObject.Parse(Client.Save("LQKJ_RegistrationInfor", Parmeters.ToString()));
                    var Sueccess = results["Result"]["ResponseStatus"]["IsSuccess"];
                    if ((bool)Sueccess)
                    {
                        return ApiResultHelper.Success(null, "报名成功成功");
                    }
                    else
                    {
                        return ApiResultHelper.Error("报名失败请联系管理员维护！");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("ActionName:ExaminationRegistration", ex.Message, ex);
                    return ApiResultHelper.Error("报名失败，请重试或联系管理员！");
                }
            }
        }
    }
}
