using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Util;
using Kingdee.BOS.DataEntity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json.Linq;
using System.Data;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using System.Net;
using System.IO;

namespace LQKJ.DANGAN.ReportPlugIN
{
    [HotUpdate, Description("动态表单,现场查阅")]//暂未使用
    public class OnSiteInspection: AbstractDynamicFormPlugIn
    {
        public bool Zt=false;
        public bool Yq = true;
        public bool Zt1=false;
        public bool Yq1 = true;
        static string dbid = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["Dbid"].Value;
        static string username = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["username"].Value;
        static string password = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["password"].Value;
        static string url = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["url"].Value;
        static K3CloudApiClient Client = new K3CloudApiClient(url);
        static string loginResult = Client.ValidateLogin(dbid, username, password, 2052);
        static int resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
        public override void OnLoad(EventArgs e)
        {
            //this.FBillNo = this.View.OpenParameter.GetCustomParameter("FBillNo").ToString();
            
        }
        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);
            if (e.Key.ToUpper().Equals("F_LQKJ_SelectButton".ToUpper()))
            {
                Zt = false;
                this.View.Model.SetValue("FBillNo", "");
                this.View.Model.SetValue("FFileCabinetNumber", "");
                Deposit();
            }
            else if (e.Key.ToUpper().Equals("F_LQKJ_InsertBtn".ToUpper()))
            {
                InsertBtn();
            }else if (e.Key.ToUpper().Equals("F_LQKJ_SelectButton1".ToUpper()))
            {
                Zt1 = false;
                this.View.Model.SetValue("F_LQKJ_BillNo", "");
                this.View.Model.SetValue("F_LQKJ_FileCabinetNumber", "");
                OthersDeposit();
            }else if (e.Key.ToUpper().Equals("F_LQKJ_InsertBtn1".ToUpper()))
            {
                OthersInsertBtn();
            }else if (e.Key.ToUpper().Equals("F_LQKJ_Button".ToUpper()))
            {
                Zt = false;
                ReadingIDcard(0);//0本人，1他人查阅档案人，2他人查阅档案人
            }else if (e.Key.ToUpper().Equals("F_LQKJ_Button1".ToUpper()))
            {
                Zt1 = false;
                ReadingIDcard(1);//0本人，1他人查阅档案人，2他人查阅档案人
            }else if (e.Key.ToUpper().Equals("F_LQKJ_Button11".ToUpper()))
            {
                Zt1 = false;
                ReadingIDcard(2);//0本人，1他人查阅档案人，2他人查阅档案人
            }

        }

        public void ReadingIDcard(int Type)
        {
            string url1 = "http://127.0.0.1:18889/api/connect";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
            request.Method = "POST";
            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);
                if (json["resultFlag"]?.ToString() == "1")
                {
                    this.View.ShowErrMessage("连接失败!请检查刷卡机是否连接");
                    return;
                }
            }
            string url2 = "http://127.0.0.1:18889/api/readCard";
            HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(url2);
            request2.Method = "POST";
            request2.ContentType = "textml;charset=UTF-8";
            string jsonData2 = "";
            using (HttpWebResponse response1 = (HttpWebResponse)request2.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response1.GetResponseStream(), Encoding.UTF8))
                {
                    jsonData2 = sr.ReadToEnd();
                    sr.Close();
                }
                response1.Close();
            }
            if (jsonData2 != "")
            {
                string jsonString2 = jsonData2;
                JObject json2 = JObject.Parse(jsonString2);
                if (json2["resultFlag"]?.ToString() == "-1")
                {
                    this.View.ShowErrMessage("获取身份证信息失败！！");
                    return;
                }
                else
                {
                    if (Type == 0)
                    {
                        this.View.Model.SetValue("FName", json2["resultContent"]["partyName"]?.ToString());
                        this.View.Model.SetValue("F_LQKJ_IdCard", json2["resultContent"]["certNumber"]?.ToString());
                    }else if (Type == 1)
                    {
                        this.View.Model.SetValue("F_LQKJ_Name", json2["resultContent"]["partyName"]?.ToString());
                        this.View.Model.SetValue("F_LQKJ_IdCard1", json2["resultContent"]["certNumber"]?.ToString());
                    }
                    else
                    {
                        this.View.Model.SetValue("F_LQKJ_Name1", json2["resultContent"]["partyName"]?.ToString());
                        this.View.Model.SetValue("F_LQKJ_IdCard11", json2["resultContent"]["certNumber"]?.ToString());
                    }
                    
                }
            }
        }

        private void OthersDeposit()
        {
            //判断档案是否存在
            string idCard1 = this.View.Model.GetValue("F_LQKJ_IdCard1")?.ToString();
            string idCard2 = this.View.Model.GetValue("F_LQKJ_IdCard11")?.ToString();
            string name1= this.View.Model.GetValue("F_LQKJ_Name")?.ToString();
            string name2= this.View.Model.GetValue("F_LQKJ_Name1")?.ToString();
            if (string.IsNullOrWhiteSpace(idCard1)||string.IsNullOrWhiteSpace(idCard2))
            {
                this.View.ShowErrMessage("身份证号不能为空！！");
                return;
            }
            string sql = $"/*dialect*/select FBillNo,FFileCabinetNumber from T_LQKJ_FilesManage where FIDCARD='{idCard2}'";
            DataSet Dts = DBServiceHelper.ExecuteDataSet(this.Context, sql);
            if (Dts == null || Dts.Tables == null || Dts.Tables[0].Rows.Count < 1)
            {
                this.View.ShowErrMessage("所查询的档案不存在！！");
                return;
            }
            string YYSql = $"/*dialect*/select fid,FHANDLESTATES from T_DA_ArchiveAccess where left(FDATETIME1,10)>=format(GETDATE(),'yyyy-MM-dd')and FReferToType=1 and FIDCARD='{idCard1.Trim()}'and FDAIDCARD='{idCard2.Trim()}' and FFORBIDSTATUS='A' and FHANDLESTATES!='Q' ";
            DataSet Dts2 = DBServiceHelper.ExecuteDataSet(this.Context, YYSql);
            if (Dts2 == null || Dts2.Tables == null || Dts2.Tables[0].Rows.Count < 1)
            {
                this.View.ShowErrMessage("无预约信息，点击添加现场查阅记录按钮后，查看档案编号和档案柜编号！！");
                Zt1 = true;
                return;
            }
            else
            {
                this.View.Model.SetValue("F_LQKJ_BillNo", Dts.Tables[0].Rows[0]["FBillNo"].ToString());
                this.View.Model.SetValue("F_LQKJ_FileCabinetNumber", Dts.Tables[0].Rows[0]["FFileCabinetNumber"].ToString());
            }
        }

        /// <summary>
        /// 现场查阅判断
        /// </summary>
        private void OthersInsertBtn()
        {
            if (resultType != 1)
            {
                throw new Exception("登陆失败");
            }
            if (Zt1)
            {
                string idCard1 = this.View.Model.GetValue("F_LQKJ_IdCard1")?.ToString();
                string idCard2 = this.View.Model.GetValue("F_LQKJ_IdCard11")?.ToString();
                string name1 = this.View.Model.GetValue("F_LQKJ_Name")?.ToString();
                string name2 = this.View.Model.GetValue("F_LQKJ_Name1")?.ToString();
                if (string.IsNullOrEmpty(idCard1) || string.IsNullOrEmpty(idCard2))
                {
                    this.View.ShowErrMessage("身份证号不能为空！！");
                    return;
                }
                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;//查询逾期次数
                //验证是否存在逾期限制和是否在黑名单中
                if (Yq1)
                {
                    string YuQiYZStr = $"exec OverduetVerification @FIDCARD='{idCard1}'";
                    DataTable YuqiyzData = DBServiceHelper.ExecuteDataSet(this.Context, YuQiYZStr).Tables[0];
                    if (YuqiyzData != null && YuqiyzData.Rows.Count > 0)
                    {
                        if (YuqiyzData.Rows[0][0].ToString() == "1")
                        {
                            this.View.ShowErrMessage("该用户已加入黑名单,如需继续查询，再次点击查询按钮！");
                            Yq1 = false;
                            return;
                        }
                        else if (YuqiyzData.Rows[0][0].ToString() == "2")
                        {
                            this.View.ShowErrMessage($"逾期未办理次数过多！限制到期时间未{YuqiyzData.Rows[0]["XzDate"].ToString()}，如需继续查询，再次点击查询按钮！");
                            Yq1 = false;
                            return;
                        }
                        else if (YuqiyzData.Rows[0][0].ToString() == "4" && YuqiyzData.Rows[0]["CYDATE"].ToString() != "")
                        {
                            this.View.ShowErrMessage($"已预约了{YuqiyzData.Rows[0]["CYDATE"].ToString()}，如需继续查询，再次点击查询按钮！");
                            Yq1 = false;
                            return;
                        }
                        else if (YuqiyzData.Rows[0][0].ToString() == "3")
                            YuQicount = int.Parse(YuqiyzData.Rows[0]["YuQiCount"].ToString());
                    }
                }
                string YzFile = $"select FBillNo,FFileCabinetNumber,FNAME,FPHONE,FIDCARD From T_LQKJ_FilesManage where FIDCARD='{idCard2}' and FInvalidatedStatus='A'";
                DataTable YzFileData = DBServiceHelper.ExecuteDataSet(this.Context, YzFile).Tables[0];
                if (YzFileData == null || YzFileData.Rows.Count < 1)
                {
                    this.View.ShowErrMessage($"您所查阅的 {msg["Model"]["FDAName"].ToString()} 的档案不存在！！");
                    return;
                }
                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"] = name1;//查阅人姓名
                msg["Model"]["FDAName"] = YzFileData.Rows[0]["FNAME"].ToString();//档案人姓名
                msg["Model"]["FIDCard"] = idCard1;//查阅人身份证
                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)
                {
                    this.View.ShowMessage("现场查阅成功");
                    Zt1 = false;
                    Yq1 = true;
                    this.View.Model.SetValue("F_LQKJ_BillNo", YzFileData.Rows[0]["FBillNo"].ToString());
                    this.View.Model.SetValue("F_LQKJ_FileCabinetNumber", YzFileData.Rows[0]["FFileCabinetNumber"].ToString());
                }
                else
                {
                    this.View.ShowErrMessage("现场查阅失败，请联系管理员");
                    Zt1 = false;
                    Yq1 = true;
                }
            }
            else
            {
                this.View.ShowErrMessage("查询的身份信息不存在线上预约的情况下才允许记录");
            }
        }

        private void InsertBtn()
        {
            if (resultType != 1)
            {
                throw new Exception("登陆失败");
            }
            if (Zt)
            {
                if (string.IsNullOrWhiteSpace(this.View.Model.GetValue("F_LQKJ_IdCard")?.ToString()))
                {
                    this.View.ShowErrMessage("身份证号不能为空！");
                    return;
                }
                var parmeters = "{\"IsDeleteEntry\":\"false\",\"Model\":{\"FAppointedBy\":\"\",\"FIDCard\":\"\",\"FPhoneNumber\":\"\",\"FDatetime\":\"\",\"FReservationQty\":0,\"FReferToType\":\"0\",\"FDAName\":\"\",\"FDAIDCard\":\"\",\"FDAPhoneNumber\":\"\",\"FNoAppointment\":\"true\"}}";
                var msg = JObject.Parse(parmeters);
                msg["Model"]["FDatetime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                var FIDCARD = this.View.Model.GetValue("F_LQKJ_IdCard")?.ToString();
                int YuQicount = 0;//查询逾期次数
                //验证是否存在逾期限制和是否在黑名单中
                if (Yq)
                {
                    string YuQiYZStr = $"exec OverduetVerification @FIDCARD='{FIDCARD}'";
                    DataTable YuqiyzData = DBServiceHelper.ExecuteDataSet(this.Context,YuQiYZStr).Tables[0];
                    if (YuqiyzData != null && YuqiyzData.Rows.Count > 0)
                    {
                        if (YuqiyzData.Rows[0][0].ToString() == "1")
                        {
                            this.View.ShowErrMessage("该用户已加入黑名单,是否继续查询");
                            Yq = false;
                            return;
                        }
                        else if (YuqiyzData.Rows[0][0].ToString() == "2")
                        {
                            this.View.ShowErrMessage($"逾期未办理次数过多！限制到期时间未{YuqiyzData.Rows[0]["XzDate"].ToString()}，是否继续查询？");
                            Yq = false;
                            return;
                        }
                        else if (YuqiyzData.Rows[0][0].ToString() == "4" && YuqiyzData.Rows[0]["CYDATE"].ToString() != "")
                        {
                            this.View.ShowErrMessage($"已预约了{YuqiyzData.Rows[0]["CYDATE"].ToString()}，是否继续查询");
                            Yq = false;
                            return;
                        }
                        else if (YuqiyzData.Rows[0][0].ToString() == "3")
                                YuQicount = int.Parse(YuqiyzData.Rows[0]["YuQiCount"].ToString());
                    }
                }
                string YzFile = $"select FBillNo,FFileCabinetNumber,FNAME,FPHONE,FIDCARD From T_LQKJ_FilesManage where FIDCARD='{FIDCARD}' and FInvalidatedStatus='A'";
                DataTable YzFileData = DBServiceHelper.ExecuteDataSet(this.Context, YzFile).Tables[0];
                if (YzFileData == null || YzFileData.Rows.Count < 1)
                {
                    this.View.ShowErrMessage($"您所查阅的 {msg["Model"]["FDAName"].ToString()} 的档案不存在！！");
                    return;
                }
                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"] = YzFileData.Rows[0]["FNAME"].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;//逾期次数                                       
                var result = JObject.Parse(Client.Save("LQKJ_ArchiveAccess", msg.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)
                {
                    this.View.ShowMessage("现场查阅成功");
                    Zt = false;
                    Yq = true;
                    this.View.Model.SetValue("FBillNo", YzFileData.Rows[0]["FBillNo"].ToString());
                    this.View.Model.SetValue("FFileCabinetNumber", YzFileData.Rows[0]["FFileCabinetNumber"].ToString());
                }
                else
                {
                    this.View.ShowErrMessage("现场查阅失败，请联系管理员");
                    Zt = false;
                    Yq = true;
                }
            }
            else
            {
                this.View.ShowErrMessage("查询的身份信息不存在线上预约的情况下才允许记录");
            }
        }

        /// <summary>
        /// 本人查阅
        /// </summary>
        private void Deposit()
        {
            //判断档案是否存在
            string idCard = this.View.Model.GetValue("F_LQKJ_IdCard")?.ToString();
            if (string.IsNullOrEmpty(idCard))
            {
                this.View.ShowErrMessage("身份证号不能为空！！");
                return;
            }
            string sql = $"/*dialect*/select FBillNo,FFileCabinetNumber from T_LQKJ_FilesManage where FIDCARD='{idCard}'";
            DataSet Dts = DBServiceHelper.ExecuteDataSet(this.Context, sql);
            if (Dts == null || Dts.Tables == null || Dts.Tables[0].Rows.Count < 1)
            {
                this.View.ShowErrMessage("所查询的档案不存在！！");
                return;
            }
            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 = DBServiceHelper.ExecuteDataSet(this.Context, YYSql);
            if (Dts2 == null || Dts2.Tables == null || Dts2.Tables[0].Rows.Count < 1)
            {
                this.View.ShowErrMessage("无预约信息，请点击添加现场查阅记录按钮后，查看档案编号和档案柜编号！！");
                Zt = true;
                return;
            }
            else
            {
                this.View.Model.SetValue("FBillNo", Dts.Tables[0].Rows[0]["FBillNo"].ToString());
                this.View.Model.SetValue("FFileCabinetNumber", Dts.Tables[0].Rows[0]["FFileCabinetNumber"].ToString());
            }

        }
    }
}
