using Infrastructure;
using Infrastructure.Extensions;
using OpenAuth.App.Base;
using OpenAuth.App.FormScheme.FormHelpers;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenAuth.App.BaseApp.Base;

namespace OpenAuth.App.DataSource
{
    public class DataSourceApp : SqlSugarBaseApp<Repository.Domain.DataSource, SugarDbContext>
    {
        public DataSourceApp(ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<Repository.Domain.DataSource> repository)
            : base(unitWork, repository, null)
        {

        }
        /// <summary>
        /// 分页获取列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<Repository.Domain.DataSource>>>> LoadDataSourceList(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<Repository.Domain.DataSource>>>
            {
                Result = new PageInfo<List<Repository.Domain.DataSource>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="code">编码</param>
        /// <returns></returns>
        public Task<Repository.Domain.DataSource> GetEntityByCode(string code)
        {
            return this.Repository.AsQueryable().FirstAsync(t => t.Code == code);
        }
        /// <summary>
        /// 获取sql的列
        /// </summary>
        /// <param name="code">编码</param>
        /// <returns></returns>
        public async Task<Response<List<string>>> GetDataColName(string code)
        {
            Repository.Domain.DataSource entity = await GetEntityByCode(code);
            if (entity == null || string.IsNullOrEmpty(entity.Sql) || !entity.Sql.Contains("select"))
            {
                return new Response<List<string>>();
            }
            else
            {
                string sql = entity.Sql;
                sql = sql.Replace("={userId}", " is not null ");
                sql = sql.Replace("={userAccount}", " is not null");
                sql = sql.Replace("={companyId}", " is not null");
                sql = sql.Replace("={departmentId}", " is not null");

                sql = sql.Replace("= {userId}", " is not null ");
                sql = sql.Replace("= {userAccount}", " is not null");
                sql = sql.Replace("= {companyId}", " is not null");
                sql = sql.Replace("= {departmentId}", " is not null");

                sql = sql.Replace("=@param", " is not null");
                sql = sql.Replace("= @param", " is not null");
                using (SugarDbContext db = base.UnitWork.CreateContext())
                {
                    DataTable dt = await db.Db.SqlQueryable<object>(sql).ToDataTablePageAsync(1, 1);
                    List<string> res = new List<string>();
                    foreach (DataColumn item in dt.Columns)
                    {
                        res.Add(item.ColumnName.ToLower());
                    }
                    return new Response<List<string>>
                    {
                        Result = res
                    };
                }

            }

        }
        /// <summary>
        /// 保存（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="dataSourceEntity">数据源实体</param>
        /// <returns></returns>
        public async Task<Response<bool>> SaveEntity(string keyValue, Repository.Domain.DataSource dataSourceEntity)
        {
            var flag = false;
            dataSourceEntity.Sql = FormHelper.SqlFilters(dataSourceEntity.Sql);
            if (!string.IsNullOrEmpty(keyValue))
            {
                Repository.Domain.DataSource entity = await this.Repository.GetFirstAsync(t => t.Code == dataSourceEntity.Code && t.Id != keyValue);
                if (entity != null)
                {
                    return new Response<bool>
                    {
                        Result = flag,
                        Message = flag == true ? "success" : "error"
                    };
                }
                dataSourceEntity.Id = keyValue;
                dataSourceEntity.ModifyDate = DateTime.Now;
                dataSourceEntity.ModifyUserId = dataSourceEntity.ModifyUserId;
                dataSourceEntity.ModifyUserName = dataSourceEntity.ModifyUserName;
                flag = await this.Repository.UpdateAsync(dataSourceEntity);
            }
            else
            {
                Repository.Domain.DataSource entity = await GetEntityByCode(dataSourceEntity.Code);
                if (entity != null)
                {
                    return new Response<bool>
                    {
                        Result = flag,
                        Message = flag == true ? "success" : "error"
                    };
                }
                dataSourceEntity.Id = Guid.NewGuid().ToString();
                dataSourceEntity.CreateDate = DateTime.Now;
                dataSourceEntity.CreateUserId = dataSourceEntity.CreateUserId;
                dataSourceEntity.CreateUserName = dataSourceEntity.CreateUserName;
                flag = await this.Repository.InsertAsync(dataSourceEntity);
            }
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

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