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.CheckService.Services;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Material.Dtos;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.ThirdpartyPush;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.ThirdpartyPush.Dtos;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.ThirdpartyPush.Services;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Device;
using BPA.SAAS.Manage.Core.Product;
using Microsoft.AspNetCore.Components.Forms;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System.Drawing.Drawing2D;

namespace BPA.SAAS.Manage.Application.AExternalPlatform.Service.Material.Services
{
    public class MaterialService : IMaterialServices, ITransient
    {
        private readonly ICheckServices _checkServices;
        private readonly IThirdpartyPushService _thirdpartyPushService;
        public MaterialService(ICheckServices checkServices, IThirdpartyPushService thirdpartyPushService)
        {
            _checkServices = checkServices;
            _thirdpartyPushService = thirdpartyPushService;
        }

        /// <summary>
        /// 分页查询物料
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<PageUtil<List<MaterialDto>>> GetMaterialPageList(MaterialPageInputDto inputDto)
        {
            int total = new RefAsync<int>();
            var data = SqlSugarDb.Db.Queryable<BPA_Batching, BPA_BatchingType, BPA_BatchingUint>((a, b, c) =>
                new JoinQueryInfos(JoinType.Left, a.Batching_Type == b.Id,
                    JoinType.Left, a.StockUint == c.Id))
                .Where((a, b, c) => a.IsDeleted == 0)
                .WhereIF(!string.IsNullOrEmpty(inputDto.Name), (a, b, c) => a.Batching_Name.Contains(inputDto.Name))
                .Select((a, b, c) => new MaterialDto()
                {
                    Id = a.Id,
                    Code = a.Code,
                    Name = a.Batching_Name,
                    //TypeId = b.Id,
                    TypeName = b.Name,
                    // UintId = c.Id,
                    UintName = c.Name,

                }).ToPageList(inputDto.Current, inputDto.PageSize, ref total);

            return new PageUtil<List<MaterialDto>>()
            {
                Total = total,
                Data = data
            };
        }


        /// <summary>
        /// 添加物料
        /// </summary>
        /// <param name="InputDto"></param>
        /// <returns></returns>
        public async Task<string> AddMaterial(BaseRequestDto<MaterialCreateDto> inputDto)
        {
            try
            {

                var list=new List<BPA_Batching>();

                SqlSugarDb.Db.Ado.BeginTran();

                foreach (var item in inputDto.DataInfo)
                {
                    //1.物料单位查询
                    var typeData = await SqlSugarDb.Db.Queryable<BPA_BatchingType>().FirstAsync(x => x.Name == item.TypeName);
                    if (typeData == null)
                    {

                        typeData = new BPA_BatchingType()
                        {
                            GroupId = CurrentUser.GroupId,
                            Id = Guid.NewGuid().ToString(),
                            Name = string.IsNullOrEmpty(item.TypeName) ? "默认分类" : item.TypeName,
                        };
                        SqlSugarDb.Db.Insertable(typeData).ExecuteCommand();
                    }

                    //2.单位查询
                    var uintData = await SqlSugarDb.Db.Queryable<BPA_BatchingUint>()
                        .FirstAsync(x => x.Name == item.UintName);
                    if (uintData == null)
                    {
                        uintData = new BPA_BatchingUint()
                        {
                            GroupId = CurrentUser.GroupId,
                            Id = Guid.NewGuid().ToString(),
                            Name = string.IsNullOrEmpty(item.UintName) ? "默认分类" : item.UintName,
                        };
                        SqlSugarDb.Db.Insertable(uintData).ExecuteCommand();
                    }
                    //3.物料查询
                    var materialData = await SqlSugarDb.Db.Queryable<BPA_Batching>().FirstAsync(x => x.Batching_Name == item.Name || x.Code == item.Code);
                    if (materialData == null)
                    {
                        materialData = new BPA_Batching()
                        {
                            Id = Guid.NewGuid().ToString(),
                            GroupId = CurrentUser.GroupId,
                            Aittribute = 0,
                            Batching_Name = item.Name,
                            Batching_Type = typeData.Id,
                            Code = item.Code,
                            Price = 0,
                            Specs = "",
                            outstockUint = uintData.Id,
                            Status = CommonStatus.ENABLE,
                            StockUint = uintData.Id,
                            TypeID = typeData.Id,
                            IsDeleted = 0,
                        };

                        SqlSugarDb.Db.Insertable(materialData).ExecuteCommand();
                    }
                    else
                    {
                        throw Oops.Oh(ErrorCodeEnum.Code1002);
                    }
                    list.Add(materialData);
                }

                SqlSugarDb.Db.Ado.CommitTran();

                #region 下发数据到设备

                var data = new List<PushDataBatchingDto>();
                foreach (var item in list)
                {
                    data.Add(new PushDataBatchingDto()
                    {
                        Aittribute = item.Aittribute,
                        AutoKey = item.AutoKey,
                        Code = item.Code,
                        ForeignKeyRe = item.ForeignKeyRe,
                        Id = item.Id,
                        Name = item.Batching_Name,
                        netrecovery = item.netrecovery,
                        outstockUint = item.outstockUint,
                        Price = item.Price,
                        proportion = item.proportion,
                        Specs = item.Specs,
                        StockUint = item.StockUint,
                        StockUintName = item.StockUint,
                        TypeID = item.TypeID,
                    });
                }

                if (inputDto.IsPush)
                {
                    await _thirdpartyPushService.AddPushRecordAndPushDevice<MaterialCreateDto>(inputDto, 2, JsonConvert.SerializeObject(list.Select(x => x.Id).ToList()),
                        JsonConvert.SerializeObject(data));
                }


                #endregion

                return JsonConvert.SerializeObject(list.Select(x => x.Id).ToList());
            }
            catch (Exception e)
            {
                SqlSugarDb.Db.Ado.RollbackTran();
                throw Oops.Oh(e.Message);
            }
        }

        /// <summary>
        /// 删除物料
        /// </summary>
        /// <param name="MaterialId"></param>
        /// <returns></returns>
        public async Task<bool> DelMaterial(DelMaterialDto inputDto)
        {
            try
            {
                var materialData = await SqlSugarDb.Db.Queryable<BPA_Batching>().FirstAsync(x => x.Id == inputDto.MaterialId);
                if (materialData == null)
                {
                    throw Oops.Oh(ErrorCodeEnum.Code1003);
                }
                var res = await SqlSugarDb.Db.Deleteable(materialData).ExecuteCommandAsync();
                return res > 0;
            }
            catch (Exception e)
            {
                throw Oops.Oh(e.Message);
            }


        }

        /// <summary>
        /// 修改物料
        /// </summary>
        /// <param name="InputDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateMateria(BaseRequestDto<MaterialUpdateDto> inputDto)
        {
            try
            {
                SqlSugarDb.Db.Ado.BeginTran();

                if (inputDto.DataInfo.Count>1)
                {
                    throw Oops.Oh("不支持多物料修改");
                }

                var materia = inputDto.DataInfo.FirstOrDefault();


                //1.物料单位查询
                var typeData = await SqlSugarDb.Db.Queryable<BPA_BatchingType>().FirstAsync(x => x.Name == materia.TypeName);
                if (typeData == null)
                {

                    typeData = new BPA_BatchingType()
                    {
                        GroupId = CurrentUser.GroupId,
                        Id = Guid.NewGuid().ToString(),
                        Name = string.IsNullOrEmpty(materia.TypeName) ? "默认分类" : materia.TypeName,
                    };
                    SqlSugarDb.Db.Insertable(typeData).ExecuteCommand();
                }

                //2.单位查询
                var uintData = await SqlSugarDb.Db.Queryable<BPA_BatchingUint>()
                    .FirstAsync(x => x.Name == materia.UintName);
                if (uintData == null)
                {
                    uintData = new BPA_BatchingUint()
                    {
                        GroupId = CurrentUser.GroupId,
                        Id = Guid.NewGuid().ToString(),
                        Name = string.IsNullOrEmpty(materia.UintName) ? "默认分类" : materia.UintName,
                    };
                    SqlSugarDb.Db.Insertable(uintData).ExecuteCommand();
                }
                //3.物料查询
                var material = await SqlSugarDb.Db.Queryable<BPA_Batching>().FirstAsync(x => x.Code == materia.Code || x.Batching_Name == materia.Name);
               // if(material==null) throw Oops.Oh(ErrorCodeEnum.Code1003);
                var materialData = await SqlSugarDb.Db.Queryable<BPA_Batching>().FirstAsync(x => x.Id == materia.Id);

                if (materialData == null)
                {
                    throw Oops.Oh(ErrorCodeEnum.Code1003);
                }
                else
                {
                    if (material != null && material.Id != materialData.Id)
                    {
                        throw Oops.Oh(ErrorCodeEnum.Code10017);
                    }

                    materialData = new BPA_Batching()
                    {
                        Id = materia.Id,
                        GroupId = CurrentUser.GroupId,
                        Aittribute = 0,
                        Batching_Name = materia.Name,
                        Batching_Type = typeData.Id,
                        Code = materia.Code,
                        Price = 0,
                        Specs = "",
                        outstockUint = uintData.Id,
                        Status = CommonStatus.ENABLE,
                        StockUint = uintData.Id,
                        TypeID = typeData.Id,
                        IsDeleted = 0,
                    };
                    SqlSugarDb.Db.Updateable(materialData).ExecuteCommand();
                }
                SqlSugarDb.Db.Ado.CommitTran();
                #region 下发数据到设备

                var data = new PushDataBatchingDto()
                {
                    Aittribute = materialData.Aittribute,
                    AutoKey = materialData.AutoKey,
                    Code = materialData.Code,
                    ForeignKeyRe = materialData.ForeignKeyRe,
                    Id = materialData.Id,
                    Name = materialData.Batching_Name,
                    netrecovery = materialData.netrecovery,
                    outstockUint = materialData.outstockUint,
                    Price = materialData.Price,
                    proportion = materialData.proportion,
                    Specs = materialData.Specs,
                    StockUint = materialData.StockUint,
                    StockUintName = materialData.StockUint,
                    TypeID = materialData.TypeID,
                };
                if (inputDto.IsPush)
                {
                    await _thirdpartyPushService.AddPushRecordAndPushDevice<MaterialUpdateDto>(inputDto, 2, materialData.Id,
                        JsonConvert.SerializeObject(data));
                }


                #endregion
                return true;
            }
            catch (Exception e)
            {
                SqlSugarDb.Db.Ado.RollbackTran();
                throw Oops.Oh(e.Message);
            }
        }
    }
}
