using Infrastructure;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using OpenAuth.App.BaseApp.WFTask;
using OpenAuth.App.Interface;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.App.BaseApp.Jobs
{
    public class TaskOverTimeJob:IJob
    {
        private ImMsgApp _immsgApp;
        private OpenJobApp _openJobApp;
        private WFTaskApp _wfTaskApp;
        private IAuth _auth;

        public TaskOverTimeJob(ImMsgApp immsgApp, OpenJobApp openJobApp, WFTaskApp wfTaskApp, IAuth auth)
        {
            _immsgApp = immsgApp;
            _openJobApp = openJobApp;
            _wfTaskApp = wfTaskApp;
            _auth = auth;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            var jobId = context.MergedJobDataMap.GetString(Define.JOBMAPKEY);
            //todo:这里可以加入自己的自动任务逻辑
            try
            {
                var job = _openJobApp.Get(jobId);
                if (job != null)
                {
                    var parms = (JObject)JsonConvert.DeserializeObject(job.JobCallParams);
                    string taskid = parms["TaskId"].ToString();

                    //更新任务状态
                    var taskInfo = _wfTaskApp.GetEntity(taskid);
                    if(taskInfo != null && (taskInfo.State == 3 || taskInfo.State == 4))
                    {
                        _openJobApp.DeleteEntity(job);
                    }
                    else
                    {
                        taskInfo.IsOutTime = 2;
                        _wfTaskApp.Update(taskInfo);

                        //创建消息接收用户集合
                        List<string> userlist = new List<string>();
                        userlist.Add(taskInfo.UserId);
                        var users = _wfTaskApp.GetUsers(taskid);
                        userlist = userlist.Union(users).ToList();
                        //创建消息发送内容
                        string msg = $"任务{taskInfo.ProcessTitle}{taskInfo.UnitName}已严重超时，请及时办理";

                        //更新Job信息，停止job，运行次数+1
                        _openJobApp.RecordRun(jobId);
                        _openJobApp.ChangeJobStatus1(new App.Request.ChangeJobStatusReq { Id = jobId, Status = 0 });

                        //发送消息
                        await _immsgApp.SendMsg("ChaoShi", userlist, msg, "4", taskInfo.Token);
                    }
                }
            }
            catch
            {

            }

            await Task.CompletedTask;
        }
    }
}
