using iTextSharp.text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Core.Standard.Mvc;
using XYY.Data.Model.Standard.Tracking;
using XYY.Service.Standard.First.DB;
using XYY.TaskTrack.Standard;

namespace XYY.Api.First.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TrackingLogController
    {
        ITrackingLogDB trackingLogDB;
        private IMQManager _MQManager;

        public TrackingLogController(ITrackingLogDB trackingLogDB, IMQManager mQManager)
        {
            this.trackingLogDB = trackingLogDB;
            _MQManager = mQManager;
        }

        [AllowAnonymous]
        public async Task<ApiJsonModel> RetryOnlie()
        {
            return ApiJsonModel.OK(trackingLogDB.GetOnlineErrors().Select(x => x.CustomerNo));
        }




        [AllowAnonymous]
        public async Task<ApiJsonModel> AddLog(List<TrackingTraceLog> trackingTraceLogs)
        {
            ///写入日志是否成功
            bool IsInsert = trackingLogDB.ManyInsert(trackingTraceLogs, out var IsRepeat);
            if (IsInsert)
            {
                //写入待推送消息
                var message = trackingTraceLogs.Select(x => new XikeTraceMessage
                {
                    CustomerNo = x.CustomerNo,
                    EventLoaction = x.EventLoaction,
                    EventContent = x.EventContent,
                    EventTime = x.EventTime,
                    Key = x.Key,
                    TrackingEventType = x.TrackingEventType,
                }).ToList();
                try
                {
                    await _MQManager.Publish(message);
                }
                catch (Exception ex)
                {
                    trackingTraceLogs.ForEach(x =>
                    {
                        x.StepName = StepName.InsertMQError;
                        x.SendMessage = "推送同步消息失败" + ex.Message;
                    });
                    var IsUpdate = trackingLogDB.ManyUpdate(trackingTraceLogs);
                    if (!IsUpdate)
                    {
                        throw new Exception("更新ES日志状态失败,推送同步消息异常" + ex.Message);
                    }
                    else
                    {
                        throw new Exception("推送同步消息失败" + ex.Message);
                    }
                }
                return ApiJsonModel.OK(null);

            }
            else
            {
                if (IsRepeat)
                    return ApiJsonModel.OK(null);
                throw new Exception("写入ES日志失败");
            }
        }
    }
}
