using Hotline.Enterprise;
using Hotline.Share.Dtos.Enterprise;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Users;
using Hotline.Share.Dtos;
using Hotline.Tools;
using Microsoft.AspNetCore.Mvc;
using XF.Domain.Authentications;
using Hotline.Application.Enterprise;
using Hotline.Configurations;
using Hotline.Orders;
using Hotline.Repository.SqlSugar.Extensions;
using MapsterMapper;
using Microsoft.Extensions.Options;
using XF.Domain.Repository;
using Hotline.Api.Filter;

namespace Hotline.Api.Controllers
{
    /// <summary>
    /// 泸州企业专员工单管理
    /// </summary>
    public class EnterpriseLuzhouController : BaseController
    {
        private readonly IRepository<EnterpriseSpecialist> _enterpriseSpecialistRepository;
        private readonly IEnterpriseApplication _enterpriseApplication;
        private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
        private readonly ISessionContext _sessionContext;
        private readonly IMapper _mapper;

        public EnterpriseLuzhouController(
            IRepository<EnterpriseSpecialist> enterpriseSpecialistRepository,
            IEnterpriseApplication enterpriseApplication,
            IOptionsSnapshot<AppConfiguration> appOptions,
            ISessionContext sessionContext,
            IMapper mapper)
        {
            _enterpriseSpecialistRepository = enterpriseSpecialistRepository;
            _enterpriseApplication = enterpriseApplication;
            _appOptions = appOptions;
            _sessionContext = sessionContext;
            _mapper = mapper;
        }

        
        [HttpGet("specialist/users")]
        public async Task<PagedDto<UserDto>> QueryUsers([FromQuery] UserPagedDto request)
        {
            var query = _enterpriseApplication.QueryUsersForSpecialist(request);
            var (total, users) = await query.ToPagedListAsync(request);
            var userDtos = _mapper.Map<List<UserDto>>(users);
            return new PagedDto<UserDto>(total, userDtos);
        }

        /// <summary>
        /// 批量新增企业专员
        /// </summary>
        /// <returns></returns>
        [HttpPost("specialist-batch")]
        public async Task AddSpecialists([FromBody] List<AddEnterpriseSpecialistDto> dto)
        {
            var specialists = _mapper.Map<List<EnterpriseSpecialist>>(dto);
            await _enterpriseSpecialistRepository.AddRangeAsync(specialists, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 批量删除企业专员
        /// </summary>
        [HttpDelete("specialist-batch")]
        public async Task RemoveSpecialists([FromBody] List<string> ids)
        {
            var specialists = await _enterpriseSpecialistRepository.Queryable()
                .Where(d => ids.Contains(d.Id) || ids.Contains(d.ParentId))
                .ToListAsync(HttpContext.RequestAborted);
            await _enterpriseSpecialistRepository.RemoveRangeAsync(specialists, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 查询企业专员
        /// </summary>
        /// <returns></returns>
        [HttpGet("specialists-tree")]
        public Task<List<EnterpriseSpecialistDto>> QuerySpecialists()
        {
            return _enterpriseSpecialistRepository.Queryable()
                .Includes(d => d.User, s => s.Account)
                .OrderBy(d => d.Id)
                .Select(d => new EnterpriseSpecialistDto
                {
                    Id = d.Id,
                    ParentId = d.ParentId,
                    Name = d.User.Name,
                    UserName = d.User.Account.UserName,
                    PhoneNo = d.User.PhoneNo,
                })
                .ToTreeAsync(d => d.Children, it => it.ParentId, null);
        }

        /// <summary>
        /// 查询企业专员工单
        /// </summary>
        [HttpGet("specialist/orders")]
        public async Task<IReadOnlyList<OrderDto>> QueryEnterpriseSpecialistOrders([FromQuery] QueryOrderDto dto)
        {
            var query = await _enterpriseApplication.QueryEnterpriseSpecialistOrdersAsync(dto, HttpContext.RequestAborted);
            var orders = await query.ToPageListWithoutTotalAsync(dto, HttpContext.RequestAborted);
            return _mapper.Map<IReadOnlyList<OrderDto>>(orders);
        }

        /// <summary>
        /// 查询总数
        /// </summary>
        [HttpGet("specialist/orders/count")]
        public async Task<int> CountEnterpriseSpecialistOrders([FromQuery] QueryOrderDto dto)
        {
            var query = await _enterpriseApplication.QueryEnterpriseSpecialistOrdersAsync(dto, HttpContext.RequestAborted);
            return await query.CountAsync(HttpContext.RequestAborted);
        }

        /// <summary>
        /// 导出企业专员工单
        /// </summary>
        [HttpPost("specialist/orders/export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> ExportOrders([FromBody] ExportExcelDto<QueryOrderDto> dto)
        {
            var query = await _enterpriseApplication.QueryEnterpriseSpecialistOrdersAsync(dto.QueryDto, HttpContext.RequestAborted);
            List<Order> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }

            var orderDtos = _mapper.Map<ICollection<OrderDto>>(orders);

            if (_appOptions.Value.IsLuZhou && !_sessionContext.OrgIsCenter)
                orderDtos = orderDtos.Select(p => p.DataMask(false)).ToList();

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "企业专员工单数据");
        }

    }
}
