using CrazyStudio.Core.Common.Tools.Extensions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XPrintServer.Business.Dto;
using XPrintServer.Business.Services.Interface;
using XPrintServer.DataModel;
using XPrintServer.DataModel.Models;

namespace XPrintServer.Business.Services
{
    public class ModelPartService : SqlSugarRepository<ModelPart>, IBusinessService
    {
        public ModelPartService(ConnectionConfig config) : base(config)
        {
        }

        public async Task AddOrUpdateModelParts(List<ModelPart> modelParts)
        {
            if (modelParts.Any())
            {
                var deleteParts = await Context.Queryable<ModelPart>().Where(p => p.ModelId == modelParts[0].ModelId).OrderBy(p => p.Sort).SplitTable().ToListAsync().ConfigureAwait(false);
                await Context.Deleteable(deleteParts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
                await Context.Insertable(modelParts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
            }
        }

        public async Task<List<ModelPartDto>> GetModePartsFormModelId(Guid Id)
        {
            var parts = await Context.Queryable<ModelPart>().Where(p => p.ModelId == Id).OrderBy(p => p.Sort).SplitTable().Select(p => new ModelPartDto
            {
                Id = p.Id,
                Alpha = p.Alpha,
                Beta = p.Beta,
                Radius = p.Radius,
                AlphaStr = p.Alpha.ToString(),
                BetaStr = p.Beta.ToString(),
                RadiusStr = p.Radius.ToString(),
                CreateTime = p.CreateTime,
                IsCanEditColor = p.IsCanEditColor,
                IsCanEditPicture = p.IsCanEditPicture,
                MaskImageUrl = p.MaskImageUrl,
                MaskScale = p.MaskScale,
                ModelId = p.ModelId,
                PartColor = p.PartColor,
                PartName = p.PartName,
                PartKey = p.PartKey,
                ProductImageX = p.ProductImageX,
                ProductImageY = p.ProductImageY,
                ProductImageHeight = p.ProductImageHeight,
                ProductImageWidth = p.ProductImageWidth,
                Sort = p.Sort,
                UVWidth = p.UVWidth,
                UVX = p.UVX,
                UVY = p.UVY,
                UVHeight = p.UVHeight,
            }).ToListAsync().ConfigureAwait(false);
            return parts;
        }
    }
}
