using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Data.Model.Standard.Tracking._17;
using XYY.TaskTrack.Standard;
using XYY.gRpc.Tracking;
using Grpc.Core;
using Microsoft.Extensions.Logging;
using Grpc.Net.Client;

namespace XYY.WindowsService.ReshMQ.Works
{
    public interface ISeventeenGRPC : IBaseConsumer<XYY.Data.Model.Standard.Tracking._17._17TrackingMQData>
    {
    }

    public class SeventeenGRPC : ISeventeenGRPC
    {
        GrpcChannel channelBase;
        private readonly ILogger<SeventeenGRPC> _logger;

        public SeventeenGRPC(ILogger<SeventeenGRPC> logger, TrackingGrpcChanel channelBase)
        {
            _logger = logger;
            this.channelBase = channelBase.Channel;
        }


        public async Task Consume(_17TrackingMQData message)
        {
            try
            {
                SeventeenConvert.SeventeenConvertClient client = new SeventeenConvert.SeventeenConvertClient(channelBase);
                var resut = await client.ConvertAsync(new SeventeenConvertReq
                {
                    Data = message.Data,
                    Event = message.Event,
                    Sign = message.Sign
                });
                if (!resut.Success)
                {
                    string resMeg = resut.Message;
                    string reqMsg = message.Data;
                    string errorTitle = "获取17Tracking转换";
                    await HandErroLog(resMeg, reqMsg, errorTitle);
                    return;
                }
                Db.DbClient dbClient = new Db.DbClient(channelBase);
                var addMessage = await dbClient.AddTrackingAsync(resut.Data);
                if (!addMessage.Success)
                    await HandErroLog("保存数据失败", message.Data, addMessage.Message);
            }
            catch (Exception ex)
            {
                await HandErroLog("GRPC服务调用失败", message.Data, ex.Message);
            }
        }

        private async Task HandErroLog(string resMeg, string reqMsg, string errorTitle)
        {
            HandErrorLog.HandErrorLogClient logClient = new HandErrorLog.HandErrorLogClient(channelBase);
            var req = new HandErrorLogReq();
            req.Logs.Add(new ErrorLog
            {
                Source = "17Tracking",
                ErrorMessage = resMeg,
                RequestMessage = reqMsg,
                TargetTime = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.Now.ToUniversalTime()),
                TrackingNumber = String.Empty
            });
            await logClient.PostDataAsync(req);
            _logger.LogError("api:{api} res:{res} req:{req}", errorTitle, resMeg, reqMsg);
        }
    }
}
