
using Furion.ClayObject;
using Furion.RemoteRequest.Extensions;
using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 家长问卷填答进度管理服务
/// </summary>
public class ExamPatriarchQuestionnaireProgressSync(IRepository<ExamPatriarchQuestionnaireProgress> rep) : IExamPatriarchQuestionnaireProgressSync, IScoped
{
    public async Task Sync()
    {
        // 目前已废弃
        if (DateTime.Now < new DateTime(2023, 1, 1))
        {
            return;
        }

        Log.Information("开始同步学生家长问卷进度");

        Dictionary<string, string> qs = new()
        {
            { "9am", "http://wenjuan.cqcet.edu.cn/question/applice/answer/answerData.action?code=9am&tokenId=ce789fc1044dd7b0d4ef2b42e4916b66" },
            { "yyd", "http://wenjuan.cqcet.edu.cn/question/applice/answer/answerData.action?code=yyd&tokenId=d07e946b0d1d36666f68623a38fd26a7" },
        };

        foreach (var kvp in qs)
        {
            var maxSubmitTime = await rep.DetachedEntities.Where(t => t.QuestionnaireCode.ToLower() == kvp.Key.ToLower()).MaxAsync(t => t.SubmitTime);
            string url = kvp.Value;
            if (maxSubmitTime != null)
            {
                url = $"{url}&beginTime={maxSubmitTime:yyyy-MM-dd HH:mm:ss}";
            }
            var strRes = await url.GetAsStringAsync();
            var res = (QuestionnaireProgressResponse)Clay.Parse(strRes);
            if (res.code != "200")
            {
                Log.Error($"同步{kvp.Key}问卷错误");
                continue;
            }
            var items = res.data.Where(t => maxSubmitTime == null || t.finishedTime > maxSubmitTime);
            var dt = DateTime.Now;
            List<ExamPatriarchQuestionnaireProgress> newItems = [];
            foreach (var item in items)
            {
                newItems.Add(new()
                {
                    QuestionnaireCode = kvp.Key,
                    ExamStudentId = item.id,
                    Mobile = item.phone,
                    SubmitTime = item.finishedTime,
                    IsCompleted = true,
                    CreateTime = dt,
                });
            }
            if (items.Any())
            {
                await rep.InsertNowAsync(newItems);
            }
        }
    }
}
