using DocumentFormat.OpenXml.Office2013.Word;
using Infrastructure;
using Microsoft.Extensions.Configuration;
using NetTaste;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.BaseApp.SysGroupManager.Request;
using OpenAuth.App.FormScheme.FormHelpers;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.App.BaseApp.SysGroupManager
{
    public class SysGroupApp : SqlSugarBaseApp<SysGroup, SugarDbContext>
    {
        private readonly IConfiguration _configuration;
        private readonly ISqlSugarClient client;
        public SysGroupApp(ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<SysGroup> repository, IAuth auth, ISqlSugarClient sqlSugarClient,
            IConfiguration configuration) : base(unitWork, repository, auth)
        {
            _configuration = configuration;
            this.client = sqlSugarClient;
        }

        /// <summary>
        /// 分页获取列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<SysGroup>>>> LoadGroupList(string keyword, int pageindex, int pagesize)
        {
            //定义且实例化分页数据
            RefAsync<int> totalCount = 0;
            //数据查询并返回
            var info = await this.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(keyword), t => t.Name.Contains(keyword))
                .OrderBy(t => t.Name)
                .ToPageListAsync(pageindex, pagesize, totalCount);
            return new Response<PageInfo<List<SysGroup>>>
            {
                Result = new PageInfo<List<SysGroup>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="code">Id</param>
        /// <returns></returns>
        public Task<SysGroup> GetEntityById(string id)
        {
            return this.Repository.AsQueryable().FirstAsync(t => t.Id == id);
        }

        /// <summary>
        /// 保存（新增、修改）
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="group">数据源实体</param>
        /// <returns></returns>
        public async Task<Response<bool>> SaveEntity(string id, SysGroup group)
        {
            var flag = false;
            //判断是更新还是添加
            if (!string.IsNullOrEmpty(id))
            {
                using (var uwo = UnitWork.CreateContext())
                {
                    //判断是否名称重复
                    SysGroup entity = await this.Repository.GetFirstAsync(t => t.Name == group.Name && t.Id != group.Id);
                    if (entity != null)
                    {
                        return new Response<bool>
                        {
                            Result = flag,
                            Message = "分组名称已存在"
                        };
                    }
                    //更新数据
                    await uwo.SysGroup.UpdateSetColumnsTrueAsync(a => new SysGroup
                    {
                        Name = group.Name,
                        GroupLeaderId = group.GroupLeaderId,
                        GroupLeaderName = group.GroupLeaderName,
                        Remark = group.Remark
                    }, a => a.Id == id);

                    //将组长添加中间表
                    SysGroupuser gu = new SysGroupuser();
                    gu.GroupId = group.Id;
                    gu.UserId = group.GroupLeaderId;
                    var guser = client.Queryable<SysGroupuser>().Where(r => r.GroupId == gu.GroupId && r.UserId == gu.UserId).ToList();
                    if (guser.Count==0)
                    {
                        await uwo.SysGroupuser.InsertAsync(gu);
                    }
                    flag = uwo.Commit();
                }
            }
            else
            {
                using (var uwo = UnitWork.CreateContext())
                {
                    //判断名称是否重复
                    SysGroup entity = await this.Repository.GetFirstAsync(t => t.Name == group.Name);
                    if (entity != null)
                    {
                        return new Response<bool>
                        {
                            Result = flag,
                            Message = "分组名称已存在"
                        };
                    }
                    //添加数据
                    group.Id = Guid.NewGuid().ToString();
                    group.CreateTime = DateTime.Now;
                    await uwo.SysGroup.InsertAsync(group);
                    //将组长添加中间表
                    SysGroupuser gu = new SysGroupuser();
                    gu.GroupId = group.Id;
                    gu.UserId=group.GroupLeaderId;
                    var guser=client.Queryable<SysGroupuser>().Where(r=>r.GroupId==gu.GroupId&&r.UserId==gu.UserId).ToList();
                    if (guser.Count==0)
                    {
                       await uwo.SysGroupuser.InsertAsync(gu);
                    }
                    flag = uwo.Commit();
                }

            }
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除数据源
        /// </summary>
        /// <param name="id">主键</param>
        public async Task<Response<bool>> DeleteEntity(string id)
        {
            SysGroup entity = new SysGroup()
            {
                Id = id
            };
            var flag = await this.Repository.DeleteAsync(entity);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 为分组分配用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AssignGroupUser(GroupUserReq model)
        {
            using (var uwo = UnitWork.CreateContext())
            {
                await uwo.SysGroupuser.DeleteAsync(a => a.GroupId == model.GroupId);
                var group = client.Queryable<SysGroup>().Where(r => r.Id == model.GroupId).First();
                if (group != null)
                {
                    model.UserIds.Add(group.GroupLeaderId);
                }
                var data = client.Queryable<SysGroupuser>()
                    .LeftJoin<SysUser>((r,u)=>r.UserId==u.Id.ToString())
                    .Where((r, u) => model.UserIds.Contains(r.UserId)&&r.GroupId!=model.GroupId)
                    .Select((r, u) => u)
                    .ToList();
                if (data.Count > 0)
                {
                    var names = string.Join(", ", data.Select(r => r.Name));
                    throw new Exception("成员" + names + "已分配小组，勿重复分配");
                }
                await uwo.SysGroupuser.DeleteAsync(r => r.GroupId == model.GroupId);
                await uwo.SysGroupuser.InsertRangeAsync(model.UserIds.Distinct().Select(a => new SysGroupuser { GroupId = model.GroupId, UserId = a }).ToList());
                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

        /// <summary>
        /// 获取小组下的成员信息
        /// </summary>
        /// <param name="groupid"></param>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<SysUser>>>> LoadUserListByGroupid(string groupid,string keyword, int pageindex, int pagesize)
        {
            //定义且实例化分页数据
            RefAsync<int> totalCount = 0;
            //数据查询并返回
            var info = await client.Queryable<SysGroupuser>()
                .Where(r=>r.GroupId==groupid)
                .LeftJoin<SysUser>((r,u)=>r.UserId==u.Id.ToString())
                .WhereIF(!string.IsNullOrEmpty(keyword), (r, u) => u.Name.Contains(keyword))
                .OrderBy((r, u) => u.Name)
                .Select((r,u)=>u)
                .ToPageListAsync(pageindex, pagesize, totalCount);
            return new Response<PageInfo<List<SysUser>>>
            {
                Result = new PageInfo<List<SysUser>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }
    }
}
