using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;
using LQKJ.LicVerify;

namespace LQKJ.DANGAN.ReportPlugIN
{
    [HotUpdate,Description("动态表单插件，定制结算单")]
   public class DynamicReport: AbstractDynamicFormPlugIn
    {
        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;
        private int JdCount = 0;
        private K3CloudApiClient Login()
        {
            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("登陆失败");
            }
            return Client;
        }
        public override void OnLoad(EventArgs e)
        {
            if (!LicScheduler.LicVerify())
                throw new Exception("lic过期");
            //this.FBillNo = this.View.OpenParameter.GetCustomParameter("FBillNo").ToString();
        }

        public override void ButtonClick(ButtonClickEventArgs e)
        {
            if (!LicScheduler.LicVerify())
                throw new Exception("lic过期");
            base.ButtonClick(e);
            if (!e.Key.ToUpper().Equals("F_LQKJ_Button".ToUpper()))
            {
                return;
            }
            if (this.View.Model.GetValue("FDate1") == null|| this.View.Model.GetValue("FDate2") == null)
            {
                this.View.ShowErrMessage("时间区间不能为空");
                return;
            }
            if (this.View.Model.GetValue("FFeiYon") == null||double.Parse(this.View.Model.GetValue("FFeiYon").ToString())<0)
            {
                this.View.ShowErrMessage("每月存放费用每年为空且不能小于0！");
                return;
            }
            double Feiyon = double.Parse(this.View.Model.GetValue("FFeiYon").ToString());
            DateTime Date01 = DateTime.Parse(this.View.Model.GetValue("FDate1")?.ToString());
            DateTime Date02 = DateTime.Parse(this.View.Model.GetValue("FDate2")?.ToString());
            if (Date01 > Date02)
            {
                this.View.ShowErrMessage("开始时间不能大于结束时间！！");
                return;
            }
            int Sum=Cousdsd(Login(), Date01,Date02,Feiyon);
            var result = new FormResult(Sum);
            this.View.ReturnToParentWindow(result);
            this.View.Close();
        }
        private  int Cousdsd(K3CloudApiClient Client,DateTime Date1,DateTime Date2,double Feiyon)
        {
            //所有查询街道
            //string sttJd = $"select DISTINCT FSTREET from T_LQKJ_FilesManage WHERE FINVALIDATEDSTATUS='A' and FRECEIPTDATE>='{Date1.ToString("yyyy-MM-dd")}' and FRECEIPTDATE<='{Date2.ToString("yyyy-MM-dd")}'";
            string sttJd = $"select DISTINCT FSTREET from T_LQKJ_FilesManage WHERE FINVALIDATEDSTATUS='A'";
            DataTable TodayLateData = DBServiceHelper.ExecuteDataSet(this.Context, sttJd).Tables[0];
            if (TodayLateData == null || TodayLateData.Rows.Count < 1)
            {
                return 0;
            }
            //计算月数
            int Yuecount = GetMonthsDifference(Date1, Date2) + 1;
            //List<Task> tasks=new List<Task>();
            foreach (DataRow item in TodayLateData.Rows)
            {
                //tasks.Add(Task.Run(() => DynamicAsync(Client, item[0].ToString(), Date1, Date2, Feiyon, Yuecount)));
                string selectstr = $"EXEC CustomSettlement @JD='{item[0].ToString()}',@Date1='{Date1.ToString("yyyy-MM-dd")}',@Date2='{Date2.ToString("yyyy-MM-dd")}'";
                DataSet datas = DBServiceHelper.ExecuteDataSet(this.Context, selectstr);
                if (datas.Tables == null || datas.Tables.Count < 1)
                    continue;
                //获取原有数
                int YyCount = int.Parse(datas.Tables[0].Rows[0][0].ToString());
                //计算原有费用
                double Fy1 = YyCount * Yuecount * Feiyon;
                //获取新增人数
                int XzCount = int.Parse(datas.Tables[1].Rows[0][0].ToString());
                //计算总人数
                int SumR = YyCount + XzCount;
                //新增总月数
                int SumYue = 0;
                //获取每月人数统计
                DataTable Dt01 = datas.Tables[2];
                //统计每月新增月数
                DataTable Dt02 = datas.Tables[3];
                //每月新增人员
                DataTable Dt03 = datas.Tables[4];

                DateTime EndDate = Date2;
                DateTime StartDate = Date1;
                StringBuilder stringBuilder = new StringBuilder();
                string header = "{\"IsDeleteEntry\": \"false\",\"Model\": {\"FSettlementDate \":\"" + Date1.ToString("yyyy年MM月dd日") + "-" + Date2.ToString("yyyy年MM月dd日") + "\",\"FEndDate\": \""+ Date2 .ToString()+ "\",\"FStartDate\": \"" + Date1 .ToString()+ "\",\"FEntity\": [";
                stringBuilder.Append(header);
                string context = "";
                for (; StartDate < EndDate; StartDate = StartDate.AddMonths(1))
                {
                    var query = from row in Dt01.AsEnumerable()
                                where row.Field<string>("Date").Contains(StartDate.ToString("yyyy-MM"))
                                select row;
                    var query2 = from row in Dt02.AsEnumerable()
                                 where row.Field<string>("Date").Contains(StartDate.ToString("yyyy-MM"))
                                 select row;
                    int YRCount = 0;//月新增人数

                    int YueyCount = 0;//月新增月数
                    if (query.Any())
                    {
                        YRCount = query.FirstOrDefault().Field<int>("Count");
                    }
                    if (query2.Any())
                    {
                        YueyCount = query2.FirstOrDefault().Field<int>("YueCount");
                        SumYue += YueyCount;
                    }
                    var PersonnelDatalist = Dt03.AsEnumerable().Where(x => x.Field<string>("Date")== StartDate.ToString("yyyy-MM")).Select(x => new
                    {
                        FRECEIPTDATEAS = x[1].ToString(),//接收时间
                        FNAME= x[2].ToString(),//--姓名
                        FIDCARD=x[3].ToString(),//--身份证
                        FPHONE= x[4].ToString(),//--手机号
                        FSTREETS= x[5].ToString(),//--街道
                    });
                    string PersonnelListstr;
                    if (PersonnelDatalist.Count()<1)
                    {
                        PersonnelListstr = "[]";
                    }
                    else
                    {
                        /*JsonConvert.SerializeObject(PersonnelDatalist, Formatting.Indented);
                        JObject Json =new JObject(PersonnelDatalist);*/
                        PersonnelListstr = JsonConvert.SerializeObject(PersonnelDatalist, Formatting.Indented).ToString();
                    }
                    context = "{\"FDateAcceptance\": \"" + StartDate.ToString("yyyy-MM-dd") + "\",\"FMonthlyAdditions\": " + YRCount + ",\"FMonthlyIncrease\": " + YueyCount + ",\"FSummaryExpenses\": " + (YueyCount * Feiyon) + ",\"F_LQKJ_PersonnelList\": " + PersonnelListstr + "},";
                    stringBuilder.Append(context);
                }
                //新增总费用
                double XzSumFy = SumYue * Feiyon;
                //总费用
                double ZFeiYon = Fy1 + XzSumFy;
                string last = "],\"FStreet\":\"" + item[0] + "\",\"FOriginalPeople\":" + YyCount + ",\"FOriginalCost\":" + Fy1 + ",\"FDangAnSum \":" + (YyCount + XzCount) + ",\"FTotalPeople\":" + ZFeiYon + ",\"FNumberAdded\":" + XzCount + ",\"FNumberMonthsAdded\":" + SumYue + ",\"FNewTotalExpenses\":" + XzSumFy + "}}";
                stringBuilder.Append(last);
                var unAuditret = Client.Save("LQKJ_T_SettlementForm", stringBuilder.ToString());
                //JObject jobject = JObject.Parse(JsonConvert.SerializeObject(unAuditret));
                bool IsunAudiSuccess = (bool)JObject.Parse(unAuditret)["Result"]["ResponseStatus"]["IsSuccess"];
                if (!IsunAudiSuccess)
                {
                    continue;
                }
                else
                {
                    JdCount++;
                }
            }
            //await Task.WhenAll(tasks);
            return JdCount;
        }
        private int GetMonthsDifference(DateTime startDate, DateTime endDate)
        {
            return (endDate.Year - startDate.Year) * 12 + (endDate.Month - startDate.Month);
        }

        public async Task DynamicAsync(K3CloudApiClient Client, string JD, DateTime Date1, DateTime Date2, double Feiyon, int Yuecount)
        {
            await Task.Delay(0);
            int id=Thread.CurrentThread.ManagedThreadId;
            string selectstr = $"EXEC CustomSettlement @JD ='{JD}',@Date1='{Date1.ToString("yyyy-MM-dd")}',@Date2='{Date2.ToString("yyyy-MM-dd")}'";
            DataSet datas = DBServiceHelper.ExecuteDataSet(this.Context, selectstr);
            if (datas.Tables == null || datas.Tables.Count < 1)
                return;
            //获取原有数
            int YyCount = int.Parse(datas.Tables[0].Rows[0][0].ToString());
            //计算原有费用
            double Fy1 = YyCount * Yuecount * Feiyon;
            //获取新增人数
            int XzCount = int.Parse(datas.Tables[1].Rows[0][0].ToString());
            //计算总人数
            int SumR = YyCount + XzCount;
            //新增总月数
            int SumYue = 0;
            //获取每月人数统计
            DataTable Dt01 = datas.Tables[2];
            //统计每月新增月数
            DataTable Dt02 = datas.Tables[3];

            DateTime EndDate = Date2;
            DateTime StartDate = Date1;
            StringBuilder stringBuilder = new StringBuilder();
            string header = "{\"IsDeleteEntry\": \"false\",\"Model\": {\"FSettlementDate \":\"" + Date1.ToString("yyyy年MM月dd日") + "-" + Date2.ToString("yyyy年MM月dd日") + "\",\"FEntity\": [";
            stringBuilder.Append(header);
            string context = "";
            for (; StartDate < EndDate; StartDate = StartDate.AddMonths(1))
            {
                var query = from row in Dt01.AsEnumerable()
                            where row.Field<string>("Date").Contains(StartDate.ToString("yyyy-MM"))
                            select row;

                var query2 = from row in Dt02.AsEnumerable()
                             where row.Field<string>("Date").Contains(StartDate.ToString("yyyy-MM"))
                             select row;

                int YRCount = 0;//月新增人数

                int YueyCount = 0;//月新增月数
                if (query.Any())
                {
                    YRCount = query.FirstOrDefault().Field<int>("Count");
                }
                if (query2.Any())
                {
                    YueyCount = query2.FirstOrDefault().Field<int>("YueCount");
                    SumYue += YueyCount;
                }
                context = "{\"FDateAcceptance\": \"" + StartDate.ToString("yyyy-MM-dd") + "\",\"FMonthlyAdditions\": " + YRCount + ",\"FMonthlyIncrease\": " + YueyCount + ",\"FSummaryExpenses\": " + (YueyCount * Feiyon) + "},";
                stringBuilder.Append(context);
            }
            //新增总费用
            double XzSumFy = SumYue * Feiyon;
            //总费用
            double ZFeiYon = Fy1 + XzSumFy;
            string last = "],\"FStreet\":\"" + JD + "\",\"FOriginalPeople\":" + YyCount + ",\"FOriginalCost\":" + Fy1 + ",\"FDangAnSum \":" + (YyCount + XzCount) + ",\"FTotalPeople\":" + ZFeiYon + ",\"FNumberAdded\":" + XzCount + ",\"FNumberMonthsAdded\":" + SumYue + ",\"FNewTotalExpenses\":" + XzSumFy + "}}";
            stringBuilder.Append(last);
            var unAuditret = Client.Save("LQKJ_T_SettlementForm", stringBuilder.ToString());
            //JObject jobject = JObject.Parse(JsonConvert.SerializeObject(unAuditret));
            bool IsunAudiSuccess = (bool)JObject.Parse(unAuditret)["Result"]["ResponseStatus"]["IsSuccess"];
            if (!IsunAudiSuccess)
            {
                return;
            }
            else
            {
                JdCount++;
            }
        }
    }
}
