using AutoMapper;
using OASystem.Domain;
using OASystem.Domain.Dtos.Resource;
using OASystem.Domain.Dtos.System;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.Entities.System;
using OASystem.Domain.ViewModels.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.System
{
    public class SetDataTypeRepository : BaseRepository<Sys_SetDataType, SetDataTypeView>
    {
        private readonly IMapper _mapper;
        public SetDataTypeRepository(SqlSugarClient sqlSugar, IMapper mapper) : base(sqlSugar)
        {
            _mapper = mapper;
        }
        /// <summary>
        /// 数据类型种类修改添加操作
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> OperationSetDataType(OperationSetDataTypeDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                if (dto.Status == 1)//添加
                {
                    string selectSql = string.Format(@"select * from Sys_SetDataType where Name='{0}' and IsDel='{1}'"
                                                       , dto.Name, 0);
                    var SetDataType = await _sqlSugar.SqlQueryable<Sys_SetDataType>(selectSql).FirstAsync();//查询是否存在
                    if (SetDataType != null)
                    {
                        return result = new Result() { Code = -1, Msg = "该信息已存在，请勿重复添加！" };

                    }
                    else//不存在，可添加
                    {
                        Sys_SetDataType _SetDataType = _mapper.Map<Sys_SetDataType>(dto);
                        int id = await AddAsyncReturnId(_SetDataType);
                        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_SetDataType
                    {
                        Name = dto.Name,
                        IsEnable = dto.IsEnable,
                        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;
        }

        /// <summary>
        /// 查询数据类型种类
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> QuerySetDataType(SetDataTypeDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                string sqlWhere = string.Empty;
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    sqlWhere += string.Format(@" And s.Name like '%{0}%'", dto.Name);
                }
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    sqlWhere += string.Format(@" And u.CnName like '%{0}%'", dto.Name);
                }
                sqlWhere += string.Format(@" And s.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 s.*,u.CnName from Sys_SetDataType s left join Sys_Users u on s.CreateUserId=u.Id  {0}", sqlWhere);
                    List<SetDataTypeView> SetDataType = await _sqlSugar.SqlQueryable<SetDataTypeView>(sql).ToListAsync();
                    if (SetDataType.Count == 0)
                    {
                        return result = new Result() { Code = -1, Msg = "暂无数据" };
                    }
                    SetDataType = SetDataType.OrderByDescending(x => x.CreateTime).ToList();

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

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

                }
                else if (dto.PortType == 2)
                {
                    string sql = string.Format(@"select s.*,u.CnName from Sys_SetDataType s left join Sys_Users u on s.CreateUserId=u.Id  {0}", sqlWhere);
                    List<SetDataTypeView> SetDataType = await _sqlSugar.SqlQueryable<SetDataTypeView>(sql).ToListAsync();
                    if (SetDataType.Count == 0)
                    {
                        return result = new Result() { Code = -1, Msg = "暂无数据" };
                    }
                    SetDataType = SetDataType.OrderByDescending(x => x.CreateTime).ToList();

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

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

}
