using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.Helper;
using JLHHJSvr.LJException;
using LJLib.Net.SPI.Server;
using LJLib.SQLEX;
using System;
using System.Diagnostics;
using System.Linq;

namespace JLHHJSvr.Excutor
{
    internal sealed class CreateScheduleTaskExcutor : ExcutorBase<CreateScheduleTaskRequest, CreateScheduleTaskResponse>
    {
        protected override void ExcuteInternal(CreateScheduleTaskRequest request, object state, CreateScheduleTaskResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }
            if (string.IsNullOrEmpty(request.task_type))
            {
                rslt.ErrMsg = "缺少任务类型";
                return;
            }
            if (request.schedule_time == null)
            {
                rslt.ErrMsg = "缺少计划执行时间";
                return;
            }
            if (request.items == null || !request.items.Any())
            {
                rslt.ErrMsg = "至少提交一条任务明细";
                return;
            }
            if (request.task_type != ScheduleTaskHelper.TaskTypeMattressRecalc)
            {
                rslt.ErrMsg = "暂不支持的任务类型:" + request.task_type;
                return;
            }

            var scheduleTime = request.schedule_time.Value;
            if (scheduleTime < DateTime.Now.AddMinutes(-1))
            {
                throw new LJCommonException("计划执行时间不能早于当前时间");
            }

            using (var con = GlobalVar.ConnectionString.NewSqlConnection())
            using (var cmd = con.CreateCommand())
            {
                con.Open();

                var mattressHelper = HelperBase.GetHelper<MattressHelper>(cmd);

                var items = request.items
                    .Where(t => t > 0)
                    .GroupBy(t => t)
                    .Select(g => g.First())
                    .ToList();
                var mattressList = mattressHelper.GetMattressList(request.items,"mattressid,mattresscode,mattressname");

                var start_time = DateTime.Now;

                if (!mattressList.Any()) throw new LJCommonException("没有有效的任务明细");
                using (cmd.Transaction = con.BeginTransaction())
                {
                    try
                    {
                        var taskid = ScheduleTaskHelper.CreateTaskLog(cmd, new u_task_log
                        {
                            task_type = request.task_type,
                            run_mode = 2,
                            schedule_time = scheduleTime,
                            status = 0,
                            total_count = mattressList.Count,
                            request_json = request.request_json,
                            create_emp = tokendata.username,
                            start_time = start_time
                        });

                        var printid = 1;
                        ScheduleTaskHelper.InsertTaskLogItems(cmd, taskid, mattressList.Select(item => new u_task_log_mx
                        {
                            printid = printid++,
                            biz_id = item.mattressid,
                            biz_code = item.mattresscode,
                            biz_name = item.mattressname,
                            status = 0,
                            start_time = start_time
                        }).ToList());

                        cmd.Transaction.Commit();
                        rslt.taskid = taskid;
                        rslt.task_type = request.task_type;
                        rslt.schedule_time = scheduleTime;
                        rslt.total_count = mattressList.Count;
                        rslt.logMsg = $"已创建定时任务，任务号:{taskid}，计划时间:{scheduleTime:yyyy-MM-dd HH:mm}，共{items.Count}条。";
                        Trace.Write(rslt.logMsg);
                    }
                    catch (Exception ex)
                    {
                        cmd.Transaction.Rollback();
                        rslt.ErrMsg = ex.Message;
                    }
                }
            }
        }
    }
}
