
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Autofac.Extras.DynamicProxy;
using Microsoft.AspNetCore.Http;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

using YC.Model;
using YC.Core;
using AutoMapper;
using System.Linq.Expressions;
using YC.Core.Attribute;
using YC.Core.Domain;
using YC.Core.Autofac;
using YC.Common.ShareUtils;
using YC.Core.Cache;
using YC.ApplicationService.DefaultConfigure;
using YC.FreeSqlFrameWork;
using YC.Core.DynamicApi;
using YC.Core.DynamicApi.Attributes;
using YC.Model.SysDbEntity;
using YC.ApplicationService.Dto;
using YC.Core.Domain.Output;


namespace YC.ApplicationService
{
    /// <summary>
    ///  <%=tableDisplayName%>业务实现接口
    /// </summary>
    public class <%=tableName%>AppService : FreeSqlBaseApplicationService, I<%=tableName%>AppService
    {
	private readonly IFreeSqlRepository<<%=tableName%>, <%=tempType%>> _<%=paramName%>FreeSqlRepository; 
        private readonly ICacheManager _cacheManager;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数自动注入我们所需要的类或接口
        /// </summary>
        public <%=tableName%>AppService(IFreeSqlRepository<<%=tableName%>,  <%=tempType%>> <%=paramName%>FreeSqlRepository,
        IHttpContextAccessor httpContextAccessor, ICacheManager cacheManager, IMapper mapper) : base(httpContextAccessor, cacheManager)
        {
            _<%=paramName%>FreeSqlRepository = <%=paramName%>FreeSqlRepository;
              _cacheManager = cacheManager;
           _mapper = mapper;
        }

        
        /// <summary>
        /// 通过Id查找数据对象
        /// </summary>
        /// <returns>返回数据集合</returns>
        
        public async Task<ApiResult<<%=tableName%>AddOrEditDto>> GetAsync(long id)
        {
            var res = new ApiResult<<%=tableName%>AddOrEditDto>();

            var entity = await _<%=paramName%>FreeSqlRepository.Select
            .WhereDynamic(id)
            .ToOneAsync();

            var entityDto = _mapper.Map<<%=tableName%>AddOrEditDto>(entity);
            return res.Ok(entityDto);
        }
        
        
        [HttpPost]
        public async Task<IApiResult> GetPage<%=tableName%>ListAsync(PageInput<PageInputDto> input)
        {
            Expression<Func<<%=tableName%>, bool>> exp = null;
            if (input.Filter != null)
            {
                //exp = a => a.Name.Contains(input.Filter.QueryString);
            }
            var list = await _<%=paramName%>FreeSqlRepository.Select.WhereIf(input.Filter.QueryString.NotNull(), exp)
                .Count(out var total).OrderByDescending(true, a => a.Id).Page(input.CurrentPage, input.PageSize)
                .ToListAsync();

             ///返回数据必须是明确实体，要不然可能存在json映射死循环
            var data = new PageOutput<<%=tableName%>AddOrEditDto>()
            {
                List = _mapper.Map<List<<%=tableName%>AddOrEditDto>>(list),
                Total = total
            };

           
            return ApiResult.Ok(data);
        }
        
         [HttpPost]
        public async Task<IApiResult> Create<%=tableName%>Async(<%=tableName%>AddOrEditDto input)
        {

            input.Id = "0";//做一个处理，要不然automapper 无法转换
            var entity = _mapper.Map<<%=tableName%>>(input);
            var obj = await _<%=paramName%>FreeSqlRepository.InsertAsync(entity);

            if (!(obj?.Id > 0))
            {
                return ApiResult.NotOk();
            }
            return ApiResult.Ok();
        }
        
        
        public async Task<IApiResult> Delete<%=tableName%>ByIdAsync(long id)
        {
            var result = false;
            if (id > 0)
            {
                result = (await _<%=paramName%>FreeSqlRepository.DeleteAsync(m => m.Id == id)) > 0;
            }

            return ApiResult.Result(result);
        }
        
        
         public async Task<IApiResult> Update<%=tableName%>Async(<%=tableName%>AddOrEditDto input)
        {
            if (string.IsNullOrWhiteSpace(input.Id)) {
                return ApiResult.NotOk("<%=tableDisplayName%>Id 不能为空!");
            }
            long id = Convert.ToInt64(input?.Id);

            var obj = await _<%=paramName%>FreeSqlRepository.GetAsync(id);
            if (!(obj?.Id > 0))
            {
                return ApiResult.NotOk("对象不存在！");
            }

            _mapper.Map(input, obj);
            await _<%=paramName%>FreeSqlRepository.UpdateAsync(obj);
          
            return ApiResult.Ok();
        }
	
	
	}
}