using RFrameGenerate.Model;
using RFramework.SQLServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RFrameGenerate.BLL
{
    public class LevelManage
    {
        public static List<T_BAS_Level> GetPageList(GridModel gridModel)
        {
            using (var query = Factory.CreateT_BAS_Level())
            {
                return query.GetPageList(gridModel, a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid()&&a.IsActive==true, false, a => a.LevelName, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default,false);
            }
        }

        public static Result AddLevel(T_BAS_Level entity)
        {
            using (var query = Factory.CreateT_BAS_Level())
            {
                try
                {
                    if (!query.IsExist(a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid() && a.LevelName == entity.LevelName))
                    {
                        entity.LevelGuid = Guid.NewGuid();
                        entity.IsActive = true;
                        entity.AgentGuid = RFrameGenerate.Common.CurrentUser.GetCurrUserGuid();
                        query.Add(entity);
                        return new Result(true);
                    }
                    else
                    {
                        return new Result(false, entity.LevelName + "已存在");
                    }
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        public static Result DeleteEntity(Guid LevelGuid)
        {
            if (LevelGuid == Guid.Empty) return new Result(false, "没有数据删除！");

            using (var tran=new SqlRTransaction())
            {
                var queryAgent = Factory.CreateT_BAS_Agents(tran);
                if (queryAgent.IsExist(a => a.LevelGuid == LevelGuid) == true)
                    return new Result(false, "无法删除,已有代理商使用了该级别!");

                var query = Factory.CreateT_BAS_Level(tran);
                query.Delete(a => a.LevelGuid == LevelGuid);
            }
            return new Result(true);
        }

        public static string GetLevelName(Guid levelGuid)
        {
            using (var query = Factory.CreateT_BAS_Level())
            {
                var level = query.GetFirstData(a => a.LevelGuid == levelGuid);
                if (level != null)
                    return level.LevelName;
                else
                    return "";
            }
        }

        public static List<T_BAS_Level> GetList()
        {
            using(var query=Factory.CreateT_BAS_Level())
            {
                return query.GetList(a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid()&&a.IsActive==true, false);
            }
        }
    }
}
