using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using Hotline.Application.Snapshot.Contracts;
using Hotline.Caching.Interfaces;
using Hotline.File;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Settings;
using Hotline.Share.Attributes;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Tools;
using Hotline.Snapshot;
using Hotline.Snapshot.IRepository;
using Hotline.Tools;
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;

namespace Hotline.Application.Snapshot;
public class IndustryApplication : IIndustryApplication, IScopeDependency
{
    private readonly IIndustryRepository _industryRepository;
    private readonly IFileRepository _fileRepository;
    private readonly ISystemSettingCacheManager _sysSetting;
    private readonly IIndustryCaseRepository _industryCaseRepository;
    private readonly ISnapshotSMSTemplateRepository _snapshotSMSTemplateRepository;
    private readonly IPractitionerRepository _practitionerRepository;
    private readonly IVolunteerRepository _volunteerRepository;
    private readonly IVolunteerReportRepository _volunteerReportRepository;
    private readonly IIndustryLogRepository _industryLogRepository;
    private readonly ISystemOrganizeRepository _systemOrganizeRepository;

    public IndustryApplication(IIndustryRepository industryRepository, IFileRepository fileRepository, ISystemSettingCacheManager sysSetting, IIndustryCaseRepository industryCaseRepository, ISnapshotSMSTemplateRepository snapshotSMSTemplateRepository, IPractitionerRepository practitionerRepository, IVolunteerRepository volunteerRepository, IVolunteerReportRepository volunteerReportRepository, IIndustryLogRepository industryLogRepository, ISystemOrganizeRepository systemOrganizeRepository)
    {
        _industryRepository = industryRepository;
        _fileRepository = fileRepository;
        _sysSetting = sysSetting;
        _industryCaseRepository = industryCaseRepository;
        _snapshotSMSTemplateRepository = snapshotSMSTemplateRepository;
        _practitionerRepository = practitionerRepository;
        _volunteerRepository = volunteerRepository;
        _volunteerReportRepository = volunteerReportRepository;
        _industryLogRepository = industryLogRepository;
        _systemOrganizeRepository = systemOrganizeRepository;
    }
    /// <summary>
    /// 新增行业
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<string> AddIndustryAsync(AddIndustryDto dto, CancellationToken cancellationToken)
    {
        dto.ValidateObject();
        if (dto.ApproveOrgId.NotNullOrEmpty() && dto.ApproveOrgName.IsNullOrEmpty())
        {
            await _systemOrganizeRepository.GetAsync(dto.ApproveOrgId, cancellationToken)
                .Then(async org => { dto.ApproveOrgName = org.Name; });
        }
        var entity = dto.Adapt<Industry>();
        entity.ModuleCode = WorkflowModuleConsts.OrderHandle;
        var id = await _industryRepository.AddAsync(entity, cancellationToken);
        if (dto.Files.NotNullOrEmpty())
        {
            var fileEntities = dto.Files.Adapt<List<Hotline.File.File>>();
            fileEntities.ForEach(m => m.Key = id);
            await _fileRepository.AddRangeAsync(fileEntities, cancellationToken);
        }
        return id;
    }

    [ExportExcel("行业集合")]
    public ISugarQueryable<IndustryItemsOutDto> GetIndustres(IndustryListInDto dto)
    {
        var query = _industryRepository.Queryable()
            .WhereIF(dto.Name.NotNullOrEmpty(), m => m.Name.Contains(dto.Name))
            .WhereIF(dto.ApproveOrgName.NotNullOrEmpty(), m => m.ApproveOrgName.Contains(dto.ApproveOrgName))
            .OrderByDescending(m => m.CreationTime)
            .Select<IndustryItemsOutDto>();


        return query;
    }

    public async Task<IndustryDetailOutDto> GetIndustryDetailAsync(string id, CancellationToken token)
    {
        var fileServiceUrl = _sysSetting.FileServerUrl;
        var fileDownloadApi = fileServiceUrl + _sysSetting.FileDownloadApi;
        var industry = await _industryRepository.GetAsync(id);
        var files = await _fileRepository.GetByKeyAsync(id, token);
        var outDto = industry.Adapt<IndustryDetailOutDto>();
        outDto.Files = files.Adapt<IList<IndustryFileDto>>();
        return outDto;
    }

    /// <summary>
    /// 修改行业
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="requestAborted"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task UpdateIndustryAsync(UpdateIndustryInDto dto, CancellationToken requestAborted)
    {
        dto.ValidateObject();
        if (dto.ApproveOrgId.NotNullOrEmpty() && dto.ApproveOrgName.IsNullOrEmpty())
        {
            await _systemOrganizeRepository.GetAsync(dto.ApproveOrgId, requestAborted)
                .Then(async org => { dto.ApproveOrgName = org.Name; });
        }
        var entity = await _industryRepository.GetAsync(dto.Id) ?? throw UserFriendlyException.SameMessage($"行业不存在 {dto.Id}");
        if (dto.Files.NotNullOrEmpty())
        {
            var fileEntities = dto.Files.Adapt<List<File.File>>();
            fileEntities.ForEach(m => m.Key = entity.Id);
            await _fileRepository.Removeable().Where(m => m.Key == entity.Id).ExecuteCommandAsync(requestAborted);
            await _fileRepository.AddRangeAsync(fileEntities, requestAborted);
        }
        else
        {
            await _fileRepository.Removeable().Where(m => m.Key == entity.Id).ExecuteCommandAsync(requestAborted);
        }
        dto.Adapt(entity);
        await _industryRepository.UpdateAsync(entity, requestAborted);
    }

    #region 行业线索
    [ExportExcel("行业线索")]
    public ISugarQueryable<IndustryCaseItemOutDto> GetIndustryCaseItems(IndustryCaseItemInDto dto)
    {
        var query = _industryCaseRepository.Queryable()
            .LeftJoin<Industry>((c, i) => c.IndustryId == i.Id)
            .WhereIF(dto.IndustryName.NotNullOrEmpty(), (c, i) => i.Name.Contains(dto.IndustryName))
            .WhereIF(dto.CaseName.NotNullOrEmpty(), (c, i) => c.Name.Contains(dto.CaseName))
            .OrderByDescending((c, i) => c.CreationTime)
            .Select<IndustryCaseItemOutDto>((c, i) =>
            new IndustryCaseItemOutDto
            {
                Id = c.Id,
                Name = c.Name,
                IndustryId = i.Id,
                IndustryName = i.Name
            }, true);
        return query;
    }

    /// <summary>
    /// 添加行业线索
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<string> AddIndustryCaseAsync(AddIndustryCaseDto dto)
    {
        dto.ValidateObject();
        var entity = dto.Adapt<IndustryCase>();
        return await _industryCaseRepository.AddAsync(entity);
    }

    /// <summary>
    /// 修改行业线索
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task UpdateIndustryCaseAsync(UpdateIndustryCaseDto dto)
    {
        dto.ValidateObject();
        var entity = await _industryCaseRepository.GetAsync(dto.Id)
            ?? throw UserFriendlyException.SameMessage($"行业线索不存在 {dto.Id}");
        dto.Adapt(entity);
        await _industryCaseRepository.UpdateAsync(entity);
    }

    public async Task<IndustryCase> GetIndustryCaseAsync(string caseId)
    {
        return await _industryCaseRepository.GetAsync(caseId);
    }
    #endregion

    #region 行业短信模板

    /// <summary>
    /// 行业模板集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("行业审批短信")]
    public ISugarQueryable<SnapshotSMSTemplateItemsOutDto> GetSMSTemplates(SnapshotSMSTemplateItemsInDto dto)
    {
        var query = _snapshotSMSTemplateRepository.Queryable()
            .LeftJoin<Industry>((s, i) => s.IndustryId == i.Id)
            .WhereIF(dto.IndustryName.NotNullOrEmpty(), (s, i) => i.Name.Contains(dto.IndustryName))
            .OrderByDescending((s, i) => s.DisplayOrder)
            .Select<SnapshotSMSTemplateItemsOutDto>();
        return query;
    }

    /// <summary>
    /// 添加行业模板
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<string> AddSMSTemplateAsync(AddSnapshotSMSTemplateInDto dto)
    {
        dto.ValidateObject();
        var entity = dto.Adapt<SnapshotSMSTemplate>();
        return await _snapshotSMSTemplateRepository.AddAsync(entity);
    }

    /// <summary>
    /// 修改行业模板
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task UpdateSMSTemplateAsync(UpdateSnapshotSMSTemplateInDto dto)
    {
        dto.ValidateObject();
        var entity = await _snapshotSMSTemplateRepository.GetAsync(dto.Id)
            ?? throw UserFriendlyException.SameMessage($"行业短信模板不存在 {dto.Id}");
        dto.Adapt(entity);
        await _snapshotSMSTemplateRepository.UpdateAsync(entity);
    }

    /// <summary>
    /// 短信详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<SnapshotSMSTemplateItemsOutDto> GetSMSTemplateDetailAsync(string id)
    {
        return await _snapshotSMSTemplateRepository.Queryable()
            .LeftJoin<Industry>((s, i) => s.IndustryId == i.Id)
            .Where((s, i) => s.Id == id)
            .Select((s, i) => new SnapshotSMSTemplateItemsOutDto
            {
                Status = s.Status
            }, true)
            .FirstAsync();
    }

    #endregion

    #region 区域从业人员
    /// <summary>
    /// 区域从业人员集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    [ExportExcel("区域从业人员")]
    public ISugarQueryable<PractitionerItemsOutDto> GetPractitionerItems(PractitionerItemsInDto dto)
    {
        var query = _practitionerRepository.Queryable()
            .WhereIF(dto.Name.NotNullOrEmpty(), m => m.Name.Contains(dto.Name!))
            .WhereIF(dto.SystemAreaName.NotNullOrEmpty(), m => m.SystemAreaName.Contains(dto.SystemAreaName!))
            .WhereIF(dto.PhoneNumber.NotNullOrEmpty(), m => m.PhoneNumber.Contains(dto.PhoneNumber!))
            .OrderByDescending(m => m.CreationTime)
            .Select<PractitionerItemsOutDto>();

        return query;
    }

    /// <summary>
    /// 添加区域从业人员
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<string> AddPractitionerAsync(AddPractitionerInDto dto)
    {
        dto.ValidateObject();
        var entity = dto.Adapt<Practitioner>();
        return await _practitionerRepository.AddAsync(entity);
    }

    /// <summary>
    /// 区域从业人员详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<PractitionerItemsOutDto> GetPractitionerAsync(string id)
    {
        return (await _practitionerRepository.GetAsync(id)).Adapt<PractitionerItemsOutDto>();
    }

    /// <summary>
    /// 删除区域从业人员
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task DeletePractitionerAsync(IList<string> id)
    {
        await _practitionerRepository.Updateable()
            .SetColumns(m => m.IsDeleted, true)
            .Where(m => id.Contains(m.Id))
            .ExecuteCommandAsync();
    }

    /// <summary>
    /// 修改区域从业人员
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task UpdatePractitionerAsync(UpdatePractitionerInDto dto)
    {
        dto.ValidateObject();

        var entity = await _practitionerRepository.GetAsync(dto.Id) ?? throw UserFriendlyException.SameMessage($"从业人员不存在 {dto.Id}");
        dto.Adapt(entity);
        await _practitionerRepository.UpdateAsync(entity);
    }

    #endregion

    #region 志愿者

    /// <summary>
    /// 志愿者集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("志愿者名单")]
    public ISugarQueryable<VolunteerItemsOutDto> GetVolunteerItems(VolunteerItemsInDto dto)
    {
        var query = _volunteerRepository.Queryable()
            .WhereIF(dto.Name.NotNullOrEmpty(), m => m.Name.Contains(dto.Name))
            .WhereIF(dto.PhoneNumber.NotNullOrEmpty(), m => m.PhoneNumber.Contains(dto.PhoneNumber))
            .OrderByDescending(m => m.CreationTime)
            .Select<VolunteerItemsOutDto>();
        return query;
    }

    /// <summary>
    /// 添加志愿者
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<string> AddVolunteerAsync(AddVolunteerInDto dto)
    {
        var entity = dto.Adapt<Volunteer>();
        entity.Id = await _volunteerRepository.AddAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 批量删除志愿者
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task DeleteVolunteerAsync(IList<string> ids)
    {
        await _volunteerRepository.Updateable()
            .SetColumns(m => m.IsDeleted, true)
            .Where(m => ids.Contains(m.Id))
            .ExecuteCommandAsync();
    }

    /// <summary>
    /// 志愿者详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<Volunteer> GetVolunteerAsync(string id)
    {
        return await _volunteerRepository.GetAsync(id);
    }

    /// <summary>
    /// 修改志愿者
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task UpdateVolunteerAsync(UpdateVolunteerInDto dto)
    {
        dto.ValidateObject();
        var entity = await _volunteerRepository.GetAsync(dto.Id) ?? throw UserFriendlyException.SameMessage($"志愿者不存在 {dto.Id}");
        dto.Adapt(entity);
        await _volunteerRepository.UpdateAsync(entity);
    }

    /// <summary>
    /// 志愿者上报集合
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [ExportExcel("志愿者上报")]
    public ISugarQueryable<VolunteerReportItemsOutDto> GetVolunteerReportItems(VolunteerReportItemsInDto dto)
    {
        var query = _volunteerReportRepository.Queryable()
            .LeftJoin<SystemDicData>((volunteer, dic) => volunteer.JobType == dic.Id)
            .WhereIF(dto.Name.NotNullOrEmpty(), (volunteer, dic) => volunteer.Name.Contains(dto.Name))
            .WhereIF(dto.PhoneNumber.NotNullOrEmpty(), (volunteer, dic) => volunteer.PhoneNumber.Contains(dto.PhoneNumber))
            .OrderByDescending((volunteer, dic) => volunteer.CreationTime)
            .Select((volunteer, dic) => new VolunteerReportItemsOutDto
            {
                JobType = dic.DicDataName,
                PhoneNumber = volunteer.DeclarePhoneNumber,
                FullAddress = volunteer.Address + volunteer.FullAddress,
            }, true)
            .Mapper((item, cache) =>
            {
                item.Files = _fileRepository.Queryable()
                .Where(file => file.Key == item.Id)
                .Select(file => new IndustryFileDto
                {
                    Id = file.Id,
                    Path = file.Path,
                    FileName = file.FileName,
                    Additions = file.Additions
                }).ToList();
            });
#if DEBUG
        var sql = query.ToSqlString();
#endif
        return query;
    }

    /// <summary>
    /// 行业修改记录
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<IndustryLogItemsOutDto> GetIndustryLogItems(IndustryLogItemsInDto dto)
    {
        var query = _industryLogRepository.Queryable()
            .WhereIF(dto.No.NotNullOrEmpty(), m => m.No.Contains(dto.No))
            .WhereIF(dto.ChangeName.NotNullOrEmpty(), m => m.CreatorName.Contains(dto.ChangeName))
            .WhereIF(dto.IndustryName.NotNullOrEmpty(), m => m.IndustryName.Contains(dto.IndustryName))
            .WhereIF(dto.oldIndustryName.NotNullOrEmpty(), m => m.OldIndustryName.Contains(dto.oldIndustryName))
            .WhereIF(dto.BeginTime.HasValue && dto.EndTime.HasValue, m => m.CreationTime >= dto.BeginTime.Value && m.CreationTime <= dto.EndTime.Value)
            .Select<IndustryLogItemsOutDto>();
        return query;
    }

    /// <summary>
    /// 删除行业短信模板
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task DeleteSMSTemplateAsync(IList<string> ids)
    {
        await _snapshotSMSTemplateRepository.Queryable()
            .Where(m => ids.Contains(m.Id))
            .ToListAsync()
            .Then(async sms =>
            {
                for (int i = 0;i < sms.Count;i++)
                {
                    sms[i].IsDeleted = true;
                    await _snapshotSMSTemplateRepository.UpdateAsync(sms[i]);
                }
            });
    }

    #endregion
}
