using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Dapper;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Entity.Missive;
using GxPress.Repository.Interface.Missive;
using GxPress.Request.App.Missive;
using GxPress.Result.App.Missive;
using Microsoft.Extensions.Options;
using SqlKata;

namespace GxPress.Repository.Implement.Missive
{
    public class MissiveAddresseeRepository : IMissiveAddresseeRepository
    {
        private readonly Repository<MissiveAddressee> _repository;
        private readonly IMapper _mapper;
        private readonly string _connectionString;
        private readonly string _databaseTypeStr;
        public MissiveAddresseeRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
        {
            _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<MissiveAddressee>(database);
            _mapper = mapper;
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

        public async Task<int> InsertAsync(MissiveAddressee missiveAddressee)
        {
            return await _repository.InsertAsync(missiveAddressee);
        }
        /// <summary>
        /// list 添加站内信收件人
        /// </summary>
        /// <param name="missiveAddressees"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(List<MissiveAddressee> missiveAddressees)
        {
            if (missiveAddressees.Count == 0)
                return false;
            var sql = "INSERT INTO `ccpph`.`tede_missive_addressee`(`Guid`,`CreatedDate`,`LastModifiedDate`,`MissiveId`,`UserId`,`UserName`,`IsRead`,`IsAdmin`,`IsDelete`)VALUES";
            foreach (var item in missiveAddressees)
            {
                var guId = Guid.NewGuid().ToString();
                var createdDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var isRead = item.IsRead == true ? 1 : 0;
                var isAdmin = item.IsAdmin == true ? 1 : 0;
                var isDelete = item.IsDelete == true ? 1 : 0;
                sql += $"('{guId}','{createdDate}','{createdDate}',{item.MissiveId},{item.UserId},'',{isRead},{isAdmin},{isDelete}),";
            }
            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;
        }
        public async Task<MissiveAddressee> GetAsync(int id)
        {
            return await _repository.GetAsync(id);
        }

        public async Task<bool> UpdateAsync(MissiveAddressee missiveAddressee)
        {
            return await _repository.UpdateAsync(missiveAddressee);
        }

        public async Task<bool> DeleteAsync(Query query)
        {
            return await _repository.DeleteAsync(query) > 0;
        }

        public async Task<bool> UpdateAsync(Query query)
        {
            return await _repository.UpdateAsync(query) > 0;
        }

        public async Task<IEnumerable<MissiveAddressee>> GetAllAsync(Query query)
        {
            return await _repository.GetAllAsync(query);
        }
        /// <summary>
        /// 获取站内信已读未读数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<MissiveReadListResult>> GetMissiveReadListAsync(MissiveReadListRequest request)
        {
            var databaseType = _databaseTypeStr.ToEnum<DatabaseType>(DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var sqlValue = "";
            if (request.ReadType > 0)
            {
                if (request.ReadType == 2)
                    request.ReadType = 0;
                sqlValue += $" and a.IsRead={request.ReadType} ";
            }
            if (!string.IsNullOrWhiteSpace(request.Key))
                sqlValue += $" and b.Name like '%{request.Key}%'";
            var sql = $"SELECT a.*,b.Id,b.Name,b.AvatarUrl,c.Name FROM ccpph.tede_missive_addressee a inner join ccpph.tede_user b on a.UserId=b.Id inner join ccpph.tede_department c on c.Id=b.DepartmentId where a.MissiveId={request.MissiveId} {sqlValue} order by a.LastModifiedDate desc";
            var items = await connection
              .QueryAsync<MissiveReadListResult, User, Department, MissiveReadListResult>(sql,
                  (missiveReadListResult, user, department) =>
                  {
                      missiveReadListResult.AvatarUrl = user == null ? "" : StringUtils.AddDomainMin(user.AvatarUrl);
                      missiveReadListResult.DepartmentName = department == null ? "" : department.Name;
                      missiveReadListResult.Name = user == null ? "" : user.Name;
                      //missiveReadListResult.UserId=user == null ? 0 : user.Id;
                      return missiveReadListResult;
                  },
                  splitOn: "Id,Name");
            return items;
        }
    }
}
