using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Dapper;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Tools;
using GxPress.Repository.Interface.FlowAttachment;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;

namespace GxPress.Repository.Implement.FlowAttachment
{

    public class FlowAttachmentRepository : IFlowAttachmentRepository
    {
        private readonly Repository<Entity.WorkFlow.FlowAttachment> _repository;
        private readonly IMapper _mapper;
        private readonly IDistributedCache _cache;
        private readonly string _connectionString;
        private readonly string _databaseTypeStr;

        public FlowAttachmentRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper, IDistributedCache cache)
        {
            _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
            _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<Entity.WorkFlow.FlowAttachment>(database);
            _mapper = mapper;
            _cache = cache;
        }
        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

        public async Task<Entity.WorkFlow.FlowAttachment> GetAsync(int id)
        {
            return await _repository.GetAsync(id);
        }

        public async Task<Entity.WorkFlow.FlowAttachment> GetAsync(SqlKata.Query query)
        {
            return await _repository.GetAsync(query);
        }
        public async Task<IEnumerable<Entity.WorkFlow.FlowAttachment>> GetAllAsync(SqlKata.Query query)
        {
            var result = await _repository.GetAllAsync(query);
            foreach (var item in result)
            {
                if (!string.IsNullOrWhiteSpace(item.Url))
                {
                    if (item.Url.Contains("."))
                    {
                        var fileType = item.Url.Split('.')[item.Url.Split('.').Length - 1]; ;
                        //图片种类
                        string imageType =
                            "bmp,jpg,jpeg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp";
                        var imageTypeList = StringUtils.StringCollectionToStringList(imageType).ToList();
                        if (imageTypeList.Contains(fileType.ToLower())) item.MinUrl = StringUtils.AddDomainMin(item.Url);
                        else item.MinUrl = "";
                        item.Url = StringUtils.AddDomain(item.Url);
                    }
                }
            }
            return result;
        }
        public async Task<bool> DeleteAsync(SqlKata.Query query)
        {
            return await _repository.DeleteAsync(query) > 0;
        }
        public async Task<bool> DeleteAllAsync(int flowId)
        {
            return await _repository.DeleteAsync(Q.Where(nameof(Entity.WorkFlow.FlowAttachment.SoureId), flowId).Where(nameof(Entity.WorkFlow.FlowAttachment.TypeId), 1)) > 0;
        }
        public async Task<IEnumerable<Entity.WorkFlow.FlowAttachment>> GetAllAsync(int flowId)
        {
            return await _repository.GetAllAsync(Q.Where(nameof(Entity.WorkFlow.FlowAttachment.SoureId), flowId).Where(nameof(Entity.WorkFlow.FlowAttachment.TypeId), 1));
        }
        public async Task<int> InsertAsync(Entity.WorkFlow.FlowAttachment flowAttachment)
        {
            return await _repository.InsertAsync(flowAttachment);
        }

        public async Task<bool> UpdateAsync(Entity.WorkFlow.FlowAttachment flowAttachment)
        {
            return await _repository.UpdateAsync(flowAttachment);
        }
        public async Task<bool> UpdateAsync(SqlKata.Query query)
        {
            return await _repository.UpdateAsync(query) > 0;
        }
        /// <summary>
        /// 添加工作流附件
        /// </summary>
        /// <param name="flowAttachments"></param>
        /// <returns></returns>
        public async Task<bool> InsertsAsync(List<Entity.WorkFlow.FlowAttachment> flowAttachments)
        {
            if (flowAttachments.Count == 0)
                return false;
            var sql = "INSERT INTO `ccpph`.`tede_flow_attachment`(`Guid`,`CreatedDate`,`LastModifiedDate`,`TypeId`,`SoureId`,`Url`,`Title`,`FlowId`,`Size`,`SoureTypeId`)VALUES";
            foreach (var item in flowAttachments)
            {
                var guId = Guid.NewGuid().ToString();
                var createdDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sql += $"('{guId}','{createdDate}','{createdDate}',{item.TypeId},{item.SoureId},'{StringUtils.RemoveDomain(item.Url)}','{item.Title}',{item.FlowId},{item.Size},{item.SoureTypeId}),";
            }
            sql = sql.Remove(sql.Length - 1, 1);
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var items = await connection.ExecuteScalarAsync<int>(sql);
            return items > 0;
        }
    }
}