using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.Manage.Application.AExternalPlatform.Enum;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.WarehouseTemplate.Dtos;
using BPA.SAAS.Manage.Application.Device.Interface;
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 LogicExtensions;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.AExternalPlatform.Service.WarehouseTemplate.Services
{
    public class WarehouseTemplateService : IWarehouseTemplateService, ITransient
    {
        public async Task<PageUtil> GetWarehouseTemplatePage(WarehouseTemplateQueryDto inputDto)
        {
            RefAsync<int> total = 0;
            var data = await SqlSugarDb.Db.Queryable<BPA_WarehouseTemplate, BPA_DeviceInfo, BPA_ProductVesion>((a, b, c) => new JoinQueryInfos(JoinType.Left, a.DeviceId == b.Id, JoinType.Left, b.ProductVersionId == c.Id))
                .WhereIF(!string.IsNullOrWhiteSpace(inputDto.TemplateName), (a, b, c) => a.TemplateName.Contains(inputDto.TemplateName))
                 .WhereIF(!string.IsNullOrWhiteSpace(inputDto.DeviceName), (a, b, c) => a.DeviceId.Contains(inputDto.DeviceName))
                 .Select((a, b, c) => new WarehouseTemplateView
                 {
                     Id = a.Id,
                     DeviceId = a.DeviceId,
                     DeviceName = b.DeviceName,
                     TemplateName = a.TemplateName,
                     CreateAt = a.CreateAt,
                     Count = c.ProductNumber,
                     ProductUrl = c.ProductUrl
                 })
                 .Mapper(x =>
                 {
                     x.WarehousePostion = SqlSugarDb.Db.Queryable<BPA_WarehousePostion,BPA_Batching>((a, b) => new JoinQueryInfos(JoinType.Left,a.BatchingId==b.Id)).Where((a, b) => a.TemplateId == x.Id).Select((a, b) => new WarehousePostionVewDto() { Id=a.Id.SelectAll(),BatchingName=b.Batching_Name}).ToList();
                 })
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .ToPageListAsync(inputDto.Current, inputDto.PageSize, total);

            return new PageUtil()
            {
                Data = data,
                Total = total

            };
        }
        public async Task<List<WarehouseTemplateView>> GetWarehouseTemplateList(WarehouseDevideId dto)
        {
            var total = new RefAsync<int>();
            var data = await SqlSugarDb.Db.Queryable<BPA_WarehouseTemplate, BPA_DeviceInfo, BPA_ProductVesion>((a, b, c) => new JoinQueryInfos(JoinType.Left, a.DeviceId == b.Id, JoinType.Left, b.ProductVersionId == c.Id))
                .WhereIF(!string.IsNullOrWhiteSpace(dto.DeviceId), (a, b, c) => a.DeviceId.Contains(dto.DeviceId))
                 .Select((a, b, c) => new WarehouseTemplateView
                 {
                     Id = a.Id,
                     DeviceId = a.DeviceId,
                     DeviceName = b.DeviceName,
                     TemplateName = a.TemplateName,
                     CreateAt = a.CreateAt,
                     Count = c.ProductNumber,
                     ProductUrl = c.ProductUrl
                 })
                 .Mapper(x =>
                 {
                     x.WarehousePostion = SqlSugarDb.Db.Queryable<BPA_WarehousePostion, BPA_Batching>((a, b) => new JoinQueryInfos(JoinType.Left, a.BatchingId == b.Id)).Where((a, b) => a.TemplateId == x.Id).Select((a, b) => new WarehousePostionVewDto() { Id = a.Id.SelectAll(), BatchingName = b.Batching_Name }).ToList();
                 })
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .ToListAsync();

            return data;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>

        public async Task<bool> AddWarehouseTemplate(WarehouseTemplatInsertDto inputDto)
        {
            try
            {
                SqlSugarDb.Db.Ado.BeginTran();
                if(string.IsNullOrWhiteSpace(inputDto.DeviceId)) throw Oops.Oh(ErrorCodeEnum.Code10019);
                if (string.IsNullOrWhiteSpace(inputDto.TemplateName)) throw Oops.Oh(ErrorCodeEnum.Code10020);
                var check = SqlSugarDb.Db.Queryable<BPA_WarehouseTemplate>().Where(x => x.TemplateName == inputDto.TemplateName).Any();
                if (check) throw Oops.Oh(ErrorCodeEnum.Code10018);
                var dev = SqlSugarDb.Db.Queryable<BPA_DeviceInfo>().Where(x => x.Id == inputDto.DeviceId).First();
                if (dev==null) throw Oops.Oh(ErrorCodeEnum.Code10012);
                var devvis = SqlSugarDb.Db.Queryable<BPA_ProductVesion>().Where(x => x.ProductId == dev.ProductId).First();
                 if(devvis != null && devvis.ProductNumber< inputDto.WarehousePostionData.Count) throw Oops.Oh("仓位数量不足");
                var res = await SqlSugarDb.Db.Insertable(new BPA_WarehouseTemplate
                {
                    DeviceId = inputDto.DeviceId,
                    TemplateName = inputDto.TemplateName,

                }).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                List<BPA_WarehousePostion> list = new();
                for (int i = 0; i < inputDto.WarehousePostionData.Count; i++)
                {
                    var tem = new BPA_WarehousePostion
                    {
                        TemplateId = res.Id,
                        Code = inputDto.WarehousePostionData[i].Code,
                        BatchingId = inputDto.WarehousePostionData[i].BatchingId,
                    };
                    list.Add(tem);
                }
                for (int i = 0; i < devvis.ProductNumber - inputDto.WarehousePostionData.Count; i++)
                {
                    var tem = new BPA_WarehousePostion
                    {
                        TemplateId = res.Id
                    };
                    list.Add(tem);
                }
                var res1 = await SqlSugarDb.Db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                SqlSugarDb.Db.Ado.CommitTran();
                return true;
            }
            catch (Exception e)
            {
                SqlSugarDb.Db.Ado.RollbackTran();
                throw Oops.Oh("添加失败," + e.Message);
            }

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public async Task<bool> UpdateWarehouseTemplate(WarehouseTemplatUpdateDto inputDto)
        {
            try
            {
                SqlSugarDb.Db.Ado.BeginTran();
                var check = SqlSugarDb.Db.Queryable<BPA_WarehouseTemplate>().Where(x => x.TemplateName == inputDto.TemplateName && x.Id!= inputDto.Id).Any();
                if (check) throw Oops.Oh(ErrorCodeEnum.Code10018);
                var model = SqlSugarDb.Db.Queryable<BPA_WarehouseTemplate>().Where(x => x.Id == inputDto.Id).First();
                model.TemplateName = inputDto.TemplateName;
                var res = await SqlSugarDb.Db.Updateable(model).ExecuteCommandAsync();
                var warehousePostion = SqlSugarDb.Db.Queryable<BPA_WarehousePostion>().Where(x => x.TemplateId == inputDto.Id).ToList();
                //await SqlSugarDb.Db.Deleteable(warehousePostion).ExecuteCommandAsync();
                List<BPA_WarehousePostion> list = new();
                for (int i = 0; i < inputDto.WarehousePostionData.Count; i++)
                {
                    var reentity=warehousePostion.Where(x => x.Id == inputDto.WarehousePostionData[i].Id).First();
                    reentity.Code = inputDto.WarehousePostionData[i].Code;
                    reentity.BatchingId = inputDto.WarehousePostionData[i].BatchingId;
                    list.Add(reentity);
                }
                var res1 = await SqlSugarDb.Db.Updateable(list).ExecuteCommandAsync();
                SqlSugarDb.Db.Ado.CommitTran();
                return res1>0;
            }
            catch (Exception)
            {
                SqlSugarDb.Db.Ado.RollbackTran();
                return false;
            }
        }
    }
}
