using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Model.Standard.Channel;
using XYY.Service.Standard.ChannelApi.Base;
using XYY.TaskTrack.Standard;

namespace XYY.Service.Standard.Order
{
    public class CancelOrderJobMessage
    {
        public CancelOrderJobMessage() { SysmteNos = new List<string>(); }
        public List<string> SysmteNos
        {
            get; set;
        }
        public int UserId { get; set; }
        public string UserName { get; set; }
        public DateTime CreateTime { get; set; }
    }

    public interface ICancelOrderJobSubscribe : IBaseConsumer<CancelOrderJobMessage>
    {

    }

    public class CancelOrderJobSubscribe : BaseConsumer<CancelOrderJobMessage>, ICancelOrderJobSubscribe
    {
        private IUnitOfWork _unitOfWork;
        private ILogger<CancelOrderJobMessage> _jobLogger;
        private IEnumerable<IBaseApi> _baseApis;

        public CancelOrderJobSubscribe(IMQManager mq, IUnitOfWork _unitOfWork, ILogger<CancelOrderJobMessage> jobLogger, IEnumerable<IBaseApi> baseApis) : base(mq)
        {
            _jobLogger = jobLogger;
            this._unitOfWork = _unitOfWork;
            this._baseApis = baseApis;
        }
        public override async Task Consume(CancelOrderJobMessage job)
        {
            var batchQty = 1000.0;
            job.SysmteNos.RemoveAll(x => string.IsNullOrEmpty(x));//去空
            for (int i = 0; i < Math.Ceiling(job.SysmteNos.Count() / batchQty); i++)
            {
                var tempSysmteNos = job.SysmteNos.Skip(i * (int)batchQty).Take((int)batchQty).ToList();
                string sql = @$"select a.Id Order_OrderId,a.TrackingNumber,a.SystemNo,b.ServiceCode,b.PublicName,b.ApiHost,b.ApiKey,b.ApiSecret,{job.UserId} OperationUserId,'{job.CreateTime}' CreateTime,'{job.UserName}' CreateUserName,'{job.UserName}' UpdateUserName from Order_Order a
join Logistics_Channel b on b.Id=a.ChannelId
where (a.OrderStatus<3 or a.OrderStatus=4) and (a.SystemNo in @SystemNo or a.TrackingNumber in @SystemNo or a.TransferNumber in @SystemNo ) ";//小于三或者等于四，才可以取消
                List<logistics_ChannelCancel> logistics_ChannelCancels = (await _unitOfWork.QueryBySqlAsync<logistics_ChannelCancel>(sql, null,
                        new { SystemNo = tempSysmteNos })).ToList();
                foreach (var item in logistics_ChannelCancels)
                {
                    try
                    {
                        var baseApi = _baseApis.Where(x => x.ServiceName == item.ServiceCode).FirstOrDefault();
                        baseApi.CannelOrdersByModel(item);
                        item.UpdateTime = DateTime.Now;
                        if(item.ResultState == null)
                        {
                            item.ResultState = ResultStateEnum.成功.GetValue();
                        }
                    }
                    catch (Exception ex)
                    {
                        item.ResultState = ResultStateEnum.异常.GetValue(); item.ResultMessage = ex.Message;
                        continue;//异常进行下一个,记录以数据表为准
                    }
                }
                //1K 数据插入一次
                if (logistics_ChannelCancels.Count > 0)
                {
                    _unitOfWork.InsertBatch(logistics_ChannelCancels);
                    //更新处理成功的数据
                    var tempOrder_OrderId = logistics_ChannelCancels.Where(x => x.ResultState == ResultStateEnum.成功.GetValue()).Select(x => x.Order_OrderId).ToList();
                    if (tempOrder_OrderId.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append($"delete Order_UnusualReason where OrderId in ({string.Join(",", tempOrder_OrderId)})");
                        sb.Append(" insert into Order_UnusualReason (OrderId,UnusualReason,CreateTime,CreateUserName,UpdateTime,UpdateUserName) values ");
                        DateTime dateTime = DateTime.Now;
                        foreach (var item in tempOrder_OrderId)
                        {
                            sb.Append($"({item},{UnusualReasonType.渠道面单已手动取消.GetValue()},'{dateTime}','{job.UserName}','{dateTime}','{job.UserName}'),");
                        }
                        await _unitOfWork.ExecuteAsync(sb.ToString().TrimEnd(','));
                        await CheackChannel(logistics_ChannelCancels);
                    }

                }
            }
        }
        private async Task CheackChannel(List<logistics_ChannelCancel> cancels)
        {
            var CanExcuteData = cancels.Where(x => x.ResultState == ResultStateEnum.成功.GetValue() && x.PublicName.StartsWith("W-")).ToList();
            if (CanExcuteData != null && CanExcuteData.Count > 0)
            {
                string sql = "delete WinitOrderInfo where TransferNumber in @TransferNumber ";
                await _unitOfWork.ExecuteAsync(sql, new { TransferNumber = CanExcuteData.Select(x => x.SystemNo) });
            }
        }
    }
}
