using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using GxPress.Common.Tools;
using GxPress.EnumConst;
using GxPress.Repository.Interface;
using GxPress.Repository.Interface.WorkFlow;
using GxPress.Repository.Interface.WorkProcess;
using GxPress.Request.GroupChat;
using GxPress.Service.Interface.IM;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Datory;
using GxPress.Repository.Interface.AdminVerify;
using GxPress.Repository.Interface.AppReport;
using GxPress.Service.Interface.ElasticSearch;
using GxPress.Repository.Interface.Collection;
using GxPress.Repository.Interface.Missive;
using GxPress.Repository.Interface.Note;
using GxPress.Repository.Interface.Topic;
using GxPress.Repository.Interface.WaitHandle;
using GxPress.Repository.Interface.WorkCar;
using GxPress.Repository.Interface.WorkMeeting;
using GxPress.Repository.Interface.Visit;
using GxPress.Repository.Interface.Analyze;
using GxPress.Repository.Interface.UserMiddle;
using GxPress.Repository.Interface.ArticleLabel;
using GxPress.Repository.Interface.VerificationCode;
using GxPress.Repository.Interface.FlowAttachment;
using GxPress.Repository.Interface.MeetingSummaryTodo;
using GxPress.Repository.Interface.RecordFolder;
using GxPress.Repository.Interface.Vip;
using GxPress.Repository.Interface.Order;
using GxPress.Repository.Interface.SystemRole;
using GxPress.Repository.Interface.Menus;
using GxPress.Repository.Interface.Navigation;
using GxPress.Repository.Interface.SystemLabel;
using GxPress.Repository.Interface.Category;
using GxPress.Repository.Interface.Media;
using GxPress.Repository.Interface.Teacher;
using GxPress.Repository.Interface.SensitiveWord;
using GxPress.Repository.Interface.Attach;
using GxPress.Repository.Interface.SystemRoleMenus;
using GxPress.Repository.Interface.AppStartPage;

namespace GxPress.Api.AdminControllers
{
    /// <summary>
    /// Utils
    /// </summary>
    [Route("api/admin/utils")]
    [ApiController]
    public class AdminUtilsController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;

        private readonly IFlowFieldValueRepository _flowFieldValueRepository;
        private readonly IFlowRepository _flowRepository;
        private readonly IFlowMessageRepository _flowMessageRepository;
        private readonly IFlowTodoRepository _flowTodoRepository;
        private readonly IProcessFieldRepository _processFieldRepository;
        private readonly IProcessGroupRepository _processGroupRepository;
        private readonly IProcessNodeRepository _processNodeRepository;
        private readonly IProcessRepository _processRepository;
        private readonly IProcessRequestLimitRepository _processRequestLimitRepository;
        private readonly IRuleApproverCheckRepository _ruleApproverCheckRepository;
        private readonly IRuleCarbonCopyRepository _ruleCarbonCopyRepository;
        private readonly IRuleConditionRepository _ruleConditionRuleRepository;
        private readonly IMeetingLocationRepository _meetingLocationRepository;
        private readonly IMeetingOrderRepository _meetingOrderRepository;
        private readonly IMeetingRepository _meetingRepository;
        private readonly IMeetingRoomRepository _meetingRoomRepository;
        private readonly IMeetingSummaryRepository _meetingSummaryRepository;
        private readonly ICarOrderRepository _carOrderRepository;
        private readonly ICarRepository _carRepository;
        private readonly ICarTypeRepository _carTypeRepository;
        private readonly IAdminRepository _adminRepository;
        private readonly IArticleGroupRepository _articleGroupRepository;
        private readonly IArticleRepository _articleRepository;
        private readonly IDepartmentRepository _departmentRepository;
        private readonly IRoleGroupRepository _roleGroupRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly ISlideRepository _slideRepository;
        private readonly IUserRepository _userRepository;
        private readonly ICommentRepository _commentRepository;
        private readonly IAppVersionRepository _appVersionRepository;
        private readonly IFeedbackRepository _feedbackRepository;
        private readonly IBlacklistArticleRepository _blacklistArticleRepository;
        private readonly IThesaurusRepository _thesaurusRepository;
        private readonly IArticleGroupUserRepository _articleGroupUserRepository;
        private readonly IAddressBookGroupRepository _addressBookGroupRepository;
        private readonly IAddressBookGroupUserRepository _addressBookGroupUserRepository;
        private readonly IGroupChatRepository _groupChatRepository;
        private readonly IGroupChatUserRepository _groupChatUserRepository;
        private readonly INoticeRepository _noticeRepository;
        private readonly IAddresseeRepository _addresseeRepository;
        private readonly ICcRepository _ccRepository;
        private readonly IBlacklistUserRepository _blacklistUserRepository;
        private readonly IFinanceRepository _financeRepository;
        private readonly IPrintRepository _printRepository;
        private readonly ISellRepository _sellRepository;
        private readonly IStorehouseRepository _storehouseRepository;
        private readonly IHumanAffairsRepository _humanAffairsRepository;
        private readonly IOftenContactRepository _oftenContactRepository;
        private readonly IChatRecordRepository _chatRecordRepository;
        private readonly ITopicRepository _topicRepository;
        private readonly ITopicAddresseeRepository _topicAddresseeRepository;
        private readonly IFileLibraryRepository _fileLibraryRepository;
        private readonly IIMService _imService;
        private readonly IGroupRepository _groupRepository;
        private readonly IGroupUserRepository _groupUserRepository;
        private readonly IGroupFolderRepository _groupFolderRepository;
        private readonly IMiddleRepository _middleRepository;
        private readonly IElasticSearchService _elasticSearchService;
        private readonly ICollectionRepository _collectionRepository;
        private readonly INoteRepository _noteRepository;
        private readonly IAppReportRepository _appReportRepository;
        private readonly ITopicGroupRepository _topicGroupRepository;
        private readonly ITopicGroupUserRepository _topicGroupUserRepository;
        private readonly IAdminVerifyRepository _adminVerifyRepository;
        private readonly IMissiveRepository _missiveRepository;
        private readonly IFolderUserRepository _folderUserRepository;
        private readonly IWaitHandleLabelRepository _waitHandleLabelRepository;
        private readonly IWaitHandleRepository _waitHandleRepository;
        private readonly IVisitRepository _vsitRepository;
        private readonly IAnalyzeRepository _analyzeRepository;
        private readonly IUserMiddleRepository _userMiddleRepository;
        private readonly IArticleInnerLabelRepository _articleInnerLabelRepository;
        private readonly IArticleLabelRepository _articleLabelRepository;
        private readonly IVerificationCodeRepository verificationCodeRepository;
        private readonly IFlowAttachmentRepository flowAttachmentRepository;
        private readonly IMeetingSummaryTodoRepository meetingSummaryTodoRepository;
        private readonly IRecordFolderRepository recordFolderRepository;
        private readonly IVipRepository vipRepository;
        private readonly IOrderRepository orderRepository;
        private readonly ISystemRoleRepository systemRoleRepository;
        private readonly IMenusRepository menusRepository;
        private readonly INavigationRepository navigationRepository;
        private readonly ISystemLabelRepository systemLabelRepository;
        private readonly ICategoryRepository categoryRepository;
        private readonly IMediaRepository mediaRepository;
        private readonly IMediaLibraryRepository mediaLibraryRepository;
        private readonly ITeacherRepository teacherRepository;
        private readonly ISensitiveWordRepository sensitiveWordRepository;
        private readonly IAttachRepository attachRepository;
        private readonly ISystemRoleMenusRepository systemRoleMenusRepository;
        private readonly IMediaLableRepository mediaLableRepository;
        private readonly IAppStartPageRepository appStartPageRepository;
        public AdminUtilsController(IWebHostEnvironment environment, IFlowFieldValueRepository flowFieldValueRepository,
            IFlowRepository flowRepository, IFlowMessageRepository flowMessageRepository,
            IFlowTodoRepository flowTodoRepository, IAdminRepository adminRepository,
            IArticleGroupRepository articleGroupRepository,
            IArticleRepository articleRepository,
            IDepartmentRepository departmentRepository,
            IProcessFieldRepository processFieldRepository, IProcessGroupRepository processGroupRepository,
            IProcessNodeRepository processNodeRepository, IProcessRepository processRepository,
            IProcessRequestLimitRepository processRequestLimitRepository,
            IRuleApproverCheckRepository ruleApproverCheckRepository,
            IRuleCarbonCopyRepository ruleCarbonCopyRepository, IRuleConditionRepository ruleConditionRuleRepository,
            IMeetingLocationRepository meetingLocationRepository, IMeetingOrderRepository meetingOrderRepository,
            IMeetingRepository meetingRepository, IMeetingRoomRepository meetingRoomRepository,
            IMeetingSummaryRepository meetingSummaryRepository,
            ICarOrderRepository carOrderRepository, ICarRepository carRepository, ICarTypeRepository carTypeRepository,
            IRoleGroupRepository roleGroupRepository,
            IRoleRepository roleRepository, IUserRepository userRepository, ISlideRepository slideRepository,
            ICommentRepository commentRepository, IAppVersionRepository appVersionRepository,
            IFeedbackRepository feedbackRepository, IBlacklistArticleRepository blacklistArticleRepository,
            IThesaurusRepository thesaurusRepository, IArticleGroupUserRepository articleGroupUserRepository,
            IAddressBookGroupRepository addressBookGroupRepository,
            IAddressBookGroupUserRepository addressBookGroupUserRepository, IGroupChatRepository groupChatRepository,
            IGroupChatUserRepository groupChatUserRepository, INoticeRepository noticeRepository,
            IAddresseeRepository addresseeRepository, ICcRepository ccRepository, IBlacklistUserRepository blacklistUserRepository,
            IFinanceRepository financeRepository, IPrintRepository printRepository, ISellRepository sellRepository,
            IStorehouseRepository storehouseRepository, IHumanAffairsRepository humanAffairsRepository,
            IOftenContactRepository oftenContactRepository, IChatRecordRepository chatRecordRepository,
            ITopicRepository topicRepository, ITopicAddresseeRepository topicAddresseeRepository,
            IFileLibraryRepository fileLibraryRepository, IIMService imService, IGroupRepository groupRepository,
            IGroupFolderRepository groupFolderRepository, IGroupUserRepository groupUserRepository,
            IMiddleRepository middleRepository, IElasticSearchService elasticSearchService,
            ICollectionRepository collectionRepository, INoteRepository noteRepository,
            IAppReportRepository appReportRepository, ITopicGroupRepository topicGroupRepository,
            ITopicGroupUserRepository topicGroupUserRepository, IAdminVerifyRepository adminVerifyRepository,
            IMissiveRepository missiveRepository, IWaitHandleLabelRepository waitHandleLabelRepository,
            IWaitHandleRepository waitHandleRepository, IVisitRepository visitRepository, IAnalyzeRepository analyzeRepository, IUserMiddleRepository userMiddleRepository, IArticleInnerLabelRepository articleInnerLabelRepository, IArticleLabelRepository articleLabelRepository, IVerificationCodeRepository verificationCodeRepository, IFlowAttachmentRepository flowAttachmentRepository, IMeetingSummaryTodoRepository meetingSummaryTodoRepository, IFolderUserRepository folderUserRepository, IRecordFolderRepository recordFolderRepository, IVipRepository vipRepository, IOrderRepository orderRepository, ISystemRoleRepository systemRoleRepository, IMenusRepository menusRepository, INavigationRepository navigationRepository, ISystemLabelRepository systemLabelRepository, ICategoryRepository categoryRepository, IMediaRepository mediaRepository, IMediaLibraryRepository mediaLibraryRepository,ITeacherRepository teacherRepository,ISensitiveWordRepository sensitiveWordRepository,IAttachRepository attachRepository,ISystemRoleMenusRepository systemRoleMenusRepository,IMediaLableRepository mediaLableRepository,IAppStartPageRepository appStartPageRepository)
        {
            _environment = environment;
            _flowFieldValueRepository = flowFieldValueRepository;
            _flowRepository = flowRepository;
            _flowMessageRepository = flowMessageRepository;
            _flowTodoRepository = flowTodoRepository;
            _processFieldRepository = processFieldRepository;
            _processGroupRepository = processGroupRepository;
            _processNodeRepository = processNodeRepository;
            _processRepository = processRepository;
            _processRequestLimitRepository = processRequestLimitRepository;
            _ruleApproverCheckRepository = ruleApproverCheckRepository;
            _ruleCarbonCopyRepository = ruleCarbonCopyRepository;
            _ruleConditionRuleRepository = ruleConditionRuleRepository;
            _adminRepository = adminRepository;
            _articleGroupRepository = articleGroupRepository;
            _articleRepository = articleRepository;
            _departmentRepository = departmentRepository;
            _meetingLocationRepository = meetingLocationRepository;
            _meetingOrderRepository = meetingOrderRepository;
            _meetingRepository = meetingRepository;
            _meetingRoomRepository = meetingRoomRepository;
            _meetingSummaryRepository = meetingSummaryRepository;
            _carOrderRepository = carOrderRepository;
            _carRepository = carRepository;
            _carTypeRepository = carTypeRepository;
            _roleGroupRepository = roleGroupRepository;
            _roleRepository = roleRepository;
            _userRepository = userRepository;
            _slideRepository = slideRepository;
            _commentRepository = commentRepository;
            _appVersionRepository = appVersionRepository;
            _feedbackRepository = feedbackRepository;
            _blacklistArticleRepository = blacklistArticleRepository;
            _thesaurusRepository = thesaurusRepository;
            _articleGroupUserRepository = articleGroupUserRepository;
            _addressBookGroupRepository = addressBookGroupRepository;
            _addressBookGroupUserRepository = addressBookGroupUserRepository;
            _groupChatRepository = groupChatRepository;
            _groupChatUserRepository = groupChatUserRepository;
            _noticeRepository = noticeRepository;
            _addresseeRepository = addresseeRepository;
            _ccRepository = ccRepository;
            _blacklistUserRepository = blacklistUserRepository;
            _humanAffairsRepository = humanAffairsRepository;
            _financeRepository = financeRepository;
            _sellRepository = sellRepository;
            _storehouseRepository = storehouseRepository;
            _printRepository = printRepository;
            _oftenContactRepository = oftenContactRepository;
            _chatRecordRepository = chatRecordRepository;
            _topicAddresseeRepository = topicAddresseeRepository;
            _topicRepository = topicRepository;
            _fileLibraryRepository = fileLibraryRepository;
            _imService = imService;
            _groupFolderRepository = groupFolderRepository;
            _groupUserRepository = groupUserRepository;
            _groupRepository = groupRepository;
            _middleRepository = middleRepository;
            _elasticSearchService = elasticSearchService;
            _collectionRepository = collectionRepository;
            _noteRepository = noteRepository;
            _appReportRepository = appReportRepository;
            _topicGroupRepository = topicGroupRepository;
            _topicGroupUserRepository = topicGroupUserRepository;
            _adminVerifyRepository = adminVerifyRepository;
            _missiveRepository = missiveRepository;
            _folderUserRepository = folderUserRepository;
            _waitHandleRepository = waitHandleRepository;
            _waitHandleLabelRepository = waitHandleLabelRepository;
            _vsitRepository = visitRepository;
            _analyzeRepository = analyzeRepository;
            _userMiddleRepository = userMiddleRepository;
            _articleInnerLabelRepository = articleInnerLabelRepository;
            _articleLabelRepository = articleLabelRepository;
            this.verificationCodeRepository = verificationCodeRepository;
            this.flowAttachmentRepository = flowAttachmentRepository;
            this.meetingSummaryTodoRepository = meetingSummaryTodoRepository;
            this.recordFolderRepository = recordFolderRepository;
            this.vipRepository = vipRepository;
            this.orderRepository = orderRepository;
            this.menusRepository = menusRepository;
            this.systemRoleRepository = systemRoleRepository;
            this.navigationRepository = navigationRepository;
            this.systemLabelRepository = systemLabelRepository;
            this.categoryRepository = categoryRepository;
            this.mediaRepository = mediaRepository;
            this.mediaLibraryRepository = mediaLibraryRepository;
            this.teacherRepository=teacherRepository;
            this.sensitiveWordRepository = sensitiveWordRepository;
            this.attachRepository=attachRepository;
            this.systemRoleMenusRepository= systemRoleMenusRepository;
            this.mediaLableRepository=mediaLableRepository;
            this.appStartPageRepository=appStartPageRepository;
        }

        [HttpGet("works")]
        public async Task<string> WorksAsync()
        {
            var retVal = await _adminRepository.Database.IsConnectionWorksAsync();
            return retVal.IsConnectionWorks ? "Database Connection Works" : retVal.ErrorMessage;
        }

        [HttpGet("sync_database")]
        public async Task<string> SyncDatabase()
        {
            var database = _adminRepository.Database;
            var repositories = new List<IRepository>
            {
                _adminRepository,
                _flowFieldValueRepository,
                _flowRepository,
                _flowMessageRepository,
                _flowTodoRepository,
                _processFieldRepository,
                _processGroupRepository,
                _processNodeRepository,
                _processRepository,
                _processRequestLimitRepository,
                _ruleApproverCheckRepository,
                _ruleCarbonCopyRepository,
                _ruleConditionRuleRepository,
                _articleGroupRepository,
                _articleRepository,
                _departmentRepository,
                _meetingLocationRepository,
                _meetingOrderRepository,
                _meetingRepository,
                _meetingRoomRepository,
                _meetingSummaryRepository,
                _carOrderRepository,
                _carRepository,
                _carTypeRepository,
                _roleGroupRepository,
                _roleRepository,
                _slideRepository,
                _userRepository,
                _commentRepository,
                _appVersionRepository,
                _feedbackRepository,
                _blacklistArticleRepository,
                _thesaurusRepository,
                _articleGroupUserRepository,
                _addressBookGroupRepository,
                _addressBookGroupUserRepository,
                _groupChatRepository,
                _groupChatUserRepository,
                _noticeRepository,
                _addresseeRepository,
                _ccRepository,
                _blacklistUserRepository,
                _humanAffairsRepository,
                _financeRepository,
                _sellRepository,
                _storehouseRepository,
                _printRepository,
                _chatRecordRepository,
                _oftenContactRepository,
                _topicAddresseeRepository,
                _topicRepository,
                _fileLibraryRepository,
                _groupFolderRepository,
                _groupUserRepository,
                _groupRepository,
                _middleRepository,
                _collectionRepository,
                _noteRepository,
                _appReportRepository,
                _topicGroupRepository,
                _topicGroupUserRepository,
                _adminVerifyRepository,
                _missiveRepository,
                _folderUserRepository,
                _waitHandleRepository,
                _waitHandleLabelRepository,
                _vsitRepository,
                _analyzeRepository,
                _userMiddleRepository,
                _articleInnerLabelRepository,
                _articleLabelRepository,
                verificationCodeRepository,
                flowAttachmentRepository,
                meetingSummaryTodoRepository,
                recordFolderRepository,
                vipRepository,
                orderRepository,
                menusRepository,
                systemRoleRepository,
                navigationRepository,
                systemLabelRepository,
                categoryRepository,
                mediaRepository,
                mediaLibraryRepository,
                teacherRepository,
                sensitiveWordRepository,
                attachRepository,
                systemRoleMenusRepository,
                mediaLableRepository,
                appStartPageRepository
            };

            var alterCount = 0;
            var createCount = 0;
            foreach (var repository in repositories)
            {
                if (await database.IsTableExistsAsync(repository.TableName))
                {
                    await database.AlterTableAsync(repository.TableName, repository.TableColumns);
                    alterCount++;
                }
                else
                {
                    await database.CreateTableAsync(repository.TableName, repository.TableColumns);
                    createCount++;
                }
            }
            //var database = new Database();
            //database.IsTableExistsAsync()
            return $"alter: {alterCount}, create: {createCount}";
        }

        [HttpGet("qrcoder")]
        public async Task<bool> SendQRCode()
        {
            var users = await _userRepository.FindAllUserAsync(Q.Where(nameof(Entity.User.Id), ">", 0));
            foreach (var user in users)
            {
                if (string.IsNullOrEmpty(user.QRCoder))
                {
                    //生成二维码
                    var qrCodeData = new { key = QRCodeTypeConst.UserInfo, value = user.Guid };
                    var resultPath =
                        FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
                            JsonConvert.SerializeObject(qrCodeData));
                    user.QRCoder = resultPath.RelativePath;
                    await _userRepository.UpdateAsync(user);
                }
            }

            var groupChats = await _groupChatRepository.GetAllGroupChatAsync();
            foreach (var groupChat in groupChats)
            {
                if (string.IsNullOrEmpty(groupChat.QRCoder))
                {
                    //生成二维码
                    var qrCodeData = new { key = QRCodeTypeConst.GroupChatInfo, value = groupChat.Guid };
                    var resultPath =
                        FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
                            JsonConvert.SerializeObject(qrCodeData));
                    groupChat.QRCoder = resultPath.RelativePath;
                    var request = new GroupChatUpRequest { Id = groupChat.Id, QrCode = groupChat.QRCoder };
                    await _groupChatRepository.UpdateAsync(request);
                }
            }

            return true;
        }

        [HttpGet("test")]
        public async Task<bool> Test()
        {
            //return await new MinIOHelper().PutObjectAsync("test", "1234.jpeg", "C:\\Users\\zuoxi\\Desktop\\1234.jpeg", "application/octet-stream");
            //return await _imService.GetTokenImAsync();
            return await _elasticSearchService.ElasticSearchData();
        }
        [HttpGet("im-token")]
        public async Task<bool> SetImToken()
        {
            return await _imService.GetTokenImAsync();
        }

        /// <summary>
        /// 插入环信用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("im-user")]
        public async Task<bool> SetImUser()
        {
            var users = await _userRepository.GetAllAsync(Q.Where(nameof(Entity.User.Id), ">", 0));
            foreach (var item in users)
            {
                await _userRepository.CreateMiUserAsync(item);
            }

            return true;
        }

        /// <summary>
        /// 设置图片
        /// </summary>
        /// <returns></returns>
        [HttpGet("set-img")]
        public async Task<bool> SetImg()
        {
            //获取文章
            var articles = await _articleRepository.GetAllAsync();
            foreach (var article in articles)
            {
                var strings = StringUtils.StringCollectionToStringList(article.ImageUrls);
                foreach (var imageUrl in strings)
                {
                    var imageUrlFullName = imageUrl.Split('/')[imageUrl.Split('/').Length - 1];
                    //获取文件路径
                    var file = StringUtils.GetWebRootPath(_environment.WebRootPath + "\\cache");
                    DirectoryInfo info = new DirectoryInfo(file);
                    foreach (var item in info.GetFileSystemInfos())
                    {
                        //判读是否是文件夹
                        if (Directory.Exists(item.FullName))
                        {
                            //获取文件夹下面的文件
                            var infos = new DirectoryInfo(item.FullName);
                            foreach (var fileIo in infos.GetFileSystemInfos())
                            {
                                if (fileIo.FullName.Contains(imageUrlFullName))
                                {
                                    //压缩图片
                                    CompressImage.Execute(fileIo.FullName);
                                    //压缩图片
                                    CompressImage.Execute(fileIo.FullName, 100);
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }
    }
}