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

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

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

                    }
                    else//不存在，可添加
                    {
                        Sys_PageFunctionPermission Function = _mapper.Map<Sys_PageFunctionPermission>(dto);
                        int id = await AddAsyncReturnId(Function);
                        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_PageFunctionPermission
                    {
                        FunctionName=dto.FunctionName,
                        FunctionCode=dto.FunctionCode,
                        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;
        }
    }
}
