using ServiceStack;

namespace BPA.MES.Base.Application.Services
{
    /// <summary>
    /// 名    称 ：成品管理服务 
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：2023/3/2 16:11:04 
    /// 描    述 ：基础数据管理 
    /// </summary>
    [ApiDescriptionSettings("基础数据管理", Order = 4, Name = "FinalsInfo", Tag = "成品管理服务", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class FinalsInfoService : IFinalsInfoService, ITransient, IDynamicApiController
    {
        private readonly ISqlSugarClient _dbContext;
        public FinalsInfoService(ISqlSugarClient db)
        {
            _dbContext = db;
        }
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> Add(FinalsInfoAddInput input)
        {
            var r_entity = await _dbContext.Queryable<Pztj_FinalsInfoEntity>().FirstAsync(x => x.Name == input.Name);
            if (r_entity != null)
            {
                throw Oops.Bah("名称已存在!");
            }
            Pztj_FinalsInfoEntity entity = input.Adapt<Pztj_FinalsInfoEntity>();
            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(FinalsInfoDelInput input)
        {
            var res = await _dbContext.Deleteable<Pztj_FinalsInfoEntity>().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<FinalsInfoOutput> Detail(string Id)
        {
            var entity = await _dbContext.Queryable<Pztj_FinalsInfoEntity>().FirstAsync(x => x.Id == Id);
            FinalsInfoOutput output = entity.Adapt<FinalsInfoOutput>();
            return output;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<List<FinalsInfoOutput>> List()
        {
            var entity = await _dbContext.Queryable<Pztj_FinalsInfoEntity>().ToListAsync();
            List<FinalsInfoOutput> output = entity.Adapt<List<FinalsInfoOutput>>();
            return output;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<FinalsInfoOutput>> PagedList(FinalsInfoQueryPageInput input)
        {
            var output = await _dbContext.Queryable<Pztj_FinalsInfoEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.Name), a => a.Name.Contains(input.Name))
                .WhereIF(!string.IsNullOrEmpty(input.Code), a => a.Code.Contains(input.Code))
                 .Select((a) => new FinalsInfoOutput
                 {
                     Id = a.Id.SelectAll()
                 })
                .ToPagedListAsync(input.PageIndex, input.PageSize);
            foreach (var item in output.Items)
            {
                var finallist = await _dbContext.Queryable<FinalLineEntity>().Where(x => x.FinalId==item.Id).ToListAsync();
                item.LineId = finallist.Select(e => e.LineId).ToArray();
            }
            return output;
        }
        /// <summary>
        /// 下拉
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<dynamic> SelectList()
        {
            var entity = await _dbContext.Queryable<Pztj_FinalsInfoEntity>().Select(x => new
            {
                key = x.Id,
                value = x.Name
            }).ToListAsync();
            return entity;
        }
        /// <summary>
        /// 根据成品获取产线
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<dynamic> LineList(string finalId)
        {
            var entity = await _dbContext.Queryable<FinalLineEntity>()
                .LeftJoin<ProductLineEntity>((a, b) => a.LineId==b.Id)
                .Where((a, b) => a.FinalId == finalId)
                .Select((a, b) => new
                {
                    key = a.LineId,
                    value = b.Name,
                    status = a.Status
                }).ToListAsync();
            return entity;
        }
        /// <summary>
        /// 根据成品获取配置完成的产线
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<dynamic> FinishLineList(string finalId)
        {
            var entity = await _dbContext.Queryable<FinalLineEntity>()
                .LeftJoin<ProductLineEntity>((a, b) => a.LineId==b.Id)
                .Where((a, b) => a.FinalId == finalId && a.Status=="1")
                .Select((a, b) => new
                {
                    key = a.LineId,
                    value = b.Name,
                    status = a.Status
                }).ToListAsync();
            return entity;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<bool> Update(FinalsInfoUpdateInput input)
        {
            var entity = await _dbContext.Queryable<Pztj_FinalsInfoEntity>().FirstAsync(x => x.Id != input.Id && x.Name == input.Name);
            if (entity != null)
            {
                throw Oops.Bah("名称已存在!");
            }
            Pztj_FinalsInfoEntity r_entity = input.Adapt<Pztj_FinalsInfoEntity>();
            var res = await _dbContext.Updateable(r_entity).IgnoreColumns(true).ExecuteCommandHasChangeAsync();
            return res;
        }
        /// <summary>
        /// 绑定产线
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> BindLine(BindLineInput input)
        {
            bool result = false;
            List<FinalLineEntity> entitys = new();
            foreach (var item in input.LineId)
            {
                FinalLineEntity finalLine = new();
                finalLine.FinalId=input.FinalId;
                finalLine.LineId = item;
                finalLine.Status = "0";
                entitys.Add(finalLine);
            }
            try
            {
                _dbContext.Ado.BeginTran();
                await _dbContext.Deleteable<FinalLineEntity>().Where(x => x.FinalId == input.FinalId).ExecuteCommandAsync();
                await _dbContext.Insertable(entitys).ExecuteCommandAsync();
                _dbContext.Ado.CommitTran();
                result = true;
            }
            catch (Exception ex)
            {
                _dbContext.Ado.RollbackTran();
                throw Oops.Bah("保存失败!");
            }
            return result;
        }
        /// <summary>
        /// 保存产线配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> SaveConfigStatus(SaveFinalConfigStatusInput input)
        {
            var result = await _dbContext.Updateable<FinalLineEntity>().SetColumns(x=>x.Status=="1").Where(x => x.FinalId == input.FinalId && x.LineId==input.LineId).ExecuteCommandHasChangeAsync();
            return result;
        }
        /// <summary>
        /// 取消产线配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> CancelConfigStatus(SaveFinalConfigStatusInput input)
        {
            var result = await _dbContext.Updateable<FinalLineEntity>().SetColumns(x => x.Status=="0").Where(x => x.FinalId == input.FinalId && x.LineId==input.LineId).ExecuteCommandHasChangeAsync();
            return result;
        }
    }
}

