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.Comm.Enum;
using BPA.SAAS.Manage.Core;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using Microsoft.AspNetCore.Components.Forms;

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

        /// <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<bool> AddMaterial(MaterialCreateDto inputDto)
        {

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

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

                //2.单位查询
                var uintData = await SqlSugarDb.Db.Queryable<BPA_BatchingUint>()
                    .FirstAsync(x => x.Name == inputDto.UintName);
                if (uintData == null)
                {
                    uintData = new BPA_BatchingUint()
                    {
                        GroupId = CurrentUser.GroupId,
                        Id = Guid.NewGuid().ToString(),
                        Name = string.IsNullOrEmpty(inputDto.UintName) ? "默认分类" : inputDto.UintName,
                    };
                    SqlSugarDb.Db.Insertable(uintData).ExecuteCommand();
                }
                //3.物料查询
                var materialData = await SqlSugarDb.Db.Queryable<BPA_Batching>().FirstAsync(x => x.Batching_Name == inputDto.Name);
                if (materialData == null)
                {
                    materialData = new BPA_Batching()
                    {
                        Id = Guid.NewGuid().ToString(),
                        GroupId = CurrentUser.GroupId,
                        Aittribute = 0,
                        Batching_Name = inputDto.Name,
                        Batching_Type = typeData.Id,
                        Code = inputDto.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);
                }


                SqlSugarDb.Db.Ado.CommitTran();
                return true;
            }
            catch (Exception e)
            {
                SqlSugarDb.Db.Ado.RollbackTran();
                throw Oops.Oh(ErrorCodeEnum.Code1001);
            }
        }

        /// <summary>
        /// 删除物料
        /// </summary>
        /// <param name="MaterialId"></param>
        /// <returns></returns>
        public async Task<bool> DelMaterial(DelMaterialDto inputDto)
        {
            

            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;
        }

        /// <summary>
        /// 修改物料
        /// </summary>
        /// <param name="InputDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateMateria(MaterialUpdateDto inputDto)
        {
            try
            {
                

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

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

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


                }
                else
                {
                    materialData = new BPA_Batching()
                    {
                        Id = Guid.NewGuid().ToString(),
                        GroupId = CurrentUser.GroupId,
                        Aittribute = 0,
                        Batching_Name = inputDto.Name,
                        Batching_Type = typeData.Id,
                        Code = inputDto.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();
                return true;
            }
            catch (Exception e)
            {
                SqlSugarDb.Db.Ado.RollbackTran();
                throw Oops.Oh(ErrorCodeEnum.Code1001);
            }
        }
    }
}
