using FluentScheduler;
using Newtonsoft.Json;
using Siger.Middlelayer.AccRepository.Request;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Configuration;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Siger.ApiACC.Tasks
{
    public class AutoMES : IJob, IDisposable
    {
      

        public void Execute()
        {
            Logger.WriteLineInfo($"execute mes job");

            var projectId = GetProjectId();
            var hostDic = GetHost();
            if (projectId==0 || !hostDic.Any())
            {
                Logger.WriteLineInfo($"配置未完整");
                return;
            }
            using (DBhelper dbhelper = new DBhelper())
            {
                var tasklist = dbhelper.GetTaskList(projectId);
                if (!tasklist.Any())
                {
                    return;
                }
                
                var tasks = tasklist.OrderBy(s => s.actiontype);
                var task = tasks.FirstOrDefault();

                var sendToPLC = new RequestPLC
                {
                    RStation = task.sectionid,
                    Fixture = task.fixtureguid,
                    RequestForm = task.no,
                    RobotStep = (int)task.action,
                    StorageNo = task.locationid,
                    SN = task.sn,
                    Program = task.programnumber
                };

                var result = PushTask(hostDic,sendToPLC, out string message);
                if (!result)
                {
                    Logger.WriteLineError($"TASK 下发失败 : {message}");
                    return;
                }
                task.send = 1;
                if (!dbhelper.UpdateTask(task))
                {
                    Logger.WriteLineError($"更新TASK 下发状态失败");
                }
            }
        }
        public void Dispose()
        {
            
        }

        /// <summary>
        /// 下发任务
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="request"></param>
        /// <param name="msg"></param>
        private bool PushTask(string ip,RequestPLC request,out string msg)
        {
            msg = string.Empty;
            try
            {
                var param = JsonHelper.SerializerToJsonString(request);
                var retstring = HttpHelper.HttpPost($"{ip}{CommonConst.SenTaskToMES}", "application/json", param);
                var result = JsonConvert.DeserializeObject<ResponsePlC>(retstring);
                if (result.return_code != 0)
                {
                    msg = $"PushTask failed,URL{ip} input:{param } result :{result.return_desc}";
                    return false;
                }
                return true;
            }catch(Exception ex)
            {
                msg = ex.ToString();
            }
            return false;
        }

        private int GetProjectId()
        {
            var _pid = ConfigManager.GetValue("ProjectSetting", "ProjectId", string.Empty);
            if (string.IsNullOrEmpty(_pid))
                Logger.WriteLineError("DbSetting about [ProjectSetting] ProjectId not found.");
            return int.Parse(_pid);
        }
        private string GetHost()
        {

            var host = ConfigManager.GetValue("ProjectSetting", "Host", string.Empty);
            if (string.IsNullOrEmpty(host))
            {
                Logger.WriteLineError("DbSetting about [ProjectSetting] Host not found.");
                return null;
            }

            return host;

        }
    }
}
