using Kingdee.BOS.Log;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.WebApi.Client;
using LQKJ.WebApi.Stub;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
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.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace LQKJ.K3.FileSystem.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>
        /// <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="typeO"></param>
        /// <returns></returns>
        public ApiResult SelectDateTime(string typeO)
        {
            string sqlSelect = $@"exec DateSelect @Type='{typeO}'";
            DataSet dataSet = (DataSet)(obj.ExecutDataSet(sqlSelect).data);
            if (dataSet!=null&&dataSet.Tables != null && dataSet.Tables[1].Rows.Count > 0)
            {
                DataTable dataTable = dataSet.Tables[0];
                DataTable data = dataSet.Tables[1];
                var datalist2 = data.AsEnumerable().Select(e => new
                {
                    FID= e.Field<Int64>("FID"),
                    FEntryID = e.Field<Int64>("FEntryID"),
                    type = e.Field<string>("type"),
                    TimeType =e.Field<Int32>("TimeType").ToString(),
                    Time = (string)e.Field<string>("Time"),
                    FREMAINDERNUMBER = (int)e.Field<int>("FREMAINDERNUMBER")
                });
                var dataList = dataTable.AsEnumerable().Select(e => new
                {
                    FID= e.Field<Int64>("FID"),
                    Date = e.Field<string>("Date"),
                    FISRESTDAYS = e.Field<string>("FISRESTDAYS"),
                    WeekdayName = e.Field<string>("WeekdayName"),
                    data = datalist2.Where(m => m.FID == e.Field<Int64>("FID")).ToList()
                });
                return ApiResultHelper.Success(dataList, "查询成功");
            }
            else
            {
                return ApiResultHelper.Success(null,"没有任何数据");
            }
        }
        public ApiResult Add(string parmeters)
        {
            try
            {
                var msg = JObject.Parse(parmeters);
                K3CloudApiClient Client = apiClient();
                var result = JObject.Parse(Client.Save("LQKJ_ArchiveTransfer", msg.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)//添加成功
                {
                    var Id = result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"].ToString();
                    var FBillNo = result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"].ToString();
                    //Client.Submit("LQKJ_ArchiveTransfer", "{\"Ids\":" + Id + "}");
                    //Client.Audit("LQKJ_ArchiveTransfer", "{\"Ids\":" + Id + "}");
                    JProperty property1 = new JProperty("Id", Id);
                    JProperty property2 = new JProperty("FBillNo", FBillNo);

                    var Model = JObject.Parse(msg["Model"].ToString());
                    Model.Add(property1); Model.Add(property2);
                    return ApiResultHelper.Success(Model, "预约成功");
                }
                else
                {
                    var ErrorMsg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                    return ApiResultHelper.Error(ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:Add", ex.Message, ex);
            }
            return ApiResultHelper.Error("代码执行出错");
        }

        /// <summary>
        /// 附件上传
        /// </summary>
        /// <returns></returns>
        public ApiResult Uploda()
        {
            lock (lockObject)
            {
                HttpRequest request = HttpContext.Current.Request;
                //var Id = request.Form["Id"].ToString();
                //var FBillNo = request.Form["FBillNo"];
                var FEntryID = request.Form["FEntryID"].ToString();
                var File = request.Files["file"];
                if (File.FileName==null)
                    return ApiResultHelper.Error("上传的文件有误！！");
                var FileName = File.FileName;
                var Type = request.Form["type"].ToString();
                var parmeters = JObject.Parse(request.Form["parmeters"]);
                string sqlSelect = $"/*dialect*/ select format(FTIMEPERIOD,'yyyy-MM-dd')+' '+format(MAKETIME,'HH:mm') [Date],T2.FREMAINDERNUMBER from LQKJ_t_AppointmentRules T1,LQKJ_t_RULEINFORMATION T2 where T1.FID=T2.FID AND T2.FEntryID={FEntryID} and FDOCUMENTSTATUS = 'C' and T1.FFORBIDSTATUS='A'";
                DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                if(dataTable==null||dataTable.Rows.Count<1)
                    return ApiResultHelper.Error("预约的时间有误");
                DateTime dateTime = Convert.ToDateTime(dataTable.Rows[0][0].ToString());
                if (dateTime < DateTime.Now)
                {
                    return ApiResultHelper.Error("预约时间已过");
                }
                if (Type.Equals("0"))
                {
                    var fid = parmeters["Model"]["FIDCard"].ToString();
                    var dw = parmeters["Model"]["FUnitName"].ToString();
                    var date = dataTable.Rows[0][0].ToString();
                    sqlSelect = $"/*dialect*/ select FID from  T_DA_ArchiveTransfer where FIDCARD='{fid}' and FDATETIME1='{date}' and FUNITNAME='{dw}'and FHANDLESTATES !='Q'and FFORBIDSTATUS='A'";
                    if (obj.ExecuteDataTable(sqlSelect).Rows.Count > 0)
                    {
                        return ApiResultHelper.Error("您已经预约过，请取消后继续？");
                    }
                }
                string FTransferredBy = parmeters["Model"]["FTransferredBy"].ToString();
                string FIDCARD = parmeters["Model"]["FIDCard"].ToString();

                int YuQicount = 0 ;//查询逾期次数
                //验证是否存在逾期限制和是否在黑名单中
                string YuQiYZStr = $"exec OverduetVerification @FIDCARD='{FIDCARD}'";
                DataTable YuqiyzData = obj.ExecuteDataTable(YuQiYZStr);
                if(YuqiyzData!=null&& YuqiyzData.Rows.Count > 0)
                {
                    if(YuqiyzData.Rows[0][0].ToString()=="1")
                        return ApiResultHelper.Error("您的逾期未办理次数过多，无法预约,如有问题请联系管理员");
                    else if(YuqiyzData.Rows[0][0].ToString() == "2")
                        return ApiResultHelper.Error($"您的逾期未办理次数过多，无法预约！请{YuqiyzData.Rows[0]["XzDate"].ToString()}后再预约");
                    else if (YuqiyzData.Rows[0][0].ToString() == "4"&& YuqiyzData.Rows[0]["YJDATE"].ToString()!="")
                        return ApiResultHelper.Error($"您的已预约了{YuqiyzData.Rows[0]["YJDATE"].ToString()}，如需要修改预约时间，请取消后再预约");
                    else if (YuqiyzData.Rows[0][0].ToString() == "3")
                        YuQicount = int.Parse(YuqiyzData.Rows[0]["YuQiCount"].ToString());
                }
                Stream stream = File.InputStream;
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                string Base64string = Convert.ToBase64String(bytes);
                IWorkbook workbook = WorkbookFactory.Create(stream);
                ISheet sheet = workbook.GetSheetAt(0);
                IRow Row0 = sheet.GetRow(0);//第一行
                string Title = Row0.GetCell(0).ToString().Replace(" ", "");
                if (Title != "南山区国有企业退休人员移交人事档案名单汇总表")
                    return ApiResultHelper.Error("文件首行标题有误，请修改");
                IRow Row1 = sheet.GetRow(1);//第二行
                Dictionary<int, string> keyValues = new Dictionary<int, string>();
                keyValues.Add(0, "序号");
                keyValues.Add(1, "所属集团");
                keyValues.Add(2, "移交企业");
                keyValues.Add(3, "移交地属地");
                keyValues.Add(4, "");
                keyValues.Add(5, "姓名");
                keyValues.Add(6, "性别");
                keyValues.Add(7, "身份证号");
                keyValues.Add(8, "个人联系电话");
                keyValues.Add(9, "是否中共党员");
                keyValues.Add(10, "党组织关系所在地");
                keyValues.Add(11, "备注");
                keyValues.Add(12, "国有企业性质");
                foreach (var item in keyValues)
                {
                    var Value = Row1.GetCell(item.Key).ToString().Replace(" ", "");
                    if (Value != item.Value)
                        return ApiResultHelper.Error($"文件第二行标题内容:{Value}有误，请修改");
                }
                IRow Row8 = sheet.GetRow(2);//第三行
                var Jd = Row8.GetCell(3).ToString().Replace(" ", "");
                if (Jd != "街道")
                {
                    return ApiResultHelper.Error($"文件第二行标题内容:{Jd}有误，请修改");
                }
                var Sq = Row8.GetCell(4).ToString().Replace(" ", "");
                if (Sq != "社区")
                {
                    return ApiResultHelper.Error($"文件第二行标题内容:{Sq}有误，请修改");
                }
                IRow Row5 = sheet.GetRow(sheet.LastRowNum - 2);//盖章
                var Gz = Row5.GetCell(2).ToString().TrimEnd();
                var Gz1 = Gz.Substring(Gz.Length - 10);
                if (Gz1 != "集团/公司 （盖章）")
                {
                    return ApiResultHelper.Error($"文件第{sheet.LastRowNum - 2}行标题内容:{Gz}有误，请修改");
                }
                var Gz3 = Row5.GetCell(8).ToString().TrimEnd();
                if (!Gz3.Contains("街道") || !Gz3.Contains("社区工作站（盖章）"))
                {
                    return ApiResultHelper.Error($"文件第{sheet.LastRowNum - 2}行标题内容:{Gz3}有误，请修改");
                }
                var Row6 = sheet.GetRow(sheet.LastRowNum - 1);
                var Jbr = Row6.GetCell(2).ToString().TrimStart();
                var JbrName1 = Jbr.Substring(Jbr.IndexOf("：") == -1 ? Jbr.IndexOf(":") : Jbr.IndexOf("："));
                var Jbr2 = Jbr.Substring(0, 8);
                if (Jbr2 != "经办人（签字）：")
                {
                    return ApiResultHelper.Error($"文件第{sheet.LastRowNum - 1}行标题内容:{Jbr}有误，请修改");
                }
                Jbr = Row6.GetCell(8).ToString().TrimStart();
                var JbrName2 = Jbr.Substring(Jbr.IndexOf("：") == -1 ? Jbr.IndexOf(":") : Jbr.IndexOf("："));
                Jbr2 = Jbr.Substring(0, 8);
                if (Jbr2 != "经办人（签字）：")
                {
                    return ApiResultHelper.Error($"文件第{sheet.LastRowNum - 1}行标题内容:{Jbr}有误，请修改");
                }
                var Row7 = sheet.GetRow(sheet.LastRowNum);
                var dt1 = Row7.GetCell(2).ToString().Replace(" ", "");
                var dt2 = Row7.GetCell(8).ToString().Replace(" ", "");
                try
                {
                    Convert.ToDateTime(dt1);
                    Convert.ToDateTime(dt2);
                }
                catch (Exception)
                {
                    return ApiResultHelper.Error($"文件第{sheet.LastRowNum }行日期有误，请修改");
                }
                int sum = 0;
                for (int i = 3; i < sheet.LastRowNum - 7; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row.GetCell(0).ToString() == "")
                    {
                        return ApiResultHelper.Error($"文件第{i}行序号有误，请修改");
                    }
                    sum += 1;
                }
                if (sum > 20)
                {
                    return ApiResultHelper.Error($"档案资料不允许超过20条！");
                }
                stream.Dispose();
                //全部都通过了
                K3CloudApiClient Client = apiClient();
                
                if (dataTable.Rows[0][1].ToString().Equals("0"))
                {
                    return ApiResultHelper.Error("名额已满");
                }
                string Date = dataTable.Rows[0][0].ToString();
                parmeters["Model"]["FDatetime"] = Date;
                parmeters["Model"]["FTransferQty"] = sum;
                // 获取现有键的值并将其转换为JObject
                JObject innerObject = (JObject)parmeters["Model"];
                // 添加新的键值对
                innerObject.Add("FBeOverdue ", YuQicount);


                var result = JObject.Parse(Client.Save("LQKJ_ArchiveTransfer", parmeters.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if (!(bool)Sueccess)
                {
                    var ErrorMsg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                    return ApiResultHelper.Error(ErrorMsg);
                }
                sqlSelect = $"update LQKJ_t_RULEINFORMATION set FREMAINDERNUMBER=FREMAINDERNUMBER-1,FAPPOINTMENTQTY=FAPPOINTMENTQTY+1 where FEntryID ={FEntryID} ";
                obj.Execute(sqlSelect);
                var Phone = parmeters["Model"]["FPhoneNumber"].ToString();
                var Id = result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"].ToString();
                var FBillNo = result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"].ToString();
                StringBuilder stringBuilder = new StringBuilder();
                string header = "{\"IsDeleteEntry\": \"false\",\"Model\": {\"FID\": " + Id + ",\"F_LQKJ_ProfileInfoEntity\": [";
                stringBuilder.Append(header);
                string context = "";
                for (int i = 3; i < sheet.LastRowNum - 7; i++)
                {
                    IRow row = sheet.GetRow(i);
                    var Jt = row.GetCell(1).ToString();//所属集团
                    var Qy = row.GetCell(2).ToString();//移交企业
                    var Jd1 = row.GetCell(3).ToString();//街道
                    var Sq1 = row.GetCell(4).ToString();//社区
                    var Sm = row.GetCell(5).ToString();//姓名
                    var Xb = row.GetCell(6).ToString() == "男" ? 0 : 1;//性别
                    var Sfz = row.GetCell(7).ToString();//身份证号
                    var Dh = row.GetCell(8).ToString();//电话
                    var Dy = row.GetCell(9).ToString() == "" ? false : row.GetCell(9).ToString() == "否" ? false : true;//是否党员
                    var Zj = row.GetCell(10).ToString();//党组织
                    var Bz = row.GetCell(11).ToString();//备注
                    var Xz = row.GetCell(12).ToString();//性质
                    if (Sm == "" && Sfz == "") 
                        continue;
                    context = "{\"FGroupAffiliation\": \"" + Jt + "\",\"FhandedOverCompanies\": \"" + Qy + "\",\"FStreet\": \"" + Jd1 + "\",\"FCommunity\": \"" + Sq1 + "\",\"FName\": \"" + Sm + "\",\"FIDCards\": \"" + Sfz + "\",\"FSex\": \"" + Xb + "\",\"FPhone\": \"" + Dh + "\",\"FISParty\": \"" + Dy + "\",\"FPartyLocation\": \"" + Zj + "\",\"FRemark\": \"" + Bz + "\",\"FEnterpriseQuality\": \"" + Xz + "\"},";
                    stringBuilder.Append(context);
                }
                string last = "]}}";
                stringBuilder.Append(last);
                result = JObject.Parse(Client.Save("LQKJ_ArchiveTransfer", stringBuilder.ToString()));
                Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if (!(bool)Sueccess)
                {
                    var msg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                    return ApiResultHelper.Error(msg);
                }
                string Json = "{\"FileName\":\"" + FileName + "\",\"FormId\":\"LQKJ_ArchiveTransfer\",\"IsLast\":\"true\",\"InterId\":\"" + Id + "\",\"BillNO\":\"" + FBillNo + "\",\"SendByte\":\"" + Base64string + "\"}";
                result = JObject.Parse(Client.AttachmentUpload(Json));
                Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)
                {
                    Verification(Phone, $"【西部人力】您好！您已预约成功（{dateTime.ToString("MM")}月{dateTime.ToString("dd")}日{dateTime.ToString("HH")}点{dateTime.ToString("mm")}分）前到西部人力办理档案业务。请携带相关证件、材料按时到场。如未能到场请提前1天取消预约，超时未到场号源将自动失效，请重新预约。");
                    return ApiResultHelper.Success(JObject.Parse(Json)["FileName"].ToString(), "上传成功");
                }
                else 
                {
                    var msg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                    return ApiResultHelper.Error(msg);
                }
            }
        }
        /// <summary>
        /// 查阅预约
        /// </summary>
        /// <param name="parmeters"></param>
        /// <returns></returns>
        public ApiResult Select(string parmeters)
        {
            lock (lockObject)
            {
                var msg = JObject.Parse(parmeters);
                var FEntryID = msg["FEntryID"].ToString();
                msg.Remove("FEntryID");
                string sqlSelect = $"/*dialect*/ select format(FTIMEPERIOD,'yyyy-MM-dd')+' '+format(MAKETIME,'HH:mm') [Date],T2.FREMAINDERNUMBER from LQKJ_t_AppointmentRules T1,LQKJ_t_RULEINFORMATION T2 where T1.FID=T2.FID AND T2.FEntryID={FEntryID} and FDOCUMENTSTATUS = 'C' and T1.FFORBIDSTATUS='A'";
                DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                if (dataTable == null || dataTable.Rows.Count < 1)
                    return ApiResultHelper.Error("预约的时间有误");
                DateTime dateTime = Convert.ToDateTime(dataTable.Rows[0][0].ToString());
                if (dateTime < DateTime.Now)
                {
                    return ApiResultHelper.Error("预约时间已过");
                }
                msg["Model"]["FDatetime"] = dataTable.Rows[0][0].ToString();
                K3CloudApiClient Client = apiClient();
                var Count = msg["Model"]["FReservationQty"].ToString();
                var Type = msg["Model"]["FReferToType"].ToString();
                var FIDCARD = msg["Model"]["FIDCard"].ToString();

                int YuQicount = 0;//查询逾期次数
                //验证是否存在逾期限制和是否在黑名单中
                string YuQiYZStr = $"exec OverduetVerification @FIDCARD='{FIDCARD}'";
                DataTable YuqiyzData = obj.ExecuteDataTable(YuQiYZStr);
                if (YuqiyzData != null && YuqiyzData.Rows.Count > 0)
                {
                    if (YuqiyzData.Rows[0][0].ToString() == "1")
                        return ApiResultHelper.Error("您的逾期未办理次数过多，无法预约,如有问题请联系管理员");
                    else if (YuqiyzData.Rows[0][0].ToString() == "2")
                        return ApiResultHelper.Error($"您的逾期未办理次数过多，无法预约！请{YuqiyzData.Rows[0]["XzDate"].ToString()}后再预约");
                    else if (YuqiyzData.Rows[0][0].ToString() == "4" && YuqiyzData.Rows[0]["CYDATE"].ToString() != "")
                        return ApiResultHelper.Error($"您的已预约了{YuqiyzData.Rows[0]["CYDATE"].ToString()}，如需要修改预约时间，请取消后查询预约");
                    else if (YuqiyzData.Rows[0][0].ToString() == "3")
                        YuQicount = int.Parse(YuqiyzData.Rows[0]["YuQiCount"].ToString());
                }
                if (Type.Equals("0"))//个人查阅
                {
                    var FidCard = msg["Model"]["FIDCard"].ToString();
                    sqlSelect = $"select FID from T_DA_ArchiveAccess where FIDCARD='{FidCard}' and FREFERTOTYPE=0 and FDAIDCARD='{FidCard}'  and FDATETIME1='{dataTable.Rows[0][0].ToString()}'and FHANDLESTATES !='Q'and FFORBIDSTATUS='A' ";
                    if (obj.ExecuteDataTable(sqlSelect).Rows.Count > 0)
                    {
                        return ApiResultHelper.Error("您已经预约过，请勿重复预约！");
                    }
                    JObject.Parse(msg["Model"].ToString()).Remove("FDAName1");
                    JObject.Parse(msg["Model"].ToString()).Remove("FDAIDCard1");
                    msg["Model"]["FAppointedBy"] = msg["Model"]["FDAName"];
                    msg["Model"]["FIDCard"] = msg["Model"]["FDAIDCard"];
                    string YzFile = $"select FBillNo,FFileCabinetNumber,FPHONE From T_LQKJ_FilesManage where FIDCARD='{FidCard}' and FInvalidatedStatus='A'";
                    DataTable YzFileData = obj.ExecuteDataTable(YzFile);
                    if (YzFileData == null || YzFileData.Rows.Count < 1)
                    {
                        return ApiResultHelper.Error($"您所查阅的 {msg["Model"]["FDAName"].ToString()} 的档案不存在！！");
                    }
                    JObject innerObject = (JObject)msg["Model"];
                    // 添加新的键值对
                    innerObject.Add("FFileNumber ", YzFileData.Rows[0]["FBillNo"].ToString());
                    innerObject.Add("FFileCabinetNo ", YzFileData.Rows[0]["FFileCabinetNumber"].ToString());

                    msg["Model"]["FDAPhoneNumber"] = YzFileData.Rows[0]["FPHONE"].ToString();
                    msg["Model"]["FReservationQty"] = YuQicount;//逾期次数
                    //msg["Model"]["FIDCard"]=
                    var result = JObject.Parse(Client.Save("LQKJ_ArchiveAccess", msg.ToString()));
                    var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                    if ((bool)Sueccess)
                    {
                        sqlSelect = $"update LQKJ_t_RULEINFORMATION set FREMAINDERNUMBER=FREMAINDERNUMBER-1,FAPPOINTMENTQTY=FAPPOINTMENTQTY+1 where FEntryID ={FEntryID} ";
                        obj.Execute(sqlSelect);
                        string phone = msg["Model"]["FPhoneNumber"].ToString();
                        var Mes = "【西部人力】请您按预约时间到西部人力办理业务，如因未能按时抵达现场导致时间段内无法完成事项办理，请您重新预约。";
                        Verification(phone, Mes);
                        return ApiResultHelper.Success(msg, "操作成功");
                    }
                    else
                    {
                        var ErrorMsg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                        return ApiResultHelper.Error(ErrorMsg);
                    }
                }
                else//他人查阅
                {
                    if (Count.Equals("1"))//只有一份
                    {
                        var FidCard = msg["Model"]["FIDCard"].ToString();
                        var FidCard2 = msg["Model"]["FDAIDCard"].ToString();

                        string YzFile = $"select  FBillNo,FFileCabinetNumber,FPHONE From T_LQKJ_FilesManage where FIDCARD='{FidCard2}' and FInvalidatedStatus='A'";
                        DataTable YzFileData = obj.ExecuteDataTable(YzFile);
                        if (YzFileData == null || YzFileData.Rows.Count < 1)
                        {
                            return ApiResultHelper.Error($"您所查阅的 {msg["Model"]["FDAName"].ToString()} 的档案不存在！！");
                        }
                        JObject innerObject = (JObject)msg["Model"];
                        // 添加新的键值对
                        innerObject.Add("FFileNumber ", YzFileData.Rows[0]["FBillNo"].ToString());
                        innerObject.Add("FFileCabinetNo ", YzFileData.Rows[0]["FFileCabinetNumber"].ToString());
                        msg["Model"]["FDAPhoneNumber"] = YzFileData.Rows[0]["FPHONE"].ToString();
                        sqlSelect = $"select FID from T_DA_ArchiveAccess where FIDCARD='{FidCard}' and FREFERTOTYPE=1 and FDAIDCARD='{FidCard2}'  and FDATETIME1='{dataTable.Rows[0][0].ToString()}'and FHANDLESTATES !='Q'and FFORBIDSTATUS='A'";
                        if (obj.ExecuteDataTable(sqlSelect).Rows.Count > 0)
                        {
                            return ApiResultHelper.Error402("您已经预约过，请勿重复预约！");
                        }
                        JObject.Parse(msg["Model"].ToString()).Remove("FDAName1");
                        JObject.Parse(msg["Model"].ToString()).Remove("FDAIDCard1");
                        msg["Model"]["FReservationQty"] = YuQicount;//逾期次数
                        var result = JObject.Parse(Client.Save("LQKJ_ArchiveAccess", msg.ToString()));
                        var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                        if ((bool)Sueccess)
                        {
                            sqlSelect = $"update LQKJ_t_RULEINFORMATION set FREMAINDERNUMBER=FREMAINDERNUMBER-1,FAPPOINTMENTQTY=FAPPOINTMENTQTY+1 where FEntryID ={FEntryID} ";
                            obj.Execute(sqlSelect);
                            string phone = msg["Model"]["FPhoneNumber"].ToString();
                            var Mes = "【西部人力】请您按预约时间到西部人力办理业务，如因未能按时抵达现场导致时间段内无法完成事项办理，请您重新预约。";
                            Verification(phone, Mes);
                            return ApiResultHelper.Success(msg, "操作成功");
                        }
                        else
                        {
                            var ErrorMsg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                            return ApiResultHelper.Error(ErrorMsg);
                        }
                    }
                    else
                    {
                        var FidCard = msg["Model"]["FIDCard"].ToString();
                        var FidCard2 = msg["Model"]["FDAIDCard"].ToString();
                        var FidCard3 = msg["Model"]["FDAIDCard1"].ToString();

                        string YzFile1 = $"select FBillNo,FFileCabinetNumber,FPHONE From T_LQKJ_FilesManage where FIDCARD='{FidCard2}' and FInvalidatedStatus='A'";
                        string YzFile2 = $"select FBillNo,FFileCabinetNumber,FPHONE From T_LQKJ_FilesManage where FIDCARD='{FidCard3}' and FInvalidatedStatus='A'";
                        DataTable YzFileData1 = obj.ExecuteDataTable(YzFile1);
                        DataTable YzFileData2 = obj.ExecuteDataTable(YzFile2);
                        if (YzFileData1 == null || YzFileData2 == null|| YzFileData1.Rows.Count < 1|| YzFileData2.Rows.Count < 1)
                        {
                            return ApiResultHelper.Error($"您所查阅的的档案不存在！！");
                        }

                        var sqlSelect1 = $"select fid from T_DA_ArchiveAccess where FIDCARD='{FidCard}' and FREFERTOTYPE=1 and FDAIDCARD='{FidCard2}'  and FDATETIME1='{dataTable.Rows[0][0].ToString()}'and FHANDLESTATES !='Q'and FFORBIDSTATUS='A'";
                        var sqlSelect2 = $"select fid from T_DA_ArchiveAccess where FIDCARD='{FidCard}' and FREFERTOTYPE=1 and FDAIDCARD='{FidCard3}'  and FDATETIME1='{dataTable.Rows[0][0].ToString()}'and FHANDLESTATES !='Q'and FFORBIDSTATUS='A'";
                        if (obj.ExecuteDataTable(sqlSelect1).Rows.Count > 0 || obj.ExecuteDataTable(sqlSelect2).Rows.Count>0)
                        {
                            return ApiResultHelper.Error("您已经预约过，请勿重复预约！");
                        }
                        string FDAName1 = msg["Model"]["FDAName1"].ToString();
                        string FDAIDCard1 = msg["Model"]["FDAIDCard1"].ToString();
                        msg["Model"]["FReservationQty"] = YuQicount;//逾期次数
                        msg["Model"]["FFileCabinetNo"] = YzFileData1.Rows[0]["FFileCabinetNumber"].ToString();
                        msg["Model"]["FDAPhoneNumber"] = YzFileData1.Rows[0]["FPHONE"].ToString();

                        JObject.Parse(msg["Model"].ToString()).Remove("FDAName1");
                        JObject.Parse(msg["Model"].ToString()).Remove("FDAIDCard1");
                        JObject innerObject = (JObject)msg["Model"];
                        // 添加新的键值对
                        innerObject.Add("FFileNumber ", YzFileData1.Rows[0]["FBillNo"].ToString());
                        innerObject.Add("FFileCabinetNo ", YzFileData1.Rows[0]["FFileCabinetNumber"].ToString());
                        

                        var result = JObject.Parse(Client.Save("LQKJ_ArchiveAccess", msg.ToString()));
                        var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                        if (!(bool)Sueccess)//第一次新增
                        {
                            var ErrorMsg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                            return ApiResultHelper.Error(ErrorMsg);
                        }
                        msg["Model"]["FDAName"] = FDAName1;
                        msg["Model"]["FDAIDCard"] = FDAIDCard1;
                        msg["Model"]["FReservationQty"] = YuQicount;//逾期次数
                        msg["Model"]["FFileNumber"] = YzFileData2.Rows[0]["FBillNo"].ToString();
                        msg["Model"]["FFileCabinetNo"] = YzFileData2.Rows[0]["FFileCabinetNumber"].ToString();
                        msg["Model"]["FDAPhoneNumber"] = YzFileData2.Rows[0]["FPHONE"].ToString();

                        result = JObject.Parse(Client.Save("LQKJ_ArchiveAccess", msg.ToString()));
                        Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                        if ((bool)Sueccess)//第二次新增
                        {
                            sqlSelect = $"update LQKJ_t_RULEINFORMATION set FREMAINDERNUMBER=FREMAINDERNUMBER-1,FAPPOINTMENTQTY=FAPPOINTMENTQTY+1 where FEntryID ={FEntryID} ";
                            obj.Execute(sqlSelect);
                            string phone = msg["Model"]["FPhoneNumber"].ToString();
                            var Mes = "【西部人力】请您按预约时间到西部人力办理业务，如因未能按时抵达现场导致时间段内无法完成事项办理，请您重新预约。";
                            Verification(phone, Mes);
                            return ApiResultHelper.Success(msg, "操作成功");
                        }
                        else
                        {
                            var ErrorMsg = (string)result["Result"]["ResponseStatus"]["Errors"][0]["Message"];
                            return ApiResultHelper.Error(ErrorMsg);
                        }
                    }

                }
            }
        }
       /// <summary>
       /// 发送验证码
       /// </summary>
       /// <param name="Phone"></param>
       /// <param name="msg"></param>
       /// <returns></returns>
        public bool Verification(string Phone, string msg)
        {
            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($"{msg}", 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":
                    {
                        return true;
                    }
            }
            return false;
        }
        /// <summary>
        /// 存放查询
        /// </summary>
        /// <param name="idCard"></param>
        /// <returns></returns>
        public ApiResult Deposit(string idCard)
        {
            string sql = $"select FBillNo,FFileCabinetNumber from T_LQKJ_FilesManage where FIDCARD='{idCard}'";
            var result = obj.ExecuteDataTable(sql);
            if (result.Rows.Count > 0)
            {
                return ApiResultHelper.Success(result, "该档案已存放于西部人力，如有需要查阅，请于“档案查阅”界面进行预约。");
            }
            else
            {
                return ApiResultHelper.Error("未查询到该人员信息，请核对信息输入是否正确（请勿输入空格），或与原档案保存单位核实情况。");
            }
        }
        /// <summary>
        /// 现场查阅状态
        /// </summary>
        /// <param name="parme"></param>
        /// <returns></returns>
        public ApiResult StatusQuery(string  parme)
        {
            var msg = JObject.Parse(parme);
            string Type = msg["Type"]?.ToString();
            string YqType = msg["YqType"]?.ToString();
            if (Type == "0")
            {
                //判断档案是否存在
                string idCard = msg["FIDCard"]?.ToString();
                string sql = $"/*dialect*/select FBillNo,FFileCabinetNumber from T_LQKJ_FilesManage where FIDCARD='{idCard}'";
                DataSet Dts = (DataSet)obj.ExecutDataSet(sql).data;
                if (Dts == null || Dts.Tables == null || Dts.Tables[0].Rows.Count < 1)
                {
                    return ApiResultHelper.Error("所查询的档案不存在！！");
                }
                string YYSql = $"/*dialect*/select fid,FHANDLESTATES from T_DA_ArchiveAccess where left(FDATETIME1,10)>=format(GETDATE(),'yyyy-MM-dd')and FReferToType=0 and FIDCARD='{idCard}'and FFORBIDSTATUS='A' and FHANDLESTATES!='Q' ";
                DataSet Dts2 = (DataSet)obj.ExecutDataSet( YYSql).data;
                if (Dts2 == null || Dts2.Tables == null || Dts2.Tables[0].Rows.Count < 1)
                {
                    return ApiResultHelper.Error402("无预约信息，请点击添加现场查阅记录按钮后，查看档案编号和档案柜编号！！");//未预约
                }
                else
                {
                    var result = new
                    {
                        FBillNo = Dts.Tables[0].Rows[0]["FBillNo"].ToString(),
                        FFileCabinetNumber = Dts.Tables[0].Rows[0]["FFileCabinetNumber"].ToString(),
                    };
                    return ApiResultHelper.Success(result,"查询成功");//未预约
                }
            }
            else
            {
                string FIDCard = msg["FIDCard"].ToString();
                string FDAIDCard = msg["FDAIDCard"].ToString();
                string sql = $"/*dialect*/select FBillNo,FFileCabinetNumber from T_LQKJ_FilesManage where FIDCARD='{FDAIDCard}'";
                DataSet Dts = (DataSet)obj.ExecutDataSet(sql).data;
                if (Dts == null || Dts.Tables == null || Dts.Tables[0].Rows.Count < 1)
                {
                    return ApiResultHelper.Error("所查询的档案不存在！！");
                }
                string YYSql = $"/*dialect*/select fid,FHANDLESTATES from T_DA_ArchiveAccess where left(FDATETIME1,10)>=format(GETDATE(),'yyyy-MM-dd')and FReferToType=1 and FIDCARD='{FIDCard}'and FDAIDCARD='{FDAIDCard}' and FFORBIDSTATUS='A' and FHANDLESTATES!='Q' ";
                DataSet Dts2 = (DataSet)obj.ExecutDataSet(YYSql).data;
                if (Dts2 == null || Dts2.Tables == null || Dts2.Tables[0].Rows.Count < 1)
                {
                    return ApiResultHelper.Error402("无预约信息，点击添加现场查阅记录按钮后，查看档案编号和档案柜编号！！");
                }
                else
                {
                    var result = new
                    {
                        FBillNo = Dts.Tables[0].Rows[0]["FBillNo"].ToString(),
                        FFileCabinetNumber = Dts.Tables[0].Rows[0]["FFileCabinetNumber"].ToString(),
                    };
                    return ApiResultHelper.Success(result, "查询成功");//未预约
                }
            }
        }
        /// <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>
        /// 预约配置
        /// </summary>
        /// <returns></returns>
        public ApiResult AppointmentConfig()
        {
            HttpRequest request = HttpContext.Current.Request;
            var FLOCATIONPAGECOM = request["FLOCATIONPAGECOM"];//页面类型
            string Sqlstr01 = $"select DISTINCT FRONTENDFIELDS from T_DA_AppointmentConfig where FLOCATIONPAGECOM='{FLOCATIONPAGECOM}' and FDOCUMENTSTATUS='C'and F_LQKJ_FORBIDSTATUS='A'";
            string Sqlstr02 = $"select * from T_DA_AppointmentConfig where FLOCATIONPAGECOM='{FLOCATIONPAGECOM}' and FDOCUMENTSTATUS='C'and F_LQKJ_FORBIDSTATUS='A'";
             DataTable dt01= obj.ExecuteDataTable(Sqlstr01);
             DataTable dt02= obj.ExecuteDataTable(Sqlstr02);
            if (dt01==null||dt01.Rows.Count < 1)
                return ApiResultHelper.Error("查询失败,无数据");
            var datalist2 = dt02.AsEnumerable().Select(e => new
            {
                FRONTENDFIELDS = e.Field<string>("FRONTENDFIELDS"),
                FCONTENT = e.Field<string>("FCONTENT"),
                FILENAME = obj.GetFilename(e.Field<string>("FATTACHMENT"))[0],
                FILEPATH = obj.GetFilename(e.Field<string>("FATTACHMENT"))[1],
                ImagePath = string.Format(e.Field<string>("FIMAGESYTP").Trim() != ""? string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FIMAGESYTP"), obj.UserToken()) :"")
            }) ;
            var dataList = dt01.AsEnumerable().Select(e =>
            {
                var fieldValue = e.Field<string>("FRONTENDFIELDS");
                dynamic result = new ExpandoObject();
                ((IDictionary<string, object>)result)[fieldValue] = datalist2.Where(m => m.FRONTENDFIELDS == fieldValue).ToList();
                return result;
            });
            return ApiResultHelper.Success(dataList, "查询成功");
        }
        /// <summary>
        /// 查询我的预约
        /// </summary>
        /// <param name="Type">0查询预约；1移交预约</param>
        /// <returns></returns>
        public SQLResult SelectYuYue(string Phone,string Type,int pageSize, int pageIndex)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sql;
                if (Type == "0")//查询预约--and CONVERT(datetime, LEFT(FDATETIME1, 16))>GETDATE()
                {
                    sql = $"/*dialect*/ select FID, FHANDLESTATES,LEFT(FDATETIME1, 10)as Date, SUBSTRING(FDATETIME1, 12, 5) AS MinDatetime, case DATEPART(WEEKDAY, CONVERT(datetime, LEFT(FDATETIME1, 16)))WHEN 1 THEN '周日'WHEN 2 THEN '周一'  WHEN 3 THEN '周二'   WHEN 4 THEN '周三'   WHEN 5 THEN '周四'  WHEN 6 THEN '周五'   WHEN 7 THEN '周六'  END AS WeekdayName From T_DA_ArchiveAccess where FPHONENUMBER='{Phone}' and FFORBIDSTATUS='A' order by Date desc,MinDatetime Desc";
                }
                else//移交预约--and CONVERT(datetime, LEFT(FDATETIME1, 16))>GETDATE()
                {
                    sql = $"/*dialect*/ SELECT FID, FHANDLESTATES,LEFT(FDATETIME1, 10)as Date, SUBSTRING(FDATETIME1, 12, 5) AS MinDatetime, case DATEPART(WEEKDAY, CONVERT(datetime, LEFT(FDATETIME1, 16)))WHEN 1 THEN '周日'WHEN 2 THEN '周一'  WHEN 3 THEN '周二'   WHEN 4 THEN '周三'   WHEN 5 THEN '周四'  WHEN 6 THEN '周五'   WHEN 7 THEN '周六'  END AS WeekdayName  From T_DA_ArchiveTransfer where FPHONENUMBER='{Phone}' and FFORBIDSTATUS='A' order by Date desc,MinDatetime Desc";
                }
                DataTable dt01 = obj.ExecuteDataTable(sql);
                if (dt01==null||dt01.Rows.Count < 1)
                {
                    sqlResult.msg = "无该手机号数据！";
                    sqlResult.code = "200";
                    sqlResult.data = null;
                }
                else
                {
                    var count = (pageIndex - 1) * pageSize;
                    int Rowcount = dt01.Rows.Count;
                    var DataRows = dt01.AsEnumerable().Skip(count).Take(pageSize).ToArray();
                    DataTable dataTable = ConvertToDataTable(DataRows);//将DataRow[]转换为DataTable
                    if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                    {
                        sqlResult.msg = "无数据！";
                        sqlResult.total = Rowcount;
                        sqlResult.code = "200";
                        sqlResult.data = null;
                    }
                    else
                    {
                        var dataList = dataTable.AsEnumerable().Select(e => new
                        {
                            FID = e.Field<Int64>("FID"),
                            FHANDLESTATES = string.Format(FHANDLESTATESState(e.Field<string>("FHANDLESTATES"), e.Field<string>("Date")+" "+ e.Field<string>("MinDatetime"))),
                            WeekdayName = e.Field<string>("WeekdayName"),
                            Date = e.Field<string>("Date"),
                            MinDatetime = e.Field<string>("MinDatetime"),
                        }).OrderBy(s => s.FHANDLESTATES != "未办理").ThenBy(s => s.FHANDLESTATES);
                        sqlResult.msg = "获取数据成功！";
                        sqlResult.total = Rowcount;
                        sqlResult.code = "200";
                        sqlResult.data = dataList;// 将指定的字符串排在前面 // 按照默认顺序排序/*.OrderBy(s=>s.FHANDLESTATES,new CustomStringComparerss("未办理"))*/;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:SelectYuYue", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "服务器错误";
            }
            return sqlResult;
        }
        /// <summary>
        /// 判断预约状态
        /// </summary>
        /// <param name="FHANDLESTATES"></param>
        /// <param name="Datestr"></param>
        /// <returns></returns>
        private string FHANDLESTATESState(string FHANDLESTATES, string Datestr)
        {
            switch (FHANDLESTATES)
            {
                case "Q":
                    return  "已取消";
                case "N":
                    DateTime YuYueDate;
                    DateTime.TryParse(Datestr, out YuYueDate);
                    if (YuYueDate > DateTime.Now)
                        return "未办理";
                    else
                        return "已逾期";
                case "Y":
                    return  "已办理";
                default:
                    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>
        /// <param name="Fid">预约id</param>
        /// <param name="Type">取消类型</param>
        /// <returns></returns>
        public ApiResult CancelReservation(string Fid, string Type)
        {
            lock (lockObject)
            {
                try
                {
                    string sql;
                    if (Type == "YJYY")
                    {
                        sql = $"select*from T_DA_ArchiveTransfer where FID='{Fid}' and FFORBIDSTATUS='A'";
                    }
                    else if(Type == "CYYY")
                    {
                        sql = $"select*from T_DA_ArchiveAccess where FID='{Fid}' and FFORBIDSTATUS='A'";
                    }
                    else
                    {
                        return ApiResultHelper.Error("提交的信息有误");
                    }
                    DataTable Dt01 = obj.ExecuteDataTable(sql);
                    DateTime YydateTime;
                    if(Dt01!=null&&Dt01.Rows.Count > 0)
                    {
                        if (Dt01.Rows[0]["FHANDLESTATES"]?.ToString() == "Q")
                        {
                            return ApiResultHelper.Error("您已取消预约，请勿重复操作");
                        }
                        else if (Dt01.Rows[0]["FHANDLESTATES"]?.ToString() == "Y")
                        {
                            return ApiResultHelper.Error("业务已办理，无法取消");
                        }
                        else if (DateTime.TryParse(Dt01.Rows[0]["FDATETIME1"].ToString(), out YydateTime)&& YydateTime<DateTime.Now)
                        {
                            return ApiResultHelper.Error("您已逾期，无法取消");
                        }
                        else if (DateTime.TryParse(Dt01.Rows[0]["FDATETIME1"].ToString(), out YydateTime) && YydateTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
                        {
                            return ApiResultHelper.Error("已过取消时间，如需取消请联系工作人员！");
                        }
                    }
                    else
                    {
                        return ApiResultHelper.Error("取消失败，请联系管理员");
                    }
                    string SqlUpdate = $"exec CancelAppointment @Fid={Fid},@Type='{Type}' ";
                    if (obj.Execute(SqlUpdate) > 0)
                        return ApiResultHelper.Success(null, "取消成功");
                    else
                        return ApiResultHelper.Error("取消预约失败未找到该次预约记录");
                }
                catch (Exception ex)
                {
                    Logger.Error("ActionName:CancelReservation", ex.Message, ex);
                    return ApiResultHelper.Error("服务器错误，请联系管理员");
                }
            }
        }
        /// <summary>
        /// 现场查阅接口
        /// </summary>
        /// <returns></returns>
        public ApiResult XcSelect(string parme)
        {
            var JSON = JObject.Parse(parme);
            string FIDCARD = JSON["FIDCard"].ToString();
            string Type = JSON["Type"].ToString();
            string YqType = JSON["YqType"].ToString();

            var parmeters = "{\"IsDeleteEntry\":\"false\",\"Model\":{\"FAppointedBy\":\"\",\"FIDCard\":\"\",\"FPhoneNumber\":\"\",\"FDatetime\":\"\",\"FReservationQty\":0,\"FReferToType\":\"1\",\"FDAName\":\"\",\"FDAIDCard\":\"\",\"FDAPhoneNumber\":\"\",\"FNoAppointment\":\"true\"}}";
            var msg = JObject.Parse(parmeters);
            msg["Model"]["FDatetime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            int YuQicount = 0;//查询逾期次数
            K3CloudApiClient Client = apiClient();
            //验证是否存在逾期限制和是否在黑名单中
            if (YqType == "1")
            {
                string YuQiYZStr = $"exec OverduetVerification @FIDCARD='{FIDCARD}'";
                DataTable YuqiyzData = obj.ExecuteDataTable(YuQiYZStr);
                if (YuqiyzData != null && YuqiyzData.Rows.Count > 0)
                {
                    if (YuqiyzData.Rows[0][0].ToString() == "1")
                    {
                        return ApiResultHelper.Error402("该用户已加入黑名单,是否继续查询");
                    }
                    else if (YuqiyzData.Rows[0][0].ToString() == "2")
                    {
                        return ApiResultHelper.Error402($"逾期未办理次数过多！限制到期时间未{YuqiyzData.Rows[0]["XzDate"].ToString()}，是否继续查询？");
                    }
                    else if (YuqiyzData.Rows[0][0].ToString() == "4" && YuqiyzData.Rows[0]["CYDATE"].ToString() != "")
                    {
                        return ApiResultHelper.Error402($"已预约了{YuqiyzData.Rows[0]["CYDATE"].ToString()}，是否继续查询");
                    }
                    else if (YuqiyzData.Rows[0][0].ToString() == "3")
                        YuQicount = int.Parse(YuqiyzData.Rows[0]["YuQiCount"].ToString());
                }
            }
            if (Type == "0")
            {
                string YzFile = $"select FBillNo,FFileCabinetNumber,FNAME,FPHONE,FIDCARD From T_LQKJ_FilesManage where FIDCARD='{FIDCARD}' and FInvalidatedStatus='A'";
                DataTable YzFileData = obj.ExecuteDataTable(YzFile);
                if (YzFileData == null || YzFileData.Rows.Count < 1)
                {
                    return ApiResultHelper.Error("档案不存在");
                }
                JObject innerObject = (JObject)msg["Model"];
                // 添加新的键值对
                innerObject.Add("FFileNumber ", YzFileData.Rows[0]["FBillNo"].ToString());
                innerObject.Add("FFileCabinetNo ", YzFileData.Rows[0]["FFileCabinetNumber"].ToString());
                innerObject.Add("FHANDLESTATES ", "Y");

                msg["Model"]["FDAPhoneNumber"] = YzFileData.Rows[0]["FPHONE"].ToString();
                msg["Model"]["FAppointedBy"] = JSON["FAppointedBy"].ToString();//姓名
                msg["Model"]["FDAName"] = YzFileData.Rows[0]["FNAME"].ToString();//姓名
                msg["Model"]["FIDCard"] = YzFileData.Rows[0]["FIDCard"].ToString();//身份证
                msg["Model"]["FDAIDCard"] = YzFileData.Rows[0]["FIDCard"].ToString();//身份证
                msg["Model"]["FReservationQty"] = YuQicount;//逾期次数                                       
                msg["Model"]["FReferToType"] = "0";//逾期次数                                       
                var result = JObject.Parse(Client.Save("LQKJ_ArchiveAccess", msg.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)
                {
                    var results = new
                    {
                        FBillNo = YzFileData.Rows[0]["FBillNo"].ToString(),
                        FFileCabinetNumber = YzFileData.Rows[0]["FFileCabinetNumber"].ToString(),
                    };
                    return ApiResultHelper.Success(results, "查阅成功");
                }
                else
                {
                    return ApiResultHelper.Error("查阅失败联系管理员");
                }
            }
            else
            {
                string YzFile = $"select FBillNo,FFileCabinetNumber,FNAME,FPHONE,FIDCARD From T_LQKJ_FilesManage where FIDCARD='{JSON["FDAIDCard"]?.ToString()}' and FInvalidatedStatus='A'";
                DataTable YzFileData = obj.ExecuteDataTable(YzFile);
                if (YzFileData == null || YzFileData.Rows.Count < 1)
                {
                    return ApiResultHelper.Error("档案不存在");
                }
                JObject innerObject = (JObject)msg["Model"];
                // 添加新的键值对
                innerObject.Add("FFileNumber ", YzFileData.Rows[0]["FBillNo"].ToString());
                innerObject.Add("FFileCabinetNo ", YzFileData.Rows[0]["FFileCabinetNumber"].ToString());
                innerObject.Add("FHANDLESTATES ", "Y");
                msg["Model"]["FDAPhoneNumber"] = YzFileData.Rows[0]["FPHONE"].ToString();
                msg["Model"]["FAppointedBy"] = JSON["FAppointedBy"]?.ToString();//姓名
                msg["Model"]["FDAName"] = YzFileData.Rows[0]["FNAME"]?.ToString();//姓名
                msg["Model"]["FIDCard"] = JSON["FIDCard"]?.ToString();//身份证
                msg["Model"]["FDAIDCard"] = YzFileData.Rows[0]["FIDCard"].ToString();//身份证

                msg["Model"]["FReservationQty"] = YuQicount;//逾期次数                                       
                var result = JObject.Parse(Client.Save("LQKJ_ArchiveAccess", msg.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)
                {
                    var results = new
                    {
                        FBillNo = YzFileData.Rows[0]["FBillNo"].ToString(),
                        FFileCabinetNumber = YzFileData.Rows[0]["FFileCabinetNumber"].ToString(),
                    };
                    return ApiResultHelper.Success(results, "查阅成功");
                }
                else
                {
                    return ApiResultHelper.Error("查阅失败联系管理员");
                }
            }
        }
        /// <summary>
        /// 微信公众号消息推送
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        public ApiResult PushMessaging(string Code,string FDatetime,string YYType)
        {
            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();
            HttpResponseMessage response = httpClient.GetAsync(url).Result;
            string openId = "";
            if (response.IsSuccessStatusCode)//获取成功
            {
                result = response.Content.ReadAsStringAsync().Result;
                JObject Json = JObject.Parse(result);
                //拉取用户信息，获取openid
                openId = Json["openid"]?.ToString();
                if (openId == null)
                {
                    return ApiResultHelper.Error($"无法获取openid！！公众号消息推送失败");
                }
            }
            try
            {
                if (openId != "")
                {
                    string url2 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "";
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url2);
                    request.Method = "GET";
                    request.ContentType = "textml;charset=UTF-8";
                    string jsonData = "";
                    using (HttpWebResponse response1 = (HttpWebResponse)request.GetResponse())
                    {
                        using (StreamReader sr = new StreamReader(response1.GetResponseStream(), Encoding.UTF8))
                        {
                            jsonData = sr.ReadToEnd();
                            sr.Close();
                        }
                        response1.Close();
                    }
                    if (jsonData != "")
                    {
                        string jsonString = jsonData;
                        JObject json = JObject.Parse(jsonString);
                        string access_token = json["access_token"].ToString();

                        string str = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

                        //json参数，传入对应的值                                                                           
                        string jsonParam = "{\"touser\": \"" + openId + "\",\"template_id\": \"yBrQVyKvoy4AnfvOIXFSPFbekQgClbHhaPHHNQKvltM\",\"data\": {\"phrase17\": { \"value\": \"" + YYType + "\"}," +
                                //"\"keyword1\": { \"value\": \""+ FDatetime + "\"}," +
                                "\"time23\": { \"value\": \""+ FDatetime + "\"}}}";

                        HttpWebRequest requests = (HttpWebRequest)WebRequest.Create(str);
                        requests.Method = "POST";
                        requests.Timeout = 20000;
                        requests.ContentType = "application/json;charset=UTF-8";
                        byte[] byteData = Encoding.UTF8.GetBytes(jsonParam);
                        int length = byteData.Length;
                        requests.ContentLength = length;

                        using (Stream writer = requests.GetRequestStream())
                        {
                            writer.Write(byteData, 0, length);
                            writer.Close();
                        }

                        string jsonStrings = string.Empty;
                        using (HttpWebResponse responses = (HttpWebResponse)requests.GetResponse())
                        {
                            using (Stream streams = responses.GetResponseStream())
                            {
                                using (StreamReader readers = new StreamReader(streams, System.Text.Encoding.UTF8))
                                {
                                    jsonStrings = readers.ReadToEnd();
                                    responses.Close();
                                    streams.Close();
                                    readers.Close();
                                }
                            }
                        }
                    }
                }
                return ApiResultHelper.Success(null,"推送成功！！");
            }
            catch (Exception)
            {

                return ApiResultHelper.Error($"公众号消息推送失败，请注意查收短信！");

            }
        }
       
    }
}
