
using AutoMapper;
using OASystem.Domain;
using OASystem.Domain.Dtos.System;
using OASystem.Domain.Dtos.UserDto;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.Entities.System;
using OASystem.Domain.ViewModels.System;

namespace OASystem.Infrastructure.Repositories.System
{
    public class SetDataRepository : BaseRepository<Sys_SetData, SetDataView>
    {
        private readonly IMapper _mapper;
        public SetDataRepository(SqlSugarClient sqlSugar, IMapper mapper) : base(sqlSugar)
        {
            _mapper = mapper;
        }

        /// <summary>
        /// 获取所有系统模块
        /// </summary>
        /// <param name="_SetData"></param>
        /// <returns></returns>
        public async Task<Result> GetSySDefultModule()
        {
            Result result = new Result();
            string sql = "select * from Sys_SetData where STid = 5 and isdel = 0";
            var DBdata = await GetListBySqlWithNolockAsync(sql);

            if (DBdata == null || DBdata.Count == 0)
            {
                return result;
            }

            result.Data = DBdata.Select(x=> new SetDataView
            {
                 Name = x.Name,
                 STid = x.STid,
                 Id = x.Id,
            });

            result.Code = 0;
            result.Msg = "成功！";

            return result;
        }

        /// <summary>
        /// 获取类型Data By STId
        /// </summary>
        /// <param name="_SetData"></param>
        /// <returns></returns>
        public async Task<Result> GetSetDataBySTId(SetDataRepository _SetData,int stId)
        {
            Result result = new Result();
            string sql = string.Format(@"select * from Sys_SetData where STid = {0} and isdel = 0",stId);
            var DBdata = await _SetData.GetListBySqlWithNolockAsync(sql);

            if (DBdata == null || DBdata.Count == 0)
            {
                return result;
            }

            result.Data = DBdata.Select(x => new SetDataInfoView
            {
                Name = x.Name,
                Id = x.Id,
                Remark = x.Remark,
            });

            result.Code = 0;
            result.Msg = "成功！";

            return result;
        }


        public async Task<Result> GetSetDataAndPageInfoBySTId(int stId = 5)
        {
            Result result = new Result();
            List<SetDataAndPageInfoView> ViewList = _sqlSugar.SqlQueryable<SetDataAndPageInfoView>($@"
                select a.id as modulid,a.Name as modulName,a.STid,a.Remark as modulRemark,
                b.Id as pageid, b.Name as pageName, b.IsEnable as PageIsEnable  ,b.phoneIsEnable as PagePhoneIsEnable,b.SystemMenuCode,b.webUrl,b.androidUrl,
                b.iosUrl,b.icon ,b.Remark as PageRemark
                from Sys_SetData a , Sys_SystemMenuPermission b where STid = {stId} 
                and a.isdel = 0 and b.Mid = a.Id  and b.IsDel = 0
            ").ToList();

            result.Data = ViewList;
            result.Code = 0;
            result.Msg = "成功！";

            if (ViewList == null || ViewList.Count == 0)
            {
                result.Msg = "无数据！";
                result.Code = -1;
            }

            return result;
        }

        public async Task<Result> QuerySetData(SetDataIDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                string sqlWhere = string.Empty;
                if (dto.STid!=0)
                {
                    sqlWhere += string.Format(@" And s2.STid ={0}=", dto.STid);
                }
                sqlWhere += string.Format(@" And s1.IsDel={0} And  s2.IsDel={0}", 0);
                if (!string.IsNullOrEmpty(sqlWhere.Trim()))
                {
                    Regex r = new Regex("And");
                    sqlWhere = r.Replace(sqlWhere, "Where", 1);
                }
                if (dto.PortType == 1)
                {
                    string sql = string.Format(@"select s2.*,s1.Name as 'StName',u.CnName from Sys_setDataType s1 left join Sys_SetData s2 on s1.Id=s2.STid left join Sys_Users u on s2.CreateUserId=u.Id {0}", sqlWhere);
                    List<SetDataIView> SetData = await _sqlSugar.SqlQueryable<SetDataIView>(sql).ToListAsync();
                    if (SetData.Count == 0)
                    {
                        return result = new Result() { Code = -1, Msg = "暂无数据" };
                    }
                    SetData = SetData.OrderByDescending(x => x.CreateTime).ToList();

                    if (dto.PageSize == 0 && dto.PageIndex == 0)
                    {
                        return result = new Result()
                        {
                            Code = 0,
                            Msg = "查询成功",
                            Data = SetData,
                        };
                    }
                    else
                    {
                        int count = SetData.Count;
                        float totalPage = (float)count / dto.PageSize;//总页数
                        if (totalPage == 0) totalPage = 1;
                        else totalPage = (int)Math.Ceiling((double)totalPage);

                        List<SetDataIView> _SetData = new List<SetDataIView>();
                        for (int i = 0; i < dto.PageSize; i++)
                        {
                            var RowIndex = i + (dto.PageIndex - 1) * dto.PageSize;
                            if (RowIndex < SetData.Count)
                            {
                                _SetData.Add(SetData[RowIndex]);
                            }
                            else
                            {
                                break;
                            }
                        }
                        return result = new Result()
                        {
                            Code = 0,
                            Msg = "查询成功",
                            Data = new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = _SetData },
                        };
                    }

                }
                else if (dto.PortType == 2)
                {
                    string sql = string.Format(@"select s2.*,s1.Name as 'StName' from Sys_setDataType s1 left join Sys_SetData s2 on s1.Id=s2.STid {0}", sqlWhere);
                    List<SetDataIView> SetData = await _sqlSugar.SqlQueryable<SetDataIView>(sql).ToListAsync();
                    if (SetData.Count == 0)
                    {
                        return result = new Result() { Code = -1, Msg = "暂无数据" };
                    }
                    SetData = SetData.OrderByDescending(x => x.CreateTime).ToList();

                    if (dto.PageSize == 0 && dto.PageIndex == 0)
                    {
                        return result = new Result()
                        {
                            Code = 0,
                            Msg = "查询成功",
                            Data = SetData,
                        };
                    }
                    else
                    {
                        int count = SetData.Count;
                        float totalPage = (float)count / dto.PageSize;//总页数
                        if (totalPage == 0) totalPage = 1;
                        else totalPage = (int)Math.Ceiling((double)totalPage);

                        List<SetDataIView> _SetData = new List<SetDataIView>();
                        for (int i = 0; i < dto.PageSize; i++)
                        {
                            var RowIndex = i + (dto.PageIndex - 1) * dto.PageSize;
                            if (RowIndex < SetData.Count)
                            {
                                _SetData.Add(SetData[RowIndex]);
                            }
                            else
                            {
                                break;
                            }
                        }
                        return result = new Result()
                        {
                            Code = 0,
                            Msg = "查询成功",
                            Data = new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = _SetData },
                        };
                    }
                }
                else
                {
                    return result = new Result() { Code = -2, Msg = "请传入PortType参数！1:Web，2:Android,3:IOS" };
                }
            }
            catch (Exception)
            {
                return result;
                throw;
            }
        }

        public async Task<Result> OperationSetData(OperationSetDataDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                if (dto.Status == 1)//添加
                {
                    string selectSql = string.Format(@"select * from Sys_SetData where Name='{0}' and IsDel='{1}'"
                                                       , dto.Name, 0);
                    var SetData = await _sqlSugar.SqlQueryable<Sys_SetData>(selectSql).FirstAsync();//查询是否存在
                    if (SetData != null)
                    {
                        return result = new Result() { Code = -1, Msg = "该信息已存在，请勿重复添加！" };

                    }
                    else//不存在，可添加
                    {
                        Sys_SetData _SetData = _mapper.Map<Sys_SetData>(dto);
                        int id = await AddAsyncReturnId(_SetData);
                        if (id == 0)
                        {
                            return result = new Result() { Code = -1, Msg = "添加失败！" };

                        }
                        result = new Result() { Code = 0, Msg = "添加成功！", Data = new { Id = id } };
                    }
                }
                else if (dto.Status == 2)//修改
                {
                    bool res = await UpdateAsync(a => a.Id == dto.Id, a => new Sys_SetData
                    {
                        Name = dto.Name,
                        STid = dto.STid,
                        Remark = dto.Remark,
                    });
                    if (!res)
                    {
                        return result = new Result() { Code = -1, Msg = "修改失败！" };
                    }
                    result = new Result() { Code = 0, Msg = "修改成功！" };
                }
                else
                {
                    return result = new Result() { Code = -1, Msg = "请传入Status参数，1添加 2修改！" };
                }
            }
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "程序错误！" };
            }
            return result;
        }
    }
}
