using Mapster;

namespace SlnMesnac.WCS.Library
{
    public class CoreMapper
    {
        /// <summary>
        /// Map source object to destination object
        /// </summary>
        /// <typeparam name="TDestination"> The type of the destination. </typeparam>
        /// <param name="source"> The source object. </param>
        /// <returns>The destination object. </returns>
        /// <exception cref="ArgumentNullException"> Thrown when source is null. </exception>
        public static TDestination Map<TDestination>(object source)
        {
            if (source == null)
                throw new ArgumentNullException("Map Error : source is null");
            TypeAdapterConfig config = new TypeAdapterConfig();

            config.NewConfig<string, Guid>().MapWith(dest => string.IsNullOrEmpty(dest.Trim()) ? Guid.Empty : new Guid(dest));
            config.NewConfig<string, Guid?>().MapWith(dest => string.IsNullOrEmpty(dest.Trim()) ? null : new Guid(dest));
            config.NewConfig<Guid, string>().MapWith(dest => dest.ToString());

            config.NewConfig<string, DateTime>().MapWith(dest => string.IsNullOrEmpty(dest) ? DateTime.Now : Convert.ToDateTime(dest));
            config.NewConfig<string, DateTime?>().MapWith(dest => string.IsNullOrEmpty(dest) ? null : Convert.ToDateTime(dest));
            config.NewConfig<DateTime, string>().MapWith(dest => dest.ToString());
            //  var c = source.Adapt(destination, config2);
            config.NewConfig<string, string>().MapWith(dest => dest.Trim());
            // config.ForType<string, Guid>().Map(member: guid => guid, source: @string => string.IsNullOrEmpty(@string) ? Guid.Empty : new Guid(@string));
            //  config.ForType<Guid, String>().Map(member: @string => @string, source: guid => ("wode"));
            config.Default.IgnoreNullValues(true);//忽略null，原本的类字段的值是null，映射出来是"",int? null
            config.Default.NameMatchingStrategy(NameMatchingStrategy.IgnoreCase);//忽略大小写
            var destination = source.Adapt<TDestination>(config);
            return destination;
        }
    }
}