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 System.Text.RegularExpressions;
using LQKJ.LicVerify;

namespace LQKJ.DANGAN.ReportPlugIN
{
    [HotUpdate,Description("动态表单")]
    public class Report: AbstractBillPlugIn
    {
        public override void AfterSave(AfterSaveEventArgs e)
        {
            if (!LicScheduler.LicVerify())
                throw new Exception("lic过期");
            base.AfterBindData(e);
            if (this.View.OpenParameter.Status.Equals(OperationStatus.ADDNEW))
            {
                this.View.Model.SetValue("FDatetime", DateTime.Now.ToString("yyyy-MM-dd HH:ss"));
                this.View.UpdateView("FDatetime");
                return;
            }
            int HS = this.Model.GetEntryRowCount("F_LQKJ_ProfileInfoEntity");
            this.View.Model.SetValue("FTransferQty", HS);
            this.View.UpdateView("FTransferQty");
        }
        public override void AfterBindData(EventArgs e)
        {
            if (!LicScheduler.LicVerify())
                throw new Exception("lic过期");
            base.AfterBindData(e);
            //判断单据的状态是否为新增
            if (this.View.OpenParameter.Status.Equals(OperationStatus.ADDNEW))
            {
                return;
            }
            //获取总行数
            int HS = this.Model.GetEntryRowCount("F_LQKJ_ProfileInfoEntity");
            /*string UpdateSql = $"update T_DA_ArchiveEntry set FFileCabinet='{HS}', where FEntryID='{this.View.Model.DataObject["Id"].ToString()}'";
            DBServiceHelper.Execute(this.Context, UpdateSql);*/
            //单据体数据
            DynamicObjectCollection selectedRowsDy = this.Model.DataObject["DA_ArchiveEntry"] as DynamicObjectCollection;
            for (int i = 0; i < HS; i++)
            {
                DynamicObject selectedRow = selectedRowsDy[i];
                if (selectedRow["FFileCabinet"]==null||selectedRow["FFileCabinet"].ToString().Trim() != "")
                {
                    LockEntityRow(this.View, "DA_ArchiveEntry", i);
                }
            }
        }
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            //判断单据的状态是否为新增
            if (this.View.OpenParameter.Status.Equals(OperationStatus.ADDNEW))
            {
                return;
            }
            if (e.BarItemKey.Equals("LQKJ_YRDANGAN"))
            {
                if (this.View.Model.GetValue("FHandleStates").ToString() != "Y")
                {
                    this.View.ShowErrMessage("请办理业务后进行移入档案柜操作！");
                    return;
                }
                this.View.Model.Save();
                string dbid = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["Dbid"].Value;
                string username = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["username"].Value;
                string password = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["password"].Value;
                string url = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["url"].Value;
                K3CloudApiClient Client = new K3CloudApiClient(url);
                var loginResult = Client.ValidateLogin(dbid, username, password, 2052);
                var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
                if (resultType != 1)
                {
                    throw new Exception("登陆失败");
                }
                //获取总行数
                int HS = this.Model.GetEntryRowCount("F_LQKJ_ProfileInfoEntity");
                if (HS == 0)
                {
                    this.View.ShowErrMessage("没有数据！");
                    return;
                }
                DataTable DtId= DBServiceHelper.ExecuteDataSet(this.Context, $"/*dialect*/select FIDCARD from T_LQKJ_FilesManage where FINVALIDATEDSTATUS='A'").Tables[0];
                //单据体数据
                DynamicObjectCollection selectedRowsDy = this.Model.DataObject["DA_ArchiveEntry"] as DynamicObjectCollection;
                StringBuilder stringBuilder = new StringBuilder();
                string header = "{\"IsDeleteEntry\": \"false\",\"IsAutoAdjustField\": \"true\",\"Model\":[";
                stringBuilder.Append(header);
                string context = "";
                string Datestr;
                if (string.IsNullOrWhiteSpace(this.View.Model.GetValue("FDatetime")?.ToString()))
                {
                     Datestr = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                }
                else
                {
                     Datestr = this.View.Model.GetValue("FDatetime")?.ToString();
                }
                List<int> ConutList = new List<int>();//记录序号
                List<int> FShareTransferList = new List<int>();//移交份数大于1的序号
                for (int i = 0; i < HS; i++)
                {
                    DynamicObject selectedRow = selectedRowsDy[i];
                    if((bool)selectedRow["FSelection"] && (selectedRow["FFileCabinet"]==null||selectedRow["FFileCabinet"].ToString().Trim() == ""))
                    {
                        if (string.IsNullOrWhiteSpace(selectedRow["FFileCabinetNumber"]?.ToString()) || string.IsNullOrWhiteSpace(selectedRow["FName"]?.ToString())|| string.IsNullOrWhiteSpace(selectedRow["FIDCards"]?.ToString()))
                        {
                            this.View.ShowErrMessage("选择的所有行的档案柜编号,姓名，身份证不能为空！");
                            return;
                        }else if(!ValidateIdCardNumber(selectedRow["FIDCards"]?.ToString()))
                        {
                            this.View.ShowErrMessage($"序号为{i+1}的行身份证格式不正确！请修改");
                            return;
                        }
                        else if (DtId.AsEnumerable().Where(s=>s.Field<string>("FIDCARD")== selectedRow["FIDCards"].ToString().Trim()).Count()>0)
                        {
                            this.View.ShowErrMessage("移入失败！ " + "选择的行中：序号为" + (i + 1) + ",姓名，身份证为  " + selectedRow["FName"].ToString().Trim() + "  " + selectedRow["FIDCards"].ToString().Trim() + "档案已存在");
                            return;
                        }
                        if (int.Parse(selectedRow["FShareTransfer"]?.ToString()) > 1)
                        {
                            FShareTransferList.Add(i);
                        }
                        ConutList.Add(i);
                        context = "{\"FDocumentStatus\":\" C \", \"FFileCabinetNumber \": \"" + selectedRow["FFileCabinetNumber"] + "\",\"FGroupAffiliation\": \"" + selectedRow["FGroupAffiliation"] + "\",\"FhandedOverCompanies\": \"" + selectedRow["FhandedOverCompanies"] + "\",\"FStreet\": \"" + selectedRow["FStreet"] + "\",\"FCommunity\": \"" + selectedRow["FCommunity"] + "\",\"FName\": \"" + selectedRow["FName"] + "\",\"FIDCard\": \"" + selectedRow["FIDCards"] + "\",\"FSex\": \"" + selectedRow["FSex"] + "\",\"FPhone\": \"" + selectedRow["FPhone"] + "\",\"FISParty\": \"" + selectedRow["FISParty"] + "\",\"FPartyLocation\": \"" + selectedRow["FPartyLocation"] + "\",\"FEnterpriseQuality\": \"" + selectedRow["FEnterpriseQuality"] + "\",\"FReceiptDate\": \"" + Datestr + "\"},";
                        stringBuilder.Append(context);
                    }
                }
                if (ConutList.Count == 0)
                {
                    this.View.ShowMessage("未选择任何行！");
                    return;
                }
                try
                {
                    string last = "]}";
                    stringBuilder.Append(last);
                    var result = JObject.Parse(Client.BatchSave("LQKJ_FilesManage", stringBuilder.ToString()));
                    var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                    List<string> list = new List<string>();
                    if ((bool)Sueccess)
                    {
                        foreach (var item in result["Result"]["ResponseStatus"]["SuccessEntitys"])
                        {
                            string DangBH = item["Number"].ToString();
                            int XH = ConutList[(int)item["DIndex"]];
                            string FENID = this.View.Model.GetEntryPKValue("F_LQKJ_ProfileInfoEntity", XH).ToString();
                            string UpdateSql = $"update T_DA_ArchiveEntry set FFileCabinet='{DangBH}',FSELECTION=0,FFileStateFFILESTATE='B' where FEntryID='{FENID}';";
                            list.Add(UpdateSql);
                        }
                        DBServiceHelper.ExecuteBatch(this.Context, list);
                        MultipleReport(selectedRowsDy, FShareTransferList, Client);
                        this.View.ShowMessage("选中行全部已全部移入成功");
                    }
                    else
                    {
                        if (result["Result"]["ResponseStatus"]["SuccessEntitys"]?.Count() == 0)
                        {
                            this.View.ShowErrMessage("全部移入失败！档案已存在或输入的数据不合法");
                        }
                        else
                        {
                            foreach (var item in result["Result"]["ResponseStatus"]["SuccessEntitys"])
                            {
                                string DangBH = item["Number"].ToString();
                                int XH = ConutList[(int)item["DIndex"]];
                                string FENID = this.View.Model.GetEntryPKValue("F_LQKJ_ProfileInfoEntity", XH).ToString();
                                string UpdateSql = $"update T_DA_ArchiveEntry set FFileCabinet='{DangBH}',FSELECTION=0 ,FFileStateFFILESTATE='B' where FEntryID='{FENID}'";
                                list.Add(UpdateSql);
                            }
                            string Xhstr = "";
                            foreach (var item in result["Result"]["ResponseStatus"]["Errors"])
                            {
                                Xhstr += ((ConutList[(int)item["DIndex"]]+1) + ",");

                            }
                            DBServiceHelper.ExecuteBatch(this.Context, list);
                            this.View.ShowErrMessage("序号为：" + Xhstr + "的档案信息移入失败！档案已存在或输入的数据不合法");
                        }
                    }
                    this.View.Model.Save();
                    this.View.Refresh();
                }
                catch (Exception ex)
                {
                    this.View.ShowErrMessage("移入失败，请检查数据是否合法!!"+ex.Message);
                }
                

            }
        }
        public void LockEntityRow(IDynamicFormView formView, string entryKey, int row)
        {
            var entityCollection = formView.Model.DataObject[entryKey] as DynamicObjectCollection;
            if (entityCollection == null || entityCollection.Count == 0) return;
            foreach (var property in entityCollection[0].DynamicObjectType.Properties)
            {
                var propertyName = property.Name;
                if (propertyName.Contains("Id") || propertyName.Equals("Seq"))
                {
                    continue;
                }
                formView.GetFieldEditor(propertyName, row).Enabled = false;
            }
        }
        /// <summary>
        /// 身份证校验
        /// </summary>
        /// <param name="idCardNumber"></param>
        /// <returns></returns>
        private bool ValidateIdCardNumber(string idCardNumber)
        {
            if (!char.IsLetter(idCardNumber[0]))
            {
                // 身份证号码正则表达式
                string pattern = @"(^\d{15}$)|(^\d{17}(\d|X|x)$)";
                Regex regex = new Regex(pattern);

                if (!regex.IsMatch(idCardNumber))
                {
                    return false; // 格式不正确
                }
            }
            return true;
        }

        public void MultipleReport(DynamicObjectCollection selectedRowsDy,List<int> FShareTransferList, K3CloudApiClient Client)
        {
            foreach (var i in FShareTransferList)
            {
                DynamicObject selectedRow = selectedRowsDy[i];
                int FShareTrans = int.Parse(selectedRow["FShareTransfer"]?.ToString());//获取移入行数
                if (FShareTrans <= 1)
                    continue;
                string SeSql = $"select FID,FBillNo,FIDCard from T_LQKJ_FilesManage where FDOCUMENTSTATUS='C'and FINVALIDATEDSTATUS='A' AND FIDCARD='{selectedRow["FIDCards"]}'";
                DataTable SeDt = DBServiceHelper.ExecuteDataSet(this.Context, SeSql).Tables[0];
                if(SeDt==null|| SeDt.Rows.Count < 1)
                {
                    continue;
                }
                string FBillNo = SeDt.Rows[0]["FBillNo"]?.ToString();//获取第一份的单据编号
                string Datestr;
                if (string.IsNullOrWhiteSpace(this.View.Model.GetValue("FDatetime")?.ToString()))
                {
                    Datestr = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                }
                else
                {
                    Datestr = this.View.Model.GetValue("FDatetime")?.ToString();
                }
                StringBuilder stringBuilder = new StringBuilder();
                string header = "{\"IsDeleteEntry\": \"false\",\"IsAutoAdjustField\": \"true\",\"Model\":[";
                stringBuilder.Append(header);
                for (int j = 1; j < FShareTrans; j++)
                {
                    stringBuilder.Append("{\"FBillNo\":\""+ FBillNo+"["+(j+1) +"]" + "\",\"FDocumentStatus\":\" C \", \"FFileCabinetNumber \": \"" + selectedRow["FFileCabinetNumber"] + "\",\"FGroupAffiliation\": \"" + selectedRow["FGroupAffiliation"] + "\",\"FhandedOverCompanies\": \"" + selectedRow["FhandedOverCompanies"] + "\",\"FStreet\": \"" + selectedRow["FStreet"] + "\",\"FCommunity\": \"" + selectedRow["FCommunity"] + "\",\"FName\": \"" + selectedRow["FName"] + "\",\"FIDCard\": \"" + selectedRow["FIDCards"] + "\",\"FSex\": \"" + selectedRow["FSex"] + "\",\"FPhone\": \"" + selectedRow["FPhone"] + "\",\"FISParty\": \"" + selectedRow["FISParty"] + "\",\"FPartyLocation\": \"" + selectedRow["FPartyLocation"] + "\",\"FEnterpriseQuality\": \"" + selectedRow["FEnterpriseQuality"] + "\",\"FReceiptDate\": \"" + Datestr + "\"},");
                }
                string last = "]}";
                stringBuilder.Append(last);
                var result = JObject.Parse(Client.BatchSave("LQKJ_FilesManage", stringBuilder.ToString()));
                var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                if ((bool)Sueccess)
                {
                    string UpdateSql1 = $"update T_LQKJ_FilesManage SET FBillNo='{FBillNo + "[1]"}' WHERE FBillNo='{FBillNo}'";
                    DBServiceHelper.Execute(this.Context, UpdateSql1);
                    List<string> DangBH=new List<string>();
                    DangBH.Add(FBillNo + "[1]");
                    foreach (var item in result["Result"]["ResponseStatus"]["SuccessEntitys"])
                    {
                        DangBH.Add(item["Number"].ToString());
                    }
                    string FENID = this.View.Model.GetEntryPKValue("F_LQKJ_ProfileInfoEntity", i).ToString();
                    string UpdateSql = $"update T_DA_ArchiveEntry set FFileCabinet='{string.Join(",", DangBH)}',FSELECTION=0,FFileStateFFILESTATE='B' where FEntryID='{FENID}';";
                    DBServiceHelper.Execute(this.Context, UpdateSql);
                }
            }
        }
    }
}
