using ServiceStack;

namespace BPA.MES.Base.Application.Services
{
    /// <summary>
    /// 名    称 ：产线服务 
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：2023/3/2 16:11:04 
    /// 描    述 ：基础数据管理 
    /// </summary>
    [ApiDescriptionSettings("产线管理", Order = 0, Name = "ProductLine", Tag = "产线服务", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class ProductLineService : IProductLineService, ITransient, IDynamicApiController
    {
        private readonly ISqlSugarClient _dbContext;
        public ProductLineService(ISqlSugarClient db)
        {
            _dbContext = db;
        }
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> Add(ProductLineAddInput input)
        {
            var r_entity = await _dbContext.Queryable<ProductLineEntity>().FirstAsync(x => x.Name == input.Name);
            if (r_entity != null)
            {
                throw Oops.Bah("名称已存在!");
            }
            ProductLineEntity entity = input.Adapt<ProductLineEntity>();
            return await _dbContext.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandIdentityIntoEntityAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<bool> Del(ProductLineDelInput input)
        {
            var res = await _dbContext.Deleteable<ProductLineEntity>().Where(x => x.Id == input.Id).ExecuteCommandHasChangeAsync();
            return res;
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<ProductLineOutput> Detail(string Id)
        {
            var entity = await _dbContext.Queryable<ProductLineEntity>().FirstAsync(x => x.Id == Id);
            ProductLineOutput output = entity.Adapt<ProductLineOutput>();
            return output;
        }
      
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<List<ProductLineOutput>> List()
        {
            var entity = await _dbContext.Queryable<ProductLineEntity>().ToListAsync();
            List<ProductLineOutput> output = entity.Adapt<List<ProductLineOutput>>();
            return output;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<ProductLineOutput>> PagedList(ProductLineQueryPageInput input)
        {
            var entity = await _dbContext.Queryable<ProductLineEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.Name), x => x.Name.Contains(input.Name))
                .WhereIF(!string.IsNullOrEmpty(input.Code), x => x.Code.Contains(input.Code))
                .ToPagedListAsync(input.PageIndex, input.PageSize);
            SqlSugarPagedList<ProductLineOutput> output = entity.Adapt<SqlSugarPagedList<ProductLineOutput>>();
            return output;
        }
        /// <summary>
        /// 下拉
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<dynamic> SelectList()
        {
            var entity = await _dbContext.Queryable<ProductLineEntity>().Select(x => new
            {
                key = x.Id,
                value = x.Name
            }).ToListAsync();
            return entity;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<bool> Update(ProductLineUpdateInput input)
        {
            var isExit =await _dbContext.Queryable<ProductLineEntity>().Where(x => x.Id != input.Id && (x.Name == input.Name)).FirstAsync();
            if (isExit != null)
            {
                throw Oops.Bah("名称或编码已存在!");
            }
            ProductLineEntity entity = input.Adapt<ProductLineEntity>();
            var res = await _dbContext.Updateable(entity).IgnoreColumns(x=>x.CreateTime).ExecuteCommandHasChangeAsync();
            return res;
        }
        /// <summary>
        /// 产线添加设备
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> AddDevice(ProductLineDeviceAddInput input)
        {
            var r_entity = await _dbContext.Queryable<Pztj_LineDevicesEntity>().FirstAsync(x => x.DeviceId == input.DeviceId);
            if (r_entity != null)
            {
                throw Oops.Bah("设备已存在!");
            }
            Pztj_LineDevicesEntity entity = input.Adapt<Pztj_LineDevicesEntity>();
            return await _dbContext.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandIdentityIntoEntityAsync();
        }
        /// <summary>
        /// 产线添加设备
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> AddBatchDevice(ProductLineDeviceBatchAddInput input)
        {

            bool result = false;
            List<Pztj_LineDevicesEntity> entitys = new();
            foreach (var item in input.DeviceId)
            {
                Pztj_LineDevicesEntity entity = new();
                entity.LineId = input.LineId;
                entity.StepId = input.Id;
                entity.DeviceId = item;
                entitys.Add(entity);
            }
          
            try
            {
                _dbContext.Ado.BeginTran();
                await _dbContext.Deleteable<Pztj_LineDevicesEntity>().Where(x => x.LineId == input.LineId && x.StepId==input.Id).ExecuteCommandAsync();
                await _dbContext.Insertable(entitys).ExecuteCommandAsync();
                _dbContext.Ado.CommitTran();
                result = true;
            }
            catch (Exception ex)
            {
                _dbContext.Ado.RollbackTran();
                throw Oops.Bah("保存失败!");
            }
            return result;
        }
        /// <summary>
        /// 产线删除设备
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> DeleteDevice(ProductLineDeviceDelInput input)
        {
            var res = await _dbContext.Deleteable<Pztj_LineDevicesEntity>().Where(x => x.Id == input.Id).ExecuteCommandHasChangeAsync();
            return res;
        }
        /// <summary>
        /// 产线设备不分页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<ProductLineDeviceOutput>> DeviceList(ProductLineDeviceQueryInput input)
        {
            var output = await _dbContext.Queryable<Pztj_LineDevicesEntity>()
                 .LeftJoin<Pztj_DevicesInfoEntity>((a, b) => a.DeviceId == b.Id)
                 .WhereIF(!string.IsNullOrEmpty(input.Name), (a, b) => b.Name.Contains(input.Name))
                .WhereIF(!string.IsNullOrEmpty(input.LineId), (a, b) => a.LineId == input.LineId)
                 .WhereIF(!string.IsNullOrEmpty(input.StepId), (a, b) => a.StepId == input.StepId)
                 .Select((a, b) => new ProductLineDeviceOutput
                 {
                     DeviceId = a.DeviceId,
                     DeviceCode = b.Code,
                     DeviceName = b.Name,
                     Describe = b.Describe,
                     DeviceType = b.DeviceType,
                     Id = a.Id,
                     LineId = a.LineId,
                     StepId = a.StepId
                 }).
                ToListAsync();
            return output;
        }
        /// <summary>
        /// 产线设备分页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<ProductLineDeviceOutput>> DevicePageList(ProductLineDeviceQueryPageInput input)
        {
            var entity = await _dbContext.Queryable<Pztj_LineDevicesEntity>()
                .LeftJoin<Pztj_DevicesInfoEntity>((a,b)=>a.DeviceId==b.Id)
                .WhereIF(!string.IsNullOrEmpty(input.Name), (a, b) => b.Name.Contains(input.Name))
               .WhereIF(!string.IsNullOrEmpty(input.LineId), (a, b) => a.LineId == input.LineId)
                .Select((a,b)=>new ProductLineDeviceOutput
                {
                    DeviceId = a.DeviceId,
                    DeviceCode = b.Code,
                    DeviceName = b.Name,
                    Describe = b.Describe,
                    DeviceType = b.DeviceType,
                    Id = a.Id,
                    LineId = a.LineId
                })
                .ToPagedListAsync(input.PageIndex, input.PageSize);
            return entity;
        }


        /// <summary>
        /// 产线添加料仓
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> AddStock(ProductLineStockAddInput input)
        {
            var r_entity = await _dbContext.Queryable<Pztj_LineStocksEntity>().FirstAsync(x => x.StockId == input.StockId);
            if (r_entity != null)
            {
                throw Oops.Bah("设备已存在!");
            }
            Pztj_LineStocksEntity entity = input.Adapt<Pztj_LineStocksEntity>();
            return await _dbContext.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandIdentityIntoEntityAsync();
        }
        /// <summary>
        /// 产线删除料仓
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> DeleteStock(ProductLineStockDelInput input)
        {
            var res = await _dbContext.Deleteable<Pztj_LineStocksEntity>().Where(x => x.Id == input.Id).ExecuteCommandHasChangeAsync();
            return res;
        }
        /// <summary>
        /// 产线料仓不分页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<ProductLineStockOutput>> StockList(ProductLineStockQueryInput input)
        {
            var entity = await _dbContext.Queryable<Pztj_LineStocksEntity>()
                .LeftJoin<Pztj_StockInfoEntity>((a, b) => a.StockId == b.Id)
                .LeftJoin<Pztj_MaterialsInfoEntity>((a, b,c) => b.MaterialId == c.Id)
                .WhereIF(!string.IsNullOrEmpty(input.MaterialId), (a, b) => b.MaterialId == input.MaterialId)
                .WhereIF(!string.IsNullOrEmpty(input.LineId), (a, b) => a.LineId == input.LineId)
                .Select((a, b,c) => new ProductLineStockOutput
                {
                    Id = a.Id,
                    LineId = a.LineId,
                    StockCode = b.Code,
                    StockId = b.Id,
                    StockName = b.Name,
                    MaterialId = b.MaterialId,
                    MateriaName = c.Name
                })
                .ToListAsync();
            return entity;
        }
        /// <summary>
        /// 产线料仓分页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<ProductLineStockOutput>> StockPageList(ProductLineStockQueryPageInput input)
        {
            var entity = await _dbContext.Queryable<Pztj_LineStocksEntity>()
                .LeftJoin<Pztj_StockInfoEntity>((a, b) => a.StockId == b.Id)
                .WhereIF(!string.IsNullOrEmpty(input.Name), (a, b) => b.Name.Contains(input.Name))
                .WhereIF(!string.IsNullOrEmpty(input.LineId), (a, b) => a.LineId == input.LineId)
                .Select((a, b) => new ProductLineStockOutput
                {
                    StockId = a.StockId,
                    StockCode = b.Code,
                    StockName = b.Name,
                    Id = a.Id,
                    LineId = a.LineId
                })
                .ToPagedListAsync(input.PageIndex, input.PageSize);
            return entity;
        }
    }
}

