using ServiceStack;
using Yitter.IdGenerator;

namespace BPA.MES.Base.Application.Services
{
    /// <summary>
    /// 名    称 ：工艺路线服务 
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：2023/3/2 16:11:04 
    /// 描    述 ：CraftsInfo 工艺管理   FinalCraftSteps工艺步骤管理
    /// </summary>
    [ApiDescriptionSettings("成品工艺管理", Order = 0, Tag = "工艺服务", Name = "FinalCraftSteps", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class FinalCraftStepsService : IFinalCraftStepsService, ITransient, IDynamicApiController
    {
        private readonly ISqlSugarClient _dbContext;
        public FinalCraftStepsService(ISqlSugarClient db)
        {
            _dbContext = db;
        }
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> Add(FinalCraftStepsAddInput input)
        {


            var deviceInfo = await _dbContext.Queryable<Pztj_DevicesInfoEntity>().Where(x => x.Code==input.DeviceId).FirstAsync();
            var LineInfo = await _dbContext.Queryable<ProductLineStepsEntity>().Where(x => x.Id==input.ProductLineStepsId).FirstAsync();
            FinalCraftStepsEntity entity = input.Adapt<FinalCraftStepsEntity>();
            var step = await _dbContext.Queryable<FinalCraftStepsEntity>().Where(x => x.FinalId==input.FinalId
           && x.ProductLineStepsId == input.ProductLineStepsId
           && x.DeviceId == input.DeviceId
           && x.LineId == LineInfo.LineId
           ).MaxAsync(x => x.Step);
            entity.Step = step+1;
            entity.LineId = LineInfo.LineId;
            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(FinalCraftStepsDelInput input)
        {
            var stepItem = await _dbContext.Queryable<FinalCraftStepsEntity>().Where(x => x.Id == input.Id).FirstAsync();
            string finalId = stepItem.FinalId;
            int step = stepItem.Step;
            var res = await _dbContext.Deleteable<FinalCraftStepsEntity>().Where(x => x.Id == input.Id).ExecuteCommandHasChangeAsync();
            if (res)
            {
                var stepList = await _dbContext.Queryable<FinalCraftStepsEntity>().Where(x => x.FinalId == finalId).OrderBy(x => x.Step).ToListAsync();
                for (int i = 0; i < stepList.Count; i++)
                {
                    stepList[i].Step = i + 1;
                }
                await _dbContext.Updateable(stepList).ExecuteCommandAsync();
            }
            return res;
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<FinalCraftStepsOutput> Detail(string Id)
        {
            var entity = await _dbContext.Queryable<FinalCraftStepsEntity>().FirstAsync(x => x.Id == Id);
            FinalCraftStepsOutput output = entity.Adapt<FinalCraftStepsOutput>();
            return output;
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<List<FinalCraftStepsOutput>> List(FinalCraftStepsQueryInput input)
        {
            var output = await _dbContext.Queryable<FinalCraftStepsEntity>()
                .LeftJoin<DeviceProductFunctionEntity>((a, b) => a.DeviceProductFunctionId==b.Id)
                 .LeftJoin<Pztj_DevicesInfoEntity>((a, b, c) => a.DeviceId==c.Code)
                 .LeftJoin<DeviceProductEntity>((a, b, c, d) => c.DeviceType==d.Id)
                 .LeftJoin<ProductLineStepsEntity>((a, b, c, d, e) => a.ProductLineStepsId==e.Id)
                 .LeftJoin<ProcessEntity>((a, b, c, d, e, f) => e.ProcessId==f.Id)
            .WhereIF(!string.IsNullOrEmpty(input.FinalId), (a, b, c, d) => a.FinalId == input.FinalId)
            .WhereIF(!string.IsNullOrEmpty(input.LineId), (a, b, c, d) => a.LineId == input.LineId)
            .WhereIF(!string.IsNullOrEmpty(input.DeviceId), (a, b, c, d) => c.Code == input.DeviceId)
            .WhereIF(!string.IsNullOrEmpty(input.ProductLineStepsId), (a, b, c, d) => a.ProductLineStepsId == input.ProductLineStepsId)
            .OrderBy((a, b, c, d) => a.Step)
                .Select((a, b, c, d, e, f) => new FinalCraftStepsOutput
                {
                    Id = a.Id.SelectAll(),
                    DeviceProductFunctionName = b.Name,
                    DeviceProductFunctionId = a.DeviceProductFunctionId,
                    DeviceProductId = b.DeviceProductId,
                    DeviceTypeName = d.Name,
                    DeviceName = c.Name,
                    ProductLineStepsName = f.Name,
                    DeviceFunParams = b.Params,
                    DeviceStepParms = a.Params
                }).ToListAsync();
            return output;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<FinalCraftStepsOutput>> PagedList(FinalCraftStepsQueryPageInput input)
        {
            var output = await _dbContext.Queryable<FinalCraftStepsEntity>()
                .LeftJoin<DeviceProductFunctionEntity>((a, b) => a.DeviceProductFunctionId==b.Id)
                .WhereIF(!string.IsNullOrEmpty(input.FinalId), (a, b) => a.FinalId == input.FinalId)
                .OrderBy((a, b) => a.Step)
                .Select((a, b) => new FinalCraftStepsOutput
                {
                    Id = a.Id.SelectAll(),
                    DeviceProductFunctionName = b.Name,
                    DeviceProductFunctionId = a.DeviceProductFunctionId,
                    DeviceProductId = b.DeviceProductId
                })
                .ToPagedListAsync(input.PageIndex, input.PageSize);
            return output;
        }
        /// <summary>
        /// 下拉
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<dynamic> SelectList()
        {
            var entity = await _dbContext.Queryable<FinalCraftStepsEntity>().Select(x => new
            {
                key = x.Id,
                value = x.Description
            }).ToListAsync();
            return entity;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<bool> Update(FinalCraftStepsUpdateInput input)
        {
            FinalCraftStepsEntity entity = input.Adapt<FinalCraftStepsEntity>();
            var res = await _dbContext.Updateable(entity).IgnoreColumns(it => it.Step).IgnoreColumns(it => it.DeviceId).IgnoreColumns(true).ExecuteCommandHasChangeAsync();
            return res;
        }
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> BatchUpdate(List<FinalCraftStepsUpdateInput> inputs)
        {
            List<FinalCraftStepsEntity> entity = inputs.Adapt<List<FinalCraftStepsEntity>>();
            var res = await _dbContext.Updateable(entity).ExecuteCommandHasChangeAsync();
            return res;
        }
        /// <summary>
        /// 复制设备的工艺步骤信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> CopyFinalCraftSteps(CopyFinalCraftStepsInput input)
        {
            var m_entity = await _dbContext.Queryable<FinalCraftStepsEntity>()
                .Where(x => x.FinalId==input.FinalId && x.DeviceId==input.CopyDeviceId&&x.ProductLineStepsId==input.ProductLineStepsId&&x.LineId==input.LineId).ToListAsync();
            foreach (var entity in m_entity)
            {
                entity.DeviceId = input.ToDeviceId;
                entity.Id = YitIdHelper.NextId().ToString();
            }
            var res = await _dbContext.Insertable(m_entity).ExecuteCommandIdentityIntoEntityAsync();
            return res;
        }
    }
}

