using System.Collections.Generic;
using Mall.DataAccess;

namespace DapperExtensions.Sql
{
    /// <summary>
    /// MySql语句配置扩展类
    /// </summary>
    public class MySqlDialect : SqlDialectBase
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public MySqlDialect()
        {
            DBType = DataBaseType.MySql;
        }

        /// <summary>
        /// 开始字符
        /// </summary>
        public override char OpenQuote
        {
            get { return '`'; }
        }

        /// <summary>
        /// 结束字符
        /// </summary>
        public override char CloseQuote
        {
            get { return '`'; }
        }

        /// <summary>
        /// 或自增sql
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public override string GetIdentitySql(string tableName)
        {
            return "SELECT CONVERT(LAST_INSERT_ID(), SIGNED INTEGER) AS ID";
        }

        /// <summary>
        /// 分页sql
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="page">页码</param>
        /// <param name="resultsPerPage">每页条数</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary<string, object> parameters)
        {
            if (page <= 0)
            {
                page = 1;
            }
            int startValue = (page - 1) * resultsPerPage;
            return GetSetSql(sql, startValue, resultsPerPage, parameters);
        }

        /// <summary>
        /// 设置sql语句
        /// </summary>
        /// <param name="sql">sql命令</param>
        /// <param name="firstResult">最小值</param>
        /// <param name="maxResults">最大值</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary<string, object> parameters)
        {
            string result = string.Format("{0} LIMIT @firstResult, @maxResults", sql);
            parameters.Add("@firstResult", firstResult);
            parameters.Add("@maxResults", maxResults);
            return result;
        }
    }
}