using Edu.Common.Enum;
using Edu.Model.Entity.WeChat;
using Edu.Model.ViewModel.WeChat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB.Dapper;

namespace Edu.Repository.WeChat
{
    /// <summary>
    /// 企业微信客户字段仓储层
    /// </summary>
    public class RB_WeChat_CustomerFieldRepository : BaseRepository<RB_WeChat_CustomerField>
    {

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_CustomerField_ViewModel> GetList(RB_WeChat_CustomerField_ViewModel demodel)
        {
            DynamicParameters parameters = new DynamicParameters();
            string where = $@" 1=1 and r.{nameof(RB_WeChat_CustomerField_ViewModel.Status)} =0";
            if (demodel.Group_Id > 0)
            {
                where += $@" and r.{nameof(RB_WeChat_CustomerField_ViewModel.Group_Id)} ={demodel.Group_Id}";
            }
            if (demodel.Enable > 0)
            {
                where += $@" and r.{nameof(RB_WeChat_CustomerField_ViewModel.Enable)} ={demodel.Enable}";
            }
            if (demodel.Type > 0)
            {
                where += $@" and r.{nameof(RB_WeChat_CustomerField_ViewModel.Type)} ={(int)demodel.Type}";
            }
            if (!string.IsNullOrEmpty(demodel.CName))
            {
                where += $@" and r.{nameof(RB_WeChat_CustomerField_ViewModel.Name)} ='{demodel.CName}'";
            }
            if (!string.IsNullOrEmpty(demodel.Name))
            {
                where += $@" and r.{nameof(RB_WeChat_CustomerField_ViewModel.Name)} like @Name";
                parameters.Add("Name", "%" + demodel.Name + "%");
            }

            string sql = $@" 
SELECT * From RB_WeChat_CustomerField r
WHERE {where} 
ORDER BY r.Sort asc, r.Id asc ";
            return Get<RB_WeChat_CustomerField_ViewModel>(sql, parameters).ToList();
        }

        /// <summary>
        /// 获取最大排序
        /// </summary>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public int GetSortMax(int group_Id)
        {
            string sql = $@" select Max(Sort) from RB_WeChat_CustomerField where Group_Id ={group_Id}";
            var obj = ExecuteScalar(sql);
            return obj == null ? 0 : Convert.ToInt32(obj);
        }

        /// <summary>
        /// 此排序后面的字段排序都加1
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public bool SetSortNumAdd(int sort, int group_Id)
        {
            string sql = $@" update RB_WeChat_CustomerField set Sort = Sort +1 where Group_Id ={group_Id} and Sort >{sort}";
            return Execute(sql) > 0;
        }
    }
}
