using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.KitChenManage.Core;
using BPA.SAAS.Manage.Application.AExternalPlatform.BaseDto;
using BPA.SAAS.Manage.Application.AExternalPlatform.Enum;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Material.Dtos;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Material.Services;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.ThirdpartyPush.Dtos;
using BPA.SAAS.Manage.Comm.Util;
using BPA.SAAS.Manage.Core.Device;
using BPA.SAAS.Manage.Core.Product;
using BPA.SAAS.Manage.Core.System;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.AExternalPlatform.Service.ThirdpartyPush.Services
{
    public class ThirdpartyPushService : IThirdpartyPushService, ITransient
    {
        #region 设备 回调级下发数据和记录

        /// <summary>
        /// 添加 三方 回调设备记录
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> AddThirdpartyPushRecord(BPA_ThirdpartyPushRecord inputDto)
        {
            var res = await SqlSugarDb.Db.Insertable(inputDto).ExecuteCommandAsync();

            return res > 0;

        }


        /// <summary>
        /// 下发到设备
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> PushDevice(List<PushDeviceDto> inputDto)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("groupId", CurrentUser.GroupId);
            var url = App.Configuration["baseurl"] + "api/devicepushrecode/add_alm";
            var inputData = JsonConvert.SerializeObject(inputDto);
            var jsonData = HttpHelper.PostData(url, inputData, Encoding.UTF8, "application/json", dic);
            var data = JsonConvert.DeserializeObject<ResultSAASManageDto<bool>>(jsonData);
            if (data.statusCode != 200) throw Oops.Oh(ErrorCodeEnum.Code10016);
            if (!data.data) throw Oops.Oh(ErrorCodeEnum.Code10016);
            return true;
        }


        /// <summary>
        /// 修改 第三方订单的回调
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateThirdpartyPushRecord(ThirdpartyPushRecordDto inputDto)
        {
            var data = await SqlSugarDb.Db.Queryable<BPA_ThirdpartyPushRecord>()
                .ClearFilter()
                .FirstAsync(x => x.MessageId == inputDto.MessageId&&x.PushDevice==inputDto.DeviceId);
            if (data == null)
            {
                throw Oops.Oh("没有查询到回调信息");
            }
            data.IsPush = inputDto.IsPush;
            data.CreateAt = DateTime.Now;
            data.Status = 0;
           var result= await SqlSugarDb.Db.Updateable(data).ExecuteCommandAsync();

            //回调

            var urlstr = "";

            if (data.Type==2)
            {
                urlstr = $@"{data.CallbackUrl}?materialId={data.PushData}&Device={inputDto.DeviceId}";
                Dictionary<string, string> dic = new Dictionary<string, string>();
                var inputData ="";
               var res= HttpHelper.PostData(urlstr, inputData, Encoding.UTF8, "application/json", dic);
               if (res.ToUpper()=="true".ToUpper())
               {
                   data.IsCallback = true;
               }
               data.CallbackInfo= res;
               await SqlSugarDb.Db.Updateable(data).ExecuteCommandAsync();
            }


            return result > 0;

        }


        /// <summary>
        /// 更具店铺获取设备
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<List<string>> GetDeviceByStoreId(List<string> inputDto)
        {
            var data = await SqlSugarDb.Db.Queryable<BPA_DeviceInfo>()
                .Where(x => inputDto.Contains(x.StopId))
                .Select(x => x.Id)
                .ToListAsync();
            return data;
        }


        /// <summary>
        /// 添加下发记录和下发数据
        /// </summary>
        /// <param name="inputDto"></param>
        /// <param name="type">  1.商品  2.物料  3.配方  4.工艺</param>
        /// <param name="pushData">改动的数据 如物料的id  商品的id  订单的订单号</param>
        /// <param name="pushMQData">下发到设备的数据 json</param>
        /// <returns></returns>
        public async Task<bool> AddPushRecordAndPushDevice<T>(BaseRequestDto<T> inputDto, int type, string pushData, string pushMQData)
        {
            var input = new List<PushDeviceDto>();

            if (inputDto.StoreIdList != null && inputDto.StoreIdList.Count > 0)
            {
                input = await SqlSugarDb.Db.Queryable<BPA_DeviceInfo, BPA_Product, BPA_ProductVesion>((a, b, c) => new JoinQueryInfos(
                        JoinType.Left, a.ProductId == b.Id,
                        JoinType.Left, a.ProductVersionId == c.Id
                        ))
                    .Where((a, b, c) => inputDto.StoreIdList.Contains(a.StopId))
                    .Select((a, b, c) => new PushDeviceDto
                    {
                        deviceAutoKey = a.AutoKey,
                        deviceId = a.Id,
                        deviceName = a.DeviceName,
                        messageId = CurrentUser.MessageId,
                        productKey = b.Key,
                        productName = b.Name,
                        productVersion = c.Vesion,
                        type = 2,

                    })
                    .ToListAsync();

            }

            if (inputDto.DeviceIdList != null && inputDto.DeviceIdList.Count > 0)
            {
                input = await SqlSugarDb.Db.Queryable<BPA_DeviceInfo, BPA_Product, BPA_ProductVesion>((a, b, c) => new JoinQueryInfos(
                        JoinType.Left, a.ProductId == b.Id,
                        JoinType.Left, a.ProductVersionId == c.Id))
                    .Where((a, b, c) => inputDto.DeviceIdList.Contains(a.Id))
                    .Select((a, b, c) => new PushDeviceDto
                    {
                        deviceAutoKey = a.AutoKey,
                        deviceId = a.Id,
                        deviceName = a.DeviceName,
                        messageId = CurrentUser.MessageId,
                        productKey = b.Key,
                        productName = b.Name,
                        productVersion = c.Vesion,
                        type = 2,
                    })
                    .ToListAsync();
            }

            //4.添加记录
            foreach (var item in input)
            {
                await AddThirdpartyPushRecord(new Core.System.BPA_ThirdpartyPushRecord()
                {
                    CallbackUrl = inputDto.CallbackUrl,
                    GroupId = CurrentUser.GroupId,
                    Id = Guid.NewGuid().ToString(),
                    IsPush = false,
                    MessageId = CurrentUser.MessageId,
                    PushDevice = item.deviceId,
                    PushData = pushData,
                    Status = 1,
                    Type = type,
                    IsCallback=false,
                    CallbackInfo = "",
                });
                item.data = pushMQData;
            }

            //5.发送mqy
            await PushDevice(input);

            return true;
        }




        #endregion
    }
}
