using Infrastructure;
using OpenAuth.App.Base;
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;
using OpenAuth.App.BaseApp.Base;

namespace OpenAuth.App
{
    public class WFDelegateApp : SqlSugarBaseApp<WFDelegateRule, SugarDbContext>
    {
        ISqlSugarClient client;
        public WFDelegateApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<WFDelegateRule> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            client = base.Repository.AsSugarClient();
        }


        #region 获取数据
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryParams">查询参数</param>
        /// <returns></returns>
        public async Task<PageInfo<List<WFDelegateRule>>> GetPageList(PageReq pageReq, WFDelegateRule queryParams)
        {
            RefAsync<int> totalCount = 0;
            var userId = _auth.GetUserId();
            var exp = Expressionable.Create<WFDelegateRule>()
                .AndIF(!string.IsNullOrEmpty(queryParams.ToUserName), t => t.ToUserName.Contains(queryParams.ToUserName))
                .AndIF(queryParams.EnabledMark != null, t => t.EnabledMark == queryParams.EnabledMark)
                .AndIF(queryParams.Type != null, t => t.Type == queryParams.Type)
                .And(t => t.CreateUserId == userId).ToExpression();

            var list = await client.Queryable<WFDelegateRule>().Where(exp)
                .ToPageListAsync(pageReq.page, pageReq.limit, totalCount);
            return new PageInfo<List<WFDelegateRule>>
            {
                Items = list,
                Total = totalCount
            };

        }
        /// <summary>
        /// 根据委托人获取委托记录
        /// </summary>
        /// <param name="type">0 审核委托 1发起委托</param>
        /// <returns></returns>
        public Task<IEnumerable<WFDelegateRule>> GetList(int type = 0) { return null; }
        /// <summary>
        /// 获取关联的模板数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<WFDelegateRelation>> GetRelationList(string keyValue)
        {
            return await client.Queryable<WFDelegateRelation>().Where(a => a.DelegateRuleId == keyValue).ToListAsync();
        }
        /// <summary>
        /// 获取委托信息
        /// </summary>
        /// <returns></returns>
        public Task<WFDelegateRule> Get(string keyValue) { return null; }
        /// <summary>
        ///  获取我的委托人（发起委托）
        /// </summary>
        /// <param name="code">流程模板编码</param>
        /// <returns></returns>
        public async Task<List<SysUser>> GetMyUserList(string code)
        {
            var list = new List<string>();
            var userInfo = base._auth.GetCurrentUser().User;
            var listTmp = await GetMyUserList(userInfo, code);
            var dic = new Dictionary<string, bool>();
            foreach (var item in listTmp)
            {
                if (!dic.ContainsKey(item.CreateUserId))
                {
                    dic.Add(item.CreateUserId, true);
                    list.Add(item.CreateUserId);
                }
            }
            if (list.Count > 0)
            {
                return await client.Queryable<SysUser>().Where(t => list.Contains(t.Id.ToString())).ToListAsync();
            }
            else
            {
                return new List<SysUser>();
            }
        }

        public async Task<WFDelegateRule> GetEntity(string keyValue)
        {
            return await base.Repository.GetByIdAsync(keyValue);
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        public async Task<Response<bool>> DeleteEntity(string keyValue)
        {
            using (var uwo = UnitWork.CreateContext())
            {
                await uwo.WFDelegateRule.DeleteByIdAsync(keyValue);
                await uwo.WFDelegateRelation.DeleteAsync(t => t.DelegateRuleId == keyValue);

                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }
        /// <summary>
        /// 保存实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="wfDelegateRule">实体数据</param>
        /// <param name="schemeInfoList">关联模板主键</param>
        public async Task<Response<bool>> SaveEntity(string keyValue, WFDelegateRule wfDelegateRuleEntity, string[] schemeInfoList)
        {
            using (var uwo = UnitWork.CreateContext())
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    wfDelegateRuleEntity.Id = Guid.NewGuid().ToString();
                    wfDelegateRuleEntity.CreateDate = DateTime.Now;
                    wfDelegateRuleEntity.EnabledMark = 1;
                    wfDelegateRuleEntity.CreateUserId = _auth.GetUserId();
                    wfDelegateRuleEntity.CreateUserName = _auth.GetUserName();

                    await uwo.WFDelegateRule.InsertAsync(wfDelegateRuleEntity);
                }
                else
                {
                    wfDelegateRuleEntity.Id = keyValue;
                    await uwo.WFDelegateRule.UpdateAsync(wfDelegateRuleEntity);
                    await uwo.WFDelegateRelation.DeleteAsync(t => t.DelegateRuleId == keyValue);
                }

                foreach (string schemeInfoId in schemeInfoList)
                {
                    WFDelegateRelation wfDelegateRuleRelationEntity = new WFDelegateRelation();
                    wfDelegateRuleRelationEntity.Id = Guid.NewGuid().ToString();
                    wfDelegateRuleRelationEntity.DelegateRuleId = wfDelegateRuleEntity.Id;
                    wfDelegateRuleRelationEntity.SchemeInfoId = schemeInfoId;
                    await uwo.WFDelegateRelation.InsertAsync(wfDelegateRuleRelationEntity);
                }

                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }
        /// <summary>
        /// 更新委托规则状态信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="state"></param>
        public async Task<Response<bool>> UpdateState(string keyValue, int state)
        {
            var flag = await base.Repository.UpdateSetColumnsTrueAsync(a => new WFDelegateRule { EnabledMark = state }, a => a.Id == keyValue);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }
        #endregion


        public async Task<IEnumerable<WFDelegateRule>> GetMyUserList(SysUser userInfo, string code)
        {
            string userId = userInfo.Id.ToString();
            DateTime datetime = DateTime.Now;

            var queryable = client.Queryable<WFDelegateRule>()
                   .LeftJoin<WFDelegateRelation>((rule, r) => rule.Id == r.DelegateRuleId);
            var exp = Expressionable.Create<WFDelegateRule, WFDelegateRelation>()
            .And((rule, r) => rule.ToUserId == userId && rule.Type == 1 && r.SchemeInfoId == code)
            .And((rule, r) => rule.BeginDate <= datetime && rule.EndDate >= @datetime)
            .ToExpression();
            return await queryable.Where(exp).Select((rule, r) => rule).ToListAsync();

        }
    }
}
