using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using Kingdee.BOS.Contracts;
using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System.Data;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Kingdee.BOS.WebApi.Client;

namespace LQKJ.K3.FileSystem.BlacklistTimingPlugIN
{
    /// <summary>
    /// 定制结算清单
    /// </summary>
    class CustomSettlementTimingPlugIN: IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            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("登陆失败");
            }
            //所有查询街道
            string sttJd = "select DISTINCT FSTREET from T_LQKJ_FilesManage WHERE FINVALIDATEDSTATUS='A'";
            DataTable TodayLateData = DBServiceHelper.ExecuteDataSet(ctx, sttJd).Tables[0];
            if (TodayLateData == null || TodayLateData.Rows.Count < 1)
            {
                return;
            }
            foreach (DataRow item in TodayLateData.Rows)
            {
                string selectstr = $"EXEC CustomSettlement @JD='{item[0].ToString()}'";
                DataSet datas = DBServiceHelper.ExecuteDataSet(ctx, selectstr);
                if (datas.Tables == null || datas.Tables.Count < 1)
                    continue;
                //获取原有数
                int YyCount = int.Parse(datas.Tables[0].Rows[0][0].ToString());
                //计算原有费用
                double Fy1 = YyCount * 150;
                //获取新增人数
                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 = new DateTime(2023, 11, 1);
                DateTime StartDate = EndDate.AddMonths(-12);
                StringBuilder stringBuilder = new StringBuilder();
                string header = "{\"IsDeleteEntry\": \"false\",\"Model\": {\"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 * 12.5) + "},";
                    stringBuilder.Append(context);
                }
                //新增总费用
                double XzSumFy = SumYue * 12.5;
                //总费用
                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;
                }
            }
        }
    }
}
