using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.Manage.Application.AExternalPlatform.BaseDto;
using BPA.SAAS.Manage.Application.AExternalPlatform.Enum;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Bom.Dtos;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Material.Dtos;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.ThirdpartyPush.Dtos;
using BPA.SAAS.Manage.Application.DataBase.Dtos.Bom;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Device;
using Microsoft.AspNetCore.Components.Forms;
using Newtonsoft.Json;
using NPOI.XWPF.UserModel;
using SixLabors.ImageSharp.PixelFormats;

namespace BPA.SAAS.Manage.Application.AExternalPlatform.Service.Bom.Services
{
    public class BomService: IBomService, ITransient
    {  
        public BomService()
        {

        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<PageUtil<List<BomDto>>> GetBomPageList(BomPageQueryDto inputDto)
        {
            int total = new RefAsync<int>();
            var data = SqlSugarDb.Db.Queryable<BPA_Bom>()
                .WhereIF(!string.IsNullOrWhiteSpace(inputDto.Name),x=>x.Name.Contains(inputDto.Name))
                .Select(a => new BomDto()
                {
                    Id = a.Id.SelectAll(),
                })
                .Mapper(x =>
                {
                    var list=SqlSugarDb.Db.Queryable<BPA_BomEntry, BPA_Batching>((a,b)=> new JoinQueryInfos(JoinType.Left, a.BatchingId == b.Id)).Where((a,b)=>a.BomId==x.Id).Select((a,b)=>new BomEntr
                    {
                        Id=a.Id,
                        BatchingId=a.BatchingId,
                        BomQty=a.BomQty,
                        BomId=a.BomId,
                        Sort=a.sort,
                        BatchingName=b.Batching_Name
                    }).ToList();
                    x.BomEntr = list;
                })
                .ToPageList(inputDto.Current, inputDto.PageSize, ref total);

            return new PageUtil<List<BomDto>>()
            {
                Total = total,
                Data = data
            };
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddBom(BaseRequestDto<BomInsertDto> dto)
        {
            try
            {
                SqlSugarDb.Db.BeginTran();
                List<BPA_Bom> list = new();
                List<BPA_BomType> BomTypelist = new();
                List<BPA_BomTypeInfo> BomTypeInfolist = new();
                for (int i = 0; i < dto.DataInfo.Count; i++)
                {
                    var resEntity = new BPA_Bom();
                    resEntity.Id = Guid.NewGuid().ToString();
                    resEntity.Name = dto.DataInfo[i].Name;
                    resEntity.IsMain = dto.DataInfo[i].IsMain;
                    resEntity.Sort = dto.DataInfo[i].Sort;
                    resEntity.Code = GetNumber2(8);
                    list.Add(resEntity);
                    if (!string.IsNullOrEmpty(dto.DataInfo[i].BomTypeName))
                    {
                        var check = SqlSugarDb.Db.Queryable<BPA_BomType>().Where(x => x.Name == dto.DataInfo[i].BomTypeName).First();
                        if (check == null)
                        {
                            var BomType = new BPA_BomType() { Id = Guid.NewGuid().ToString(),Name = dto.DataInfo[i].BomTypeName};
                            BomTypelist.Add(BomType);
                            BPA_BomTypeInfo _BomTypeInfo = new();
                            _BomTypeInfo.Id = Guid.NewGuid().ToString();
                            _BomTypeInfo.BomId = resEntity.Id;
                            _BomTypeInfo.BomTypeId = BomType.Id;
                            BomTypeInfolist.Add(_BomTypeInfo);
                        }
                        else
                        {
                            BPA_BomTypeInfo _BomTypeInfo = new();
                            _BomTypeInfo.Id = Guid.NewGuid().ToString();
                            _BomTypeInfo.BomId = resEntity.Id;
                            _BomTypeInfo.BomTypeId = check.Id;
                            BomTypeInfolist.Add(_BomTypeInfo);
                        }
                    }
                }
                await SqlSugarDb.Db.Insertable(list).ExecuteCommandAsync();
                await SqlSugarDb.Db.Insertable(BomTypelist).ExecuteCommandAsync();
                await SqlSugarDb.Db.Insertable(BomTypeInfolist).ExecuteCommandAsync();
                SqlSugarDb.Db.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 true;
            }
            catch (Exception)
            {
                SqlSugarDb.Db.RollbackTran();
                throw Oops.Oh(ErrorCodeEnum.Code1007);
            }

        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateBom(BaseRequestDto<BomUpdateDto> dto)
        {
            if (dto.DataInfo.Count > 1) throw Oops.Oh("不支持多条商品修改");
            var list = new List<BPA_Bom>();
            for (int i = 0; i < dto.DataInfo.Count; i++)
            {
                var resEntity = SqlSugarDb.Db.Queryable<BPA_Bom>().Where(it => it.IsDeleted == 0).First(it => it.Id == dto.DataInfo[i].Id);
                if (resEntity != null)
                {
                    resEntity.Name = dto.DataInfo[i].Name;
                    resEntity.IsMain = dto.DataInfo[i].IsMain;
                    resEntity.Sort = dto.DataInfo[i].Sort;
                    list.Add(resEntity);
                }
            }
            var res = await SqlSugarDb.Db.Updateable(list).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteBom(DeleteBomDto dto)
        {
            try
            {
                SqlSugarDb.Db.BeginTran();
                var ids= dto.Ids;
                var goods = SqlSugarDb.Db.Queryable<BPA_Bom>().Where(x => ids.Contains(x.Id)).ToList();
                if (goods == null) throw Oops.Oh(ErrorCodeEnum.Code10015);
                var goodsbom = SqlSugarDb.Db.Queryable<BPA_BomEntry>().Where(x => ids.Contains(x.BomId)).ToList();
                await SqlSugarDb.Db.Deleteable(goodsbom).ExecuteCommandAsync();
                var res = await SqlSugarDb.Db.Deleteable(goods).ExecuteCommandAsync();
                SqlSugarDb.Db.CommitTran();
                return res > 0;
            }
            catch (Exception)
            {
                SqlSugarDb.Db.RollbackTran();
                throw Oops.Oh("删除失败");
            }

        }
        /// <summary>
        /// 根据配方id查询配方详情
        /// </summary>
        /// <param name="bomId"></param>
        /// <returns></returns>
        public async Task<List<BomEntryDto>> GetBomEntry(BomIdDto dto)
        {
            try
            {
                var resEntity=await SqlSugarDb.Db.Queryable<BPA_BomEntry, BPA_Bom,BPA_Batching>((a,b,c)=> new JoinQueryInfos(JoinType.Left, a.BomId == b.Id, JoinType.Left, a.BatchingId == c.Id))
                    .WhereIF(dto!=null && !string.IsNullOrWhiteSpace(dto.BomId), (a, b, c)=>b.Id== dto.BomId)
                    .Select((a, b, c)=> new BomEntryDto()
                    {
                        Id=a.Id,
                        BatchingId=a.BatchingId,
                        BomQty=a.BomQty,
                        Sort=a.sort,
                        BatchingName=c.Batching_Name,
                        BomId = a.BomId,
                        BomName=b.Name
                    }).ToListAsync();
               
                return resEntity;
            }
            catch (Exception)
            {
                throw Oops.Oh(ErrorCodeEnum.Code1007);
            }
        }
        /// <summary>
        /// 添加配方详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddBomEntry(BomEntryInsertDto dto)
        {
            try
            {
                var checkbatch=SqlSugarDb.Db.Queryable<BPA_Batching>().Where(x => x.Id == dto.BatchingId).Any();
                if (!checkbatch) throw Oops.Oh("找不到物料信息");
                var checkbom = SqlSugarDb.Db.Queryable<BPA_Bom>().Where(x => x.Id == dto.BomId).Any();
                if (!checkbom) throw Oops.Oh("找不到配方信息");
                var resEntity = new BPA_BomEntry();
                resEntity.BatchingId = dto.BatchingId;
                resEntity.BomId = dto.BomId;
                resEntity.BomQty = dto.BomQty;
                resEntity.sort = dto.Sort;
                var res = await SqlSugarDb.Db.Insertable(resEntity).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                return res > 0;
            }
            catch (Exception)
            {
                throw Oops.Oh(ErrorCodeEnum.Code1007);
            }
        }
        private string GetNumber2(int Length = 10)
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            var ram = BitConverter.ToInt64(buffer, 0);
            var str = string.Format("{0}", ram.ToString().Substring(0, Length));
            return str;
        }
    }
}
